Skip to content

Automate browser based workflows with AI

Record how each Task V3 tool call addressed its target, and why it failed (#8505)

pedrohsdbf1a1d8eac252
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index 037e79ee2..e36ce121a 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -174,6 +174,7 @@ from skyvern.forge.sdk.workflow.models.block import (
_task_block_supports_v3,
)
from skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowRun, WorkflowRunStatus
+from skyvern.forge.taskv3.frame_perception import frame_perception_enabled, resolve_frame_perception
from skyvern.forge.taskv3.loop import LoopOutcome, RoundAction
from skyvern.forge.taskv3.pre_submit_capture import PreSubmitCaptureRing, is_run_sampled, pre_submit_screenshot
from skyvern.forge.taskv3.target_label import compose_target_intention
@@ -1786,6 +1787,16 @@ class ForgeAgent:
llm_caller = LLMCaller(llm_key=await _resolve_task_v3_llm_key(task))
parameters = coerce_v3_parameters(task.navigation_payload)
context = skyvern_context.current()
+ if context:
+ # Once for the whole run, before anything reads it: the tool list bakes one of these
+ # reads into the observe description at build time, and a value that could change
+ # afterwards would leave that description describing a different run than the one
+ # executing.
+ await resolve_frame_perception(
+ context,
+ distinct_id=task.workflow_run_id or task.task_id,
+ organization_id=task.organization_id,
+ )
offer_error_codes = False
if task.error_code_mapping:
try:
@@ -2213,7 +2224,7 @@ class ForgeAgent:
if peek is None:
return None
own = await peek.evaluate(_PAGE_FINGERPRINT_PROBE_JS)
- if not settings.TASK_V3_FRAME_PERCEPTION:
+ if not frame_perception_enabled():
return own
# The completion-side settle deferral rides this, and it is a LIVE gate rather than only the
# shadow stall measurement: a main-frame-only fingerprint reads a page whose child frame is
diff --git a/skyvern/forge/sdk/core/skyvern_context.py b/skyvern/forge/sdk/core/skyvern_context.py
index 9498f2810..29a33ad85 100644
--- a/skyvern/forge/sdk/core/skyvern_context.py
+++ b/skyvern/forge/sdk/core/skyvern_context.py
@@ -396,6 +396,18 @@ class SkyvernContext:
workflow_block_engine_resolved_run_id: str | None = None
# Single-flight the first-use provider resolution when parallel branches share one context.
workflow_block_engine_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
+ # TASK_V3_FRAME_PERCEPTION arm, resolved once per run before the v3 loop starts; read through
+ # frame_perception_enabled(), never directly. The flag is written before the run-id sentinel, so
+ # a concurrent reader sees "unresolved" -- off, today's behaviour -- rather than a torn pair.
+ frame_perception_flag: bool = False
+ # The run the pin above was resolved for; a nested execution with a different id re-resolves.
+ # Last writer wins with no save/restore, so this prevents inheriting an unchecked arm but would
+ # not isolate two interleaved runs sharing one context, which nothing constructs today.
+ frame_perception_resolved_run_id: str | None = None
+ # Single-flight the first resolution when parallel branches share one context. Without it both
+ # branches pass the sentinel check, and the second -- which answers False on any provider
+ # failure -- overwrites the arm the first already baked into its observe description.
+ frame_perception_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
enrich_tree_mode: EnrichTreeMode = EnrichTreeMode.CONTROL
step_retry_index: int = 0
diff --git a/skyvern/forge/taskv3/engine.py b/skyvern/forge/taskv3/engine.py
index 0fe5486e5..871026ee0 100644
--- a/skyvern/forge/taskv3/engine.py
+++ b/skyvern/forge/taskv3/engine.py
@@ -34,6 +34,7 @@ from skyvern.forge.sdk.api.llm.api_handler_factory import VISION_FALLBACK_PROMPT
from skyvern.forge.sdk.api.llm.exceptions import LLMProviderErrorRetryableTask
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.taskv3.code_surface import apply_surface, configured_surface
+from skyvern.forge.taskv3.frame_perception import frame_perception_enabled
from skyvern.forge.taskv3.goal_composition import build_user_prompt
from skyvern.forge.taskv3.llm_call_params import build_call_kwargs
from skyvern.forge.taskv3.loop import (
@@ -276,7 +277,7 @@ async def run_task_v3_agent_loop(
code_tool: ToolSpec | None = None
if code_surface.offers_code_tool and not page_free:
execution_id = (_ctx.run_id or _ctx.workflow_run_id or _ctx.task_id or "") if _ctx else ""
- if settings.TASK_V3_FRAME_PERCEPTION:
+ if frame_perception_enabled():
# The realm-attributed ledger behind the data-loss guard and the completion gate is
# written only by the native action tools' wrapper. Code driving the page directly
# bypasses it, so in-frame fills and submits would be invisible to both -- worst under
diff --git a/skyvern/forge/taskv3/frame_perception.py b/skyvern/forge/taskv3/frame_perception.py
new file mode 100644
index 000000000..8d95c7cba
--- /dev/null
+++ b/skyvern/forge/taskv3/frame_perception.py
@@ -0,0 +1,82 @@
+"""Per-run resolution of the frame-perception arm.
+
+`TASK_V3_FRAME_PERCEPTION` gates reading, acting in and verifying inside child frames as one
+unit. It shipped as an env setting alone, so the only way to enable it for any traffic was to
+enable it for all of it. This resolves it per run instead, and every site that used to read the
+setting directly reads `frame_perception_enabled()`.
+"""
+
+from __future__ import annotations
+
+import structlog
+
+from skyvern.config import settings
+from skyvern.forge import app
+from skyvern.forge.sdk.core import skyvern_context
+from skyvern.forge.sdk.experimentation.providers import NoOpExperimentationProvider
+
+LOG = structlog.get_logger()
+
+FRAME_PERCEPTION_FLAG = "TASK_V3_FRAME_PERCEPTION"
+
+
+async def resolve_frame_perception(
+ context: skyvern_context.SkyvernContext,
+ *,
+ distinct_id: str,
+ organization_id: str | None,
+) -> None:
+ """Resolve the arm once per run and pin it on the context; off is the outcome of every failure.
+
+ The pin is what makes the observe tool's build-time read agree with every other consumer's
+ per-call read, so a cache expiry or mid-run ramp cannot flip the arm under a running loop --
+ see `cloud_docs/feature-flags/task-v3-frame-perception.md` for the two terms, the durability
+ caveat and why this resolves even when the env setting already forced the arm on.
+ """
+ if context.frame_perception_resolved_run_id == distinct_id:
+ return
+ async with context.frame_perception_lock:
+ # Re-checked under the lock: parallel branches sharing this context both pass the check
+ # above, and the loser must inherit the winner's arm rather than overwrite it.
+ if context.frame_perception_resolved_run_id == distinct_id:
+ return
+ enabled = False
+ try:
+ provider = app.EXPERIMENTATION_PROVIDER
+ # No experimentation configured (OSS default) -> off, and never query the provider.
+ if not isinstance(provider, NoOpExperimentationProvider):
+ enabled = await provider.is_feature_enabled_cached(
+ FRAME_PERCEPTION_FLAG,
+ distinct_id,
+ properties={"organization_id": organization_id},
+ )
+ except Exception:
+ LOG.warning("Failed to resolve TASK_V3_FRAME_PERCEPTION feature flag", exc_info=True)
+ enabled = False
+ context.frame_perception_flag = enabled
+ context.frame_perception_resolved_run_id = distinct_id
+ LOG.info(
+ "Resolved frame perception arm",
+ distinct_id=distinct_id,
+ # The provider's own resolution record carries the FLAG, which reads false for a run the env
+ # setting forced on. An operator watching a ramp needs the arm the run actually took.
+ frame_perception=settings.TASK_V3_FRAME_PERCEPTION or enabled,
+ flag=enabled,
+ forced_by_env=settings.TASK_V3_FRAME_PERCEPTION,
+ )
+
+
+def frame_perception_enabled() -> bool:
+ """Whether this run reads, acts in and verifies inside child frames.
+
+ The env setting is the force-on term and short-circuits before the pin, so an unresolved run
+ reads it alone. Takes no run id, so unlike ``workflow_block_engine_override`` this is sound
+ only because every consumer sits inside ``_execute_task_v3`` -- the v1 step engine shares this
+ context, so give this an explicit run id before calling it from outside that call tree.
+ """
+ if settings.TASK_V3_FRAME_PERCEPTION:
+ return True
+ context = skyvern_context.current()
+ if context is None or context.frame_perception_resolved_run_id is None:
+ return False
+ return context.frame_perception_flag
diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.py
index 403ece192..572ca063e 100644
--- a/skyvern/forge/taskv3/loop.py
+++ b/skyvern/forge/taskv3/loop.py
@@ -21,6 +21,7 @@ import re
import secrets
import time
from collections import deque
+from contextvars import ContextVar
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Awaitable, Callable, Literal, NamedTuple, TypeVar
@@ -36,6 +37,36 @@ LOG = structlog.get_logger()
ToolStatus = Literal["ok", "error"]
FinishStatus = Literal["completed", "failed", "terminated"]
+# Why a failing tool call failed, as one closed vocabulary. Spelled as a `Literal` rather than `str`
+# because the whole value of the facet is that it is closed: it is written at ~28 sites across two
+# modules, and a typo or a near-synonym added later would split a cohort silently. mypy runs on both
+# modules, so a value not listed here is rejected at the call site rather than discovered in a chart.
+ToolErrorClass = Literal[
+ # The address did not resolve to what it named.
+ "stale_selector",
+ "invalid_selector",
+ "invalid_mark",
+ "ambiguous_selector",
+ "ambiguous_frame",
+ "stale_ref",
+ "ref_not_in_latest",
+ "stale_mark",
+ "mark_not_in_latest",
+ # The target resolved, but the page will not let the act happen.
+ "disabled",
+ "not_editable",
+ "covered",
+ "inert",
+ "unreachable",
+ # The handler raised instead of returning; classified by `_raised_error_class`.
+ "driver_timeout",
+ "timeout_other",
+ "handler_raised",
+ # An erroring call whose construction site named no class. Deliberately a value rather than an
+ # absence, so "errored, unnamed" is countable and cannot be confused with "did not error".
+ "other",
+]
+
@dataclass
class ToolResult:
@@ -46,14 +77,19 @@ class ToolResult:
# tool's annotated screenshot). Threaded into one .call()'s ephemeral screenshots= arg and never
# appended to the transcript, so it costs one image on one turn and is gone the turn after.
screenshots: list[bytes] | None = None
+ # Telemetry only, and deliberately NOT in `data`: callers and tests pin `data` by equality, so a
+ # measurement riding in it would change an observable contract. Never shown to the model.
+ error_class: ToolErrorClass | None = None
@classmethod
def ok(cls, content: str, data: dict[str, Any] | None = None, screenshots: list[bytes] | None = None) -> ToolResult:
return cls("ok", content, data, screenshots)
@classmethod
- def error(cls, content: str, data: dict[str, Any] | None = None) -> ToolResult:
- return cls("error", content, data)
+ def error(
+ cls, content: str, data: dict[str, Any] | None = None, *, error_class: ToolErrorClass | None = None
+ ) -> ToolResult:
+ return cls("error", content, data, error_class=error_class)
ToolHandler = Callable[[dict[str, Any]], Awaitable[ToolResult]]
@@ -65,6 +101,111 @@ ToolHandler = Callable[[dict[str, Any]], Awaitable[ToolResult]]
# lives in target_label.py; this module only carries the two raw values from probe to `RoundAction`.
TARGET_LABEL_DATA_KEY = "target_label"
TARGET_KIND_DATA_KEY = "target_kind"
+# How long a call spent turning an address into a target, before the act. A context variable rather
+# than a field on the result, because the cohort this exists to price is the one where the handler
+# RAISES -- a driver timeout on a resolved target -- and a result the handler never returned cannot
+# carry anything. Set before the handler runs, so the value survives whichever way the call ends.
+# Accumulated, because the mark wrapper resolves an address and the ref wrapper then runs inside it.
+#
+# WHAT ONE ROW MEANS, written here because a chart of this by `selector_kind` reads the field and
+# cannot see the branch that produced it:
+# absent no address was supplied. Its only meaning -- never "measured, and it was zero".
+# ref / mark the server-side table lookup and the frame routing it implies: the persistent-ref
+# model's own addressing cost, which is what this field exists to price.
+# css the frame ROUTING only, and only with frame perception ON. With it off, a plain
+# selector is resolved later, INSIDE the handler, so the row is ~0 and that
+# resolution is counted in `duration_seconds` instead.
+# Working-page acquisition is excluded on every branch: every design has to get the page, so it is
+# not a cost of the addressing model. Because the css meaning is the one that moves, every row that
+# carries this also carries `frame_perception` -- a dataset spanning the ramp otherwise mixes the two
+# definitions with nothing on the record to cut on.
+_RESOLVE_SECONDS: ContextVar[float | None] = ContextVar("taskv3_resolve_seconds", default=None)
+_FRAME_PERCEPTION: ContextVar[bool | None] = ContextVar("taskv3_frame_perception", default=None)
+
+
+def record_resolve_seconds(elapsed: float) -> None:
+ """Add `elapsed` to this tool call's address-resolution time. Telemetry only."""
+ _RESOLVE_SECONDS.set((_RESOLVE_SECONDS.get() or 0.0) + elapsed)
+
+
+def record_frame_perception(enabled: bool) -> None:
+ """Stamp which of the two definitions above produced this call's reading. Telemetry only."""
+ _FRAME_PERCEPTION.set(enabled)
+
+
+# What observe() prints and the model hands back, BYTE-IDENTICAL in both directions: the digest
+# prints `ref=12` and that exact string is the selector argument, so "copy it as printed" has one
+# reading. Deliberately not an attribute-selector shape and deliberately not bracketed -- the ref
+# namespace is a server-side table, and accepting a `[ref=12]` form would let a page that authors a
+# `ref` attribute collide with it, which is the wrong-element class this addressing exists to close.
+# It lives here rather than in tools.py because both modules classify against it and a second copy
+# would drift.
+REF_SELECTOR_RE = re.compile(r"^\s*ref=(\d+)\s*$")
+
+
+DriverTimeoutPredicate = Callable[[BaseException], bool]
+
+
+def _no_driver_here(exc: BaseException) -> bool:
+ return False
+
+
+# Whether an exception is the browser driver's OWN timeout. Injected rather than imported, because
+# the driver package ships only in the `local`/`server` extras: importing it at this module's scope
+# would make the loop unimportable in a base install and would break the scripted-fake unit testing
+# the module docstring promises. `tools.py` -- the only module that can build a handler capable of
+# raising a driver error -- installs the real predicate as it imports, so the driver cohort cannot
+# read empty while a browser tool exists to fill it.
+_is_driver_timeout: DriverTimeoutPredicate = _no_driver_here
+
+
+def set_driver_timeout_predicate(predicate: DriverTimeoutPredicate) -> None:
+ global _is_driver_timeout
+ _is_driver_timeout = predicate
+
+
+def _raised_error_class(exc: BaseException) -> ToolErrorClass:
+ """Classify an exception that escaped a tool handler, for the failure-cost read.
+
+ A bare `TimeoutError` is NOT evidence of a driver timeout: `file_upload` awaits a source fetch
+ that raises one, and on 3.11 `asyncio.TimeoutError` IS `builtins.TimeoutError`. Folding those
+ into the driver cohort would corrupt the very number this field exists to produce.
+
+ The driver class is decided by the installed predicate -- `is_driver_timeout_error`, which
+ recognises BOTH Playwright-family packages -- and never by the exception's own module name: the
+ browser image rewrites this repository's driver imports to the fork, so a module test would
+ recognise driver timeouts only where the fork is absent -- i.e. nowhere that matters -- and
+ report the cohort as empty in production. Nothing here reads the exception's MESSAGE: a message
+ can carry page text and this field is indexed.
+ """
+ if _is_driver_timeout(exc):
+ return "driver_timeout"
+ if isinstance(exc, TimeoutError):
+ return "timeout_other"
+ return "handler_raised"
+
+
+def _selector_kind(args: dict[str, Any]) -> str:
+ """How the model addressed its target on this call, read off the ARGS AS SENT.
+
+ Must be taken before dispatch: the ref and act-by-mark wrappers rewrite `args["selector"]` in
+ place, so the same read afterwards reports the resolved address rather than the one the model
+ chose. It is the cut for `resolve_seconds`, but the two cohorts are NOT symmetric and the
+ contract above `_RESOLVE_SECONDS` says how: a `css` row bounds frame routing only, and only with
+ frame perception on -- a plain selector is otherwise resolved inside the handler and its row is
+ ~0. Read the two together with `frame_perception`, which rides the same record for that reason.
+ """
+ if args.get("mark") is not None:
+ return "mark"
+ selector = args.get("selector")
+ # `not selector`, matching what the wrappers themselves treat as absent. Note this does NOT make
+ # the record self-consistent: `selector_present` is read after dispatch, and act-by-mark leaves
+ # the selector it resolved in `args`, so a mark call logs kind=mark WITH selector_present=True.
+ # The two fields describe different moments on purpose -- read `selector_kind` for what the model
+ # sent.
+ if not isinstance(selector, str) or not selector:
+ return "none"
+ return "ref" if REF_SELECTOR_RE.match(selector) else "css"
class RoundAction(NamedTuple):
@@ -1194,6 +1335,10 @@ _TOOL_CALL_RECORD_FIELDS = frozenset(
"duration_seconds",
"result_chars",
"selector_present",
+ "selector_kind",
+ "tool_error_class",
+ "resolve_seconds",
+ "frame_perception",
"billable",
"turn",
"batch_size",
@@ -2697,6 +2842,10 @@ async def run_agent_tool_loop(
# Refreshed per call, not per turn: a batched action+finish turn must not defer on
# a stale turn-start snapshot (the conversion the headroom guard exists to prevent).
activity.tool_calls_remaining = st.max_tool_calls - st.total_tool_calls
+ selector_kind = _selector_kind(args)
+ # Cleared per call, so a value can never carry over from the previous one in the batch.
+ _RESOLVE_SECONDS.set(None)
+ _FRAME_PERCEPTION.set(None)
tool_started_at = time.monotonic()
if spec is None:
result = ToolResult.error(f"unknown_tool: {tool_name}")
@@ -2709,13 +2858,36 @@ async def run_agent_tool_loop(
result = await spec.handler(args)
except Exception as exc:
LOG.warning("taskv3 tool handler raised", tool=tool_name, exc_info=True)
- result = ToolResult.error(f"tool_error: {type(exc).__name__}: {exc}")
+ raised_class = _raised_error_class(exc)
+ result = ToolResult.error(f"tool_error: {type(exc).__name__}: {exc}", error_class=raised_class)
tool_duration_seconds = time.monotonic() - tool_started_at
st.tool_seconds += tool_duration_seconds
# Observe's summary counters are the only trace a perception change leaves on this
# record; its content is deliberately never logged. Gated on the tool, not the payload,
# so every other tool's record keeps exactly today's fields.
observe_summary = _observe_summary_fields(result) if tool_name == "observe" else {}
+ # Conditional for the same reason observe's counters are: a record only carries a field
+ # the call actually produced, so an ok call's record keeps exactly the fields it has
+ # today and `resolve_seconds` is absent (not null) on tools with no address to resolve.
+ cost_fields: dict[str, Any] = {}
+ if result.status == "error":
+ # `tool_error_class` on the record, `error_class` on the result: the log key lands in a
+ # FLAT index where `error_class` is already taken -- cloud/webeye logs it as
+ # `type(exc).__name__` at ~17 sites, so an unprefixed key here would mix this closed
+ # vocabulary with Python exception names under one facet, and taskv3 emits on every
+ # erroring tool call so it would dominate the values.
+ cost_fields["tool_error_class"] = result.error_class or "other"
+ # Read off the context variable, not the result: on the raise path the loop built the
+ # result itself and the handler's own resolution time would otherwise be lost.
+ resolve_seconds = _RESOLVE_SECONDS.get()
+ if resolve_seconds is not None:
+ cost_fields["resolve_seconds"] = resolve_seconds
+ # Rides every row that carries a reading, because the css reading's MEANING depends on it:
+ # a dataset spanning the frame-perception ramp otherwise mixes two definitions of the same
+ # field with nothing on the record to stratify on.
+ frame_perception = _FRAME_PERCEPTION.get()
+ if frame_perception is not None:
+ cost_fields["frame_perception"] = frame_perception
# The action-loop guard's key and the perception ledger's digest, computed here (pure) so
# their hashes ride the record below; the ledger itself is updated further down, unchanged.
action_key = (tool_name, json.dumps(args, sort_keys=True, default=str))
@@ -2760,10 +2932,12 @@ async def run_agent_tool_loop(
# Truthiness, not presence: the tools treat a null or empty selector as absent and
# fall back to scanning the whole page, which is the case this field exists to find.
selector_present=bool(args.get("selector")),
+ selector_kind=selector_kind,
billable=bool(spec is not None and spec.billable),
turn=st.turns,
batch_size=len(tool_calls),
batch_index=idx,
+ **cost_fields,
**observe_summary,
**attribution,
)
diff --git a/skyvern/forge/taskv3/tools.py b/skyvern/forge/taskv3/tools.py
index 9bd6143da..67ced08ca 100644
--- a/skyvern/forge/taskv3/tools.py
+++ b/skyvern/forge/taskv3/tools.py
@@ -38,18 +38,24 @@ from skyvern.core.script_generations.fuzzy_matcher import (
normalize_option_label,
)
from skyvern.forge.sdk.core.skyvern_context import URL_IN_TEXT, canonical_url, opaque_url_echo_window
+from skyvern.forge.taskv3.frame_perception import frame_perception_enabled
from skyvern.forge.taskv3.loop import (
NAVIGATION_DEAD_END_STATUSES,
PAGE_UNAVAILABLE_ERROR,
+ REF_SELECTOR_RE,
TARGET_KIND_DATA_KEY,
TARGET_LABEL_DATA_KEY,
SemanticCommitStats,
ToolHandler,
ToolResult,
ToolSpec,
+ record_frame_perception,
+ record_resolve_seconds,
+ set_driver_timeout_predicate,
)
from skyvern.forge.taskv3.preflight import PREFLIGHT_TOOL_NAMES, preflight_tool_action
from skyvern.forge.taskv3.target_label import TARGET_KIND_TOKENS, TARGET_NAME_CAP
+from skyvern.webeye.browser_driver_errors import is_driver_timeout_error
from skyvern.webeye.utils.page import OTP_INPUT_PRIVACY_JS, OTP_SAFE_FRAGMENT_HTML_JS, mask_otp_values_in_html
if TYPE_CHECKING:
@@ -57,6 +63,12 @@ if TYPE_CHECKING:
# typing; the OpaqueUrlRefs instance is passed in at runtime, never imported here.
from skyvern.forge.taskv3.opaque_refs import OpaqueUrlRefs
+# At import, not inside build_browser_tools(): every handler that can raise a driver error is built
+# in this module, so binding the predicate to this module's own import makes the two impossible to
+# get out of step. The loop keeps a driver-blind default for the scripted-fake case, where nothing
+# can raise a driver error in the first place.
+set_driver_timeout_predicate(is_driver_timeout_error)
+
LOG = structlog.get_logger()
# Resolved fresh per tool call rather than a page bound once, so a click that opens a new
@@ -136,12 +148,6 @@ _TV3_MARKER_SELECTOR_RE = re.compile(r'^\[data-tv3(?:-menu|-act|-sugg)?="[^"\\]+
_OPAQUE_ID_RUN_RE = re.compile(
r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|(?=[0-9a-f]*[a-f])[0-9a-f]{12,}", re.I
)
-# What observe() prints and the model hands back, BYTE-IDENTICAL in both directions: the digest
-# prints `ref=12` and that exact string is the selector argument, so "copy it as printed" has one
-# reading. Deliberately not an attribute-selector shape and deliberately not bracketed -- the ref
-# namespace is a server-side table, and accepting a `[ref=12]` form would let a page that authors a
-# `ref` attribute collide with it, which is the wrong-element class this addressing exists to close.
-_REF_SELECTOR_RE = re.compile(r"^\s*ref=(\d+)\s*$")
# Whitespace outside a quoted attribute value is a combinator: only hostAnchored composes selectors
# that way, while a natural `[name="first name"]` keeps its single round trip.
_TV3_QUOTED_VALUE_RE = re.compile(r'"(?:[^"\\]|\\.)*"')
@@ -192,7 +198,8 @@ def _invalid_selector_result(selector: Any, exc: Exception) -> ToolResult | None
return None
return ToolResult.error(
f"{selector!r} is not a valid CSS selector. Use a selector from the latest observe(), or an "
- '[id="..."] / [name="..."] attribute form (ids that start with a digit are not valid as a bare #id).'
+ '[id="..."] / [name="..."] attribute form (ids that start with a digit are not valid as a bare #id).',
+ error_class="invalid_selector",
)
@@ -244,7 +251,8 @@ def _inert_target_error(selector: str) -> ToolResult:
"else on the page is blocked is a separate question this does not answer. Hidden markup is "
"usually a template the page clones (the live control is then a DIFFERENT element) or a panel "
"some trigger opens (act on the trigger first), and something still loading may yet reveal "
- "this one. Re-observe and act on what the page actually renders."
+ "this one. Re-observe and act on what the page actually renders.",
+ error_class="inert",
)
@@ -2310,7 +2318,7 @@ async def pending_marker(page: Any, selector: str) -> str | None:
# loses the case that matters: a durable selector like `#submit` or `button[type=submit]` commonly
# matches in both documents, and the parent's unrelated control then answers "not pending" for a
# frame control still showing "Processing" -- accepting finish(completed) on a live submission.
- if settings.TASK_V3_FRAME_PERCEPTION:
+ if frame_perception_enabled():
# ONE realm -- the one the submit was recorded in -- not a walk of every frame. A walk cannot be
# bounded (a wedged renderer blocks the protocol queue), and the caller's single global deadline
# cancelling a walk is what let a cancellation read as "nothing pending": a completion accepted
@@ -6733,7 +6741,7 @@ async def _count_filled_fields(page: Any) -> int:
total = int(await page.evaluate(_FILLED_STATE_JS))
except Exception:
LOG.info("taskv3 filled-state probe failed, treating page as empty", exc_info=True)
- if not settings.TASK_V3_FRAME_PERCEPTION:
+ if not frame_perception_enabled():
return total
# The main-frame count above is UNCHANGED, deliberately: it counts every field in that document
# including ones the PAGE pre-filled, and refusing a reload over those is what the guard is for, not
@@ -7120,7 +7128,7 @@ async def _realm_document_id(target: Any) -> str:
engine), which is what this was before either mechanism.
"""
url = canonical_url(_safe_url(target))
- if not settings.TASK_V3_FRAME_PERCEPTION:
+ if not frame_perception_enabled():
# The flag-off path gets the url alone, which is the identity it always had. Ungated, this
# helper opens a CDP session and issues Page.getFrameTree on EVERY observe and every ref
# action -- on all production traffic, for a loaderId only frame refs need, against CDP
@@ -7330,7 +7338,7 @@ def _iframe_reach_clause(observation: _Observation) -> str:
which have to stay VISIBLE as unread rather than vanish, because a silent omission is what turns
"I could not see it" into a confident "the form never rendered".
"""
- if not settings.TASK_V3_FRAME_PERCEPTION:
+ if not frame_perception_enabled():
return "(contents NOT listed here and NOT reachable by selector)"
unread = observation.unreadable_frames + observation.capped_frames
if unread:
@@ -7615,7 +7623,7 @@ def build_browser_tools(
main_data, main_handles, main_document = await _read_one_realm(page)
documents: dict[Any, str] = {None: main_document}
owners: list[Any] = [None] * len(main_handles)
- if not settings.TASK_V3_FRAME_PERCEPTION:
+ if not frame_perception_enabled():
return _Observation(main_data, main_handles, owners, {None: bool(main_data.get("refsFresh"))}, documents, 0)
frames, skipped, unjudged = await _observable_child_frames(page)
if not frames:
@@ -8086,7 +8094,7 @@ def build_browser_tools(
if selector:
target = await page.query_selector(selector)
if target is None:
- return ToolResult.error(f"no element for selector {selector!r}")
+ return ToolResult.error(f"no element for selector {selector!r}", error_class="stale_selector")
text = await _page_rendered_text(target)
if text is None:
return ToolResult.error("the rendered text could not be read")
@@ -8115,7 +8123,7 @@ def build_browser_tools(
frame blocks everything after it regardless. Adding one would look like a fix and be theatre.
Disclosed and tracked rather than papered over -- v1 has the same exposure in `get_frame_text`.
"""
- if not settings.TASK_V3_FRAME_PERCEPTION:
+ if not frame_perception_enabled():
return ""
frames, skipped, unjudged = await _observable_child_frames(page)
parts: list[str] = []
@@ -8161,7 +8169,7 @@ def build_browser_tools(
if selector:
el = await page.query_selector(selector)
if el is None:
- return ToolResult.error(f"no element for selector {selector!r}")
+ return ToolResult.error(f"no element for selector {selector!r}", error_class="stale_selector")
try:
html = mask_otp_values_in_html(await el.evaluate(OTP_SAFE_FRAGMENT_HTML_JS))
except Exception:
@@ -8193,16 +8201,21 @@ def build_browser_tools(
return ToolResult.error(
f"{selector} is not rendered and nothing visible stands in for it — its section is collapsed, "
"closed or inactive, so a person could not reach this control either. Act on whatever reveals "
- "it (the section header, the step, the modal trigger), then re-observe."
+ "it (the section header, the step, the modal trigger), then re-observe.",
+ error_class="unreachable",
)
def _not_editable_error(exc: _FieldNotEditable) -> ToolResult:
if exc.read_only:
return ToolResult.error(
f"{exc.selector} is readonly — typing cannot change it. If it opens a list, click it and "
- "pick an option instead; otherwise act on whatever sets it."
+ "pick an option instead; otherwise act on whatever sets it.",
+ error_class="not_editable",
)
- return ToolResult.error(f"{exc.selector} is disabled — it cannot be typed into until the page enables it")
+ return ToolResult.error(
+ f"{exc.selector} is disabled — it cannot be typed into until the page enables it",
+ error_class="disabled",
+ )
def _covered_error(
selector: str, occluder: dict[str, Any] | None = None, *, verb: str = "typed into"
@@ -8228,12 +8241,14 @@ def build_browser_tools(
f"{selector} is covered by {layer_desc} that is INVISIBLE — it intercepts clicks but paints "
f"nothing on screen, so you will not see it in a screenshot{also}. It is most likely a "
"leftover backdrop from a dialog or cookie banner that was already dismissed. Do not keep "
- "trying to dismiss a visible overlay; press Escape, re-observe, or reach the field another way."
+ "trying to dismiss a visible overlay; press Escape, re-observe, or reach the field another way.",
+ error_class="covered",
)
if not occluder:
return ToolResult.error(
f"{selector} is rendered but something else is on top of it, so it cannot be {verb}{also}. "
- "Dismiss whatever covers it (a dialog, an overlay, a cookie banner), then re-observe."
+ "Dismiss whatever covers it (a dialog, an overlay, a cookie banner), then re-observe.",
+ error_class="covered",
)
layer_desc = f'"{name}"' if name else "a layer"
if layer_selector:
@@ -8260,7 +8275,8 @@ def build_browser_tools(
# found on it, not confirmed dismissers, since a destructive or navigational action
# (e.g. "Delete account") is not distinguishable here from a close/cancel button.
f"Its controls: {controls_desc}. Pick whichever one actually closes or dismisses the "
- f"layer, then retry {selector}."
+ f"layer, then retry {selector}.",
+ error_class="covered",
)
async def _probe_arg(page: Any, selector: str) -> dict[str, Any]:
@@ -8339,7 +8355,9 @@ def build_browser_tools(
data[TARGET_LABEL_DATA_KEY] = name
if kind is not None:
data[TARGET_KIND_DATA_KEY] = kind
- return ToolResult(result.status, result.content, data, result.screenshots)
+ # `replace`, not a positional rebuild: this carries every field the result already has,
+ # including ones added later. A rebuild that lists fields drops the ones it forgets.
+ return dataclasses.replace(result, data=data)
return wrapped
@@ -8423,10 +8441,12 @@ def build_browser_tools(
f"{selector} no longer matches anything on the page — the page re-rendered since it was "
"observed. Re-observe and act on fresh selectors from the new observation.",
data={"page_state_changed": True},
+ error_class="stale_selector",
)
return ToolResult.error(
f"{selector} matches {matches} elements, so it does not identify one control. Re-observe and "
- "act on a selector from the new observation, or narrow this one until it matches exactly one."
+ "act on a selector from the new observation, or narrow this one until it matches exactly one.",
+ error_class="ambiguous_selector",
)
async def _marker_matches(page: Any, selector: str) -> int:
@@ -8683,6 +8703,7 @@ def build_browser_tools(
"page re-renders (a closed menu destroys its options). Re-observe and act on "
"fresh selectors from the new observation.",
data={"page_state_changed": True},
+ error_class="stale_selector",
)
# The re-attach may have been a re-render that cloned the row, so the count is re-read.
matches = await _marker_matches(page, selector)
@@ -8694,6 +8715,7 @@ def build_browser_tools(
"marked element, so the marker no longer identifies one control. Re-observe and act "
"on fresh selectors from the new observation.",
data={"page_state_changed": True},
+ error_class="ambiguous_selector",
)
else:
ambiguous = await _ambiguous_selector_error(page, selector)
@@ -8750,7 +8772,10 @@ def build_browser_tools(
except Exception:
reach_pre = None
if isinstance(reach_pre, dict) and reach_pre.get("exists") and reach_pre.get("disabled"):
- return ToolResult.error(f"{selector} is disabled — it cannot be clicked until the page enables it")
+ return ToolResult.error(
+ f"{selector} is disabled — it cannot be clicked until the page enables it",
+ error_class="disabled",
+ )
# `slotted` only qualifies unoccluded (the composed hit landed cleanly on the control's own
# slotted label); `ownLabel` already implies occluded+skinned, so it qualifies on its own.
label_over_control = isinstance(reach_pre, dict) and (
@@ -8793,7 +8818,10 @@ def build_browser_tools(
if skin_probe.get("disabled"):
# Playwright refuses a label bound to a disabled control the same way it refuses the
# control, so the click path would spend its full timeout and then blame a re-render.
- return ToolResult.error(f"{selector} is disabled — it cannot be toggled until the page enables it")
+ return ToolResult.error(
+ f"{selector} is disabled — it cannot be toggled until the page enables it",
+ error_class="disabled",
+ )
try:
checked_before = await _probe_evaluate(page, _CHECKBOX_CHECKED_JS, selector, pre_click_arg)
except Exception:
@@ -8865,6 +8893,7 @@ def build_browser_tools(
f"{selector} left the page before the click could land — it was replaced by a "
"re-render; re-observe and act on fresh selectors",
data={"page_state_changed": True},
+ error_class="stale_selector",
)
base = f"clicked {selector} (hidden native control, toggled directly) — now at {await _url(page)}"
else:
@@ -8894,6 +8923,7 @@ def build_browser_tools(
"likely removed by a re-render (e.g. a menu closed and destroyed its options). "
f"Re-observe and act on fresh selectors. (original error: {type(e).__name__})",
data={"page_state_changed": True},
+ error_class="stale_selector",
)
# Diagnosed only now, after the full actionability wait: a transient overlay (a toast,
# a closing menu) deserves the whole 15s to clear on its own, not a probe-shortened one.
@@ -10946,7 +10976,9 @@ def build_browser_tools(
# A disabled control cannot be set whichever kind it is; check before diverting so a disabled
# custom combobox gets the accurate "is disabled" message rather than the typeable-gate refusal.
if isinstance(probe, dict) and probe.get("exists") and probe.get("disabled"):
- return ToolResult.error(f"{selector} is disabled — it cannot be set until the page enables it")
+ return ToolResult.error(
+ f"{selector} is disabled — it cannot be set until the page enables it", error_class="disabled"
+ )
# Native-vs-custom gates on the authoritative nodeName (a structural signal, not a heuristic).
# Divert to the shared custom-combobox path ONLY when the probe positively confirms a
# non-<select> element (React-Select, spl-autocomplete, div-list) that page.select_option would
@@ -11152,7 +11184,7 @@ def build_browser_tools(
# is staged into downloads_dir, so the selector guard's residual error can never leave a phantom
# upload for the download-signal wrapper to misread as a browser download.
if await page.query_selector(selector) is None:
- return ToolResult.error(f"no file input for selector {selector!r}")
+ return ToolResult.error(f"no file input for selector {selector!r}", error_class="stale_selector")
source = _resolve_text(args["file"])
# A failed download echoes the source back in the loop's generic tool_error; the model-facing
# masking boundary (hide_from_model) rewrites any signed payload ref to its token there, so this
@@ -11167,7 +11199,10 @@ def build_browser_tools(
el = await page.query_selector(selector)
if el is None:
return ToolResult(
- "error", f"no file input for selector {selector!r}", {**staged, "page_state_changed": True}
+ "error",
+ f"no file input for selector {selector!r}",
+ {**staged, "page_state_changed": True},
+ error_class="stale_selector",
)
# Verify the upload took EFFECT, not just that set_input_files did not raise. Watch upload-like
# network dispatches across the set_input_files + settle window (the window we already dwell in,
@@ -11265,7 +11300,7 @@ def build_browser_tools(
def _look_nothing_marked_message() -> str:
base = "look: no interactive controls are visible in the viewport."
- if settings.TASK_V3_FRAME_PERCEPTION:
+ if frame_perception_enabled():
return (
base + " Note that look marks only the page's own frame, so controls inside an embedded"
" frame are not numbered here even though observe lists them and they are actionable by"
@@ -11460,13 +11495,15 @@ def build_browser_tools(
entry = _look_manifest.get(mark)
if entry is None:
return None, ToolResult.error(
- f"mark {mark} is not in the current set of marks. Call look() first, then act on a number it drew."
+ f"mark {mark} is not in the current set of marks. Call look() first, then act on a number it drew.",
+ error_class="mark_not_in_latest",
)
handle = entry.get("handle")
stale = ToolResult.error(
f"mark {mark} no longer points to an element on the page — it moved or the page "
"re-rendered since look(). Call look() again and act on a fresh number.",
data={"page_state_changed": True},
+ error_class="stale_mark",
)
if handle is None:
return None, stale
@@ -11475,35 +11512,98 @@ def build_browser_tools(
return None, stale
return selector, None
+ def _resolve_timer() -> tuple[Callable[[], None], Callable[[], None]]:
+ """`(page_acquired, record)` for pricing the turn from an ADDRESS into a target.
+
+ Working-page acquisition is EXCLUDED on every branch. Every design has to get the page, so it
+ is not a cost of the addressing model -- and only some branches acquire it inside this
+ wrapper, so counting it would make `resolve_seconds` bound different work depending on how
+ the model addressed its target, which is exactly the comparison the field exists to support.
+ Call `page_acquired()` right after `_resolve_page()` returns, on the failing path too, so a
+ call that never got a page records a zero rather than the acquisition it did not survive.
+
+ `record` LATCHES: the first call wins, later ones are no-ops. That is what lets each wrapper
+ put a single `finally: record()` around its whole resolution phase -- covering every early
+ return and every raise, including exits added later -- while still recording at the exact
+ point resolution ends on the path that goes on to dispatch the handler, whose own time is the
+ act and not resolution. Without the latch the two would double-count, because
+ `record_resolve_seconds` accumulates so the nested wrappers can sum.
+ """
+ started = time.monotonic()
+ recorded = False
+
+ def page_acquired() -> None:
+ nonlocal started
+ started = time.monotonic()
+
+ def record() -> None:
+ nonlocal recorded
+ if recorded:
+ return
+ recorded = True
+ record_resolve_seconds(time.monotonic() - started)
+
+ return page_acquired, record
+
def _with_act_by_mark(handler: ToolHandler) -> ToolHandler:
async def wrapped(args: dict[str, Any]) -> ToolResult:
mark = args.get("mark")
if mark is None:
return await handler(args)
- existing = args.get("selector")
- # A selector this wrapper minted is not the model passing both: since the resolved
- # selector is now written back into the caller's dict, a re-dispatch of that same dict
- # would otherwise fail a guard aimed at the model. The mark still wins and is re-resolved.
- if existing and not str(existing).startswith(_ACT_SELECTOR_PREFIX):
- return ToolResult.error("Pass either mark or selector to act on a control, not both.")
+ # Read once, for the same reason the ref wrapper does.
+ frame_perception = frame_perception_enabled()
+ # One guard for the whole resolution phase, not one per call that can raise: the latch in
+ # `record` makes every exit -- early return, raise, and exits added later -- record
+ # exactly once, so a mark rejected for bad input reports ~0 rather than nothing. Absent
+ # has to keep meaning "no address to resolve".
+ page_acquired, record = _resolve_timer()
try:
- mark_int = int(mark)
- except (TypeError, ValueError):
- return ToolResult.error(f"mark must be an integer from the last look(), got {mark!r}.")
- page, error = await _resolve_page()
- if error is not None:
- return error
- selector, mark_error = await _resolve_mark(page, mark_int)
- if mark_error is not None:
- return mark_error
- # In place rather than into a copy: everything downstream reads this dict AFTER dispatch
- # -- the persisted action's element_id, the submit watch, the repeat guard's key and the
- # nudge's target -- and a copy leaves every one of them seeing only `mark`.
- args["selector"] = selector
- # The THIRD caller with this shape, found by checking rather than by being told about it: the
- # mark was resolved against THIS page, so letting preflight resolve again lets a popup that
- # became the working page in between be the one acted on.
- _prefetched_page.append(page)
+ existing = args.get("selector")
+ # A selector this wrapper minted is not the model passing both: since the resolved
+ # selector is now written back into the caller's dict, a re-dispatch of that same dict
+ # would otherwise fail a guard aimed at the model. The mark still wins and is re-resolved.
+ if existing and not str(existing).startswith(_ACT_SELECTOR_PREFIX):
+ return ToolResult.error("Pass either mark or selector to act on a control, not both.")
+ try:
+ mark_int = int(mark)
+ except (TypeError, ValueError):
+ # The mark cohort's `invalid_selector`: the address as SENT is not well formed.
+ # Its neighbour above ("either mark or selector, not both") deliberately keeps no
+ # class -- that is a schema error with no counterpart in the css cohort, so naming
+ # it would add a value to one side of the comparison this record exists to support.
+ return ToolResult.error(
+ f"mark must be an integer from the last look(), got {mark!r}.",
+ error_class="invalid_mark",
+ )
+ # `page_acquired` restarts the clock on the raising path too, so acquisition is
+ # excluded from every branch rather than bounding this one row alone.
+ try:
+ page, error = await _resolve_page()
+ finally:
+ page_acquired()
+ if error is not None:
+ return error
+ # A failed mark resolution spent real time looking; the phase guard reports it
+ # rather than hiding exactly the failure cost this field exists to price.
+ selector, mark_error = await _resolve_mark(page, mark_int)
+ if mark_error is not None:
+ return mark_error
+ # In place rather than into a copy: everything downstream reads this dict AFTER dispatch
+ # -- the persisted action's element_id, the submit watch, the repeat guard's key and the
+ # nudge's target -- and a copy leaves every one of them seeing only `mark`.
+ args["selector"] = selector
+ # The THIRD caller with this shape, found by checking rather than by being told about it: the
+ # mark was resolved against THIS page, so letting preflight resolve again lets a popup that
+ # became the working page in between be the one acted on.
+ _prefetched_page.append(page)
+ finally:
+ # A mark resolves to a selector HERE, outside the ref wrapper, which therefore sees a
+ # plain selector and measures ~0. The inner wrapper's own reading adds to this one.
+ record()
+ # Stamped here as well as in the ref wrapper: a mark that fails to resolve returns
+ # from this wrapper and never reaches the inner one, so the row would otherwise
+ # carry a reading with nothing saying which definition produced it.
+ record_frame_perception(frame_perception)
try:
return await handler(args)
finally:
@@ -11542,12 +11642,14 @@ def build_browser_tools(
entry = _observe_manifest.get(ref)
if entry is None:
return None, ToolResult.error(
- f"ref={ref} is not a ref from the latest observe — re-observe and use a ref from the new observation"
+ f"ref={ref} is not a ref from the latest observe — re-observe and use a ref from the new observation",
+ error_class="ref_not_in_latest",
)
stale = ToolResult.error(
f"ref={ref} no longer points to an element on the page — it moved or the page re-rendered "
"since observe(). Call observe() again and act on a fresh ref.",
data={"page_state_changed": True},
+ error_class="stale_ref",
)
expected = str(entry.get("tag") or "").lower()
remembered = str(entry.get("selector") or "")
@@ -11650,7 +11752,8 @@ def build_browser_tools(
return None, ToolResult.error(
f"ref={ref} was read from an embedded frame that shares a url with another frame on "
"this page, so it cannot be confirmed to still be the same document — call observe() "
- "again and act on a ref from the new reading."
+ "again and act on a ref from the new reading.",
+ error_class="ambiguous_frame",
)
if recorded_document != await _realm_document_id(page if owner is None else owner):
return None, stale
@@ -11695,7 +11798,7 @@ def build_browser_tools(
frames -- and a selector matching in more than one frame is an ERROR, never a pick: choosing
between two documents on the model's behalf is the wrong-element commit in a new costume.
"""
- if not settings.TASK_V3_FRAME_PERCEPTION:
+ if not frame_perception_enabled():
return page, None
found: list[Any] = []
try:
@@ -11732,12 +11835,14 @@ def build_browser_tools(
return None, ToolResult.error(
f"{selector} could not be confirmed to name one element: {uninspected} frame(s) of this "
"page were not readable, and a selector like this is numbered separately in every "
- "document — re-observe and act on a ref, which names exactly one."
+ "document — re-observe and act on a ref, which names exactly one.",
+ error_class="ambiguous_frame",
)
if len(found) > 1:
return None, ToolResult.error(
f"{selector} matches elements in {len(found)} different documents of this page, so it "
- "does not name one element — re-observe and act on a ref, which names exactly one."
+ "does not name one element — re-observe and act on a ref, which names exactly one.",
+ error_class="ambiguous_frame",
)
return (found[0] if found else page), None
@@ -11785,70 +11890,110 @@ def build_browser_tools(
def _with_ref_resolution(tool_name: str, handler: ToolHandler) -> ToolHandler:
async def wrapped(args: dict[str, Any]) -> ToolResult:
+ # Read ONCE, so the value stamped on the row is provably the one that chose the branch
+ # below. A stratifier read separately from the decision it describes can disagree with it.
+ frame_perception = frame_perception_enabled()
+ page_acquired, record = _resolve_timer()
selector = args.get("selector")
- match = _REF_SELECTOR_RE.match(selector) if isinstance(selector, str) else None
- if match is None:
- # Inert with the flag off: no realm to route to, so not even a page resolution.
- if not settings.TASK_V3_FRAME_PERCEPTION or not isinstance(selector, str) or not selector:
- return await handler(args)
- page, error = await _resolve_page()
+ addressed = isinstance(selector, str) and bool(selector)
+ # ONE guard for the whole phase, rather than a `record(); raise` at each call that can
+ # raise: that shape was repeated six times here and four of this PR's own review findings
+ # were exits it did not cover. `record` latches, so the explicit calls that remain mark
+ # where resolution ENDS on a path that goes on to dispatch, and this covers every other
+ # exit -- including ones added later.
+ try:
+ match = REF_SELECTOR_RE.match(selector) if isinstance(selector, str) else None
+ if match is None:
+ # Inert with the flag off: no realm to route to, so not even a page resolution.
+ if not frame_perception or not isinstance(selector, str) or not selector:
+ # Recorded HERE and not left to the phase guard: the guard runs after the
+ # handler on this path, and the handler's own time is the act, not resolution.
+ if addressed:
+ record()
+ return await handler(args)
+ # The page provider RAISES on an unrecoverable mid-run page loss rather than returning
+ # an error; the phase guard below records that too, as a zero.
+ try:
+ page, error = await _resolve_page()
+ finally:
+ page_acquired()
+ if error is not None:
+ return error
+ realm, realm_error = await _realm_for_typed_selector(page, selector)
+ if realm_error is not None:
+ return realm_error
+ # The routed page is handed on, because the realm decision was made ABOUT it: the
+ # provider is must_get_working_page and can switch to a newer tab, so letting preflight
+ # resolve again would run the selector on a popup that became valid during the frame
+ # queries while the routing belongs to the page before it. Cleared in the finally, which
+ # is what keeps this writer from leaving a page for the next call to pop.
+ _prefetched_page.append(page)
+ if realm is not page:
+ _acted_realm[:] = [realm]
+ # Resolution ends here, before the act. The latch makes this the reading the phase
+ # guard below reports, so the handler's own time is never billed to resolution.
+ record()
+ try:
+ result = await handler(args)
+ await _note_frame_work(tool_name, realm, args.get("selector"), result)
+ return result
+ finally:
+ _acted_realm.clear()
+ _prefetched_page.clear()
+ # `page_acquired` restarts the clock on the raising path too, so acquisition is excluded
+ # from every branch rather than bounding this one row alone.
+ try:
+ page, error = await _resolve_page()
+ finally:
+ page_acquired()
if error is not None:
return error
- realm, realm_error = await _realm_for_typed_selector(page, selector)
- if realm_error is not None:
- return realm_error
- # The routed page is handed on, because the realm decision was made ABOUT it: the
- # provider is must_get_working_page and can switch to a newer tab, so letting preflight
- # resolve again would run the selector on a popup that became valid during the frame
- # queries while the routing belongs to the page before it. Cleared in the finally, which
- # is what keeps this writer from leaving a page for the next call to pop.
+ ref = int(match.group(1))
+ resolved, ref_error = await _resolve_ref(page, ref)
+ if ref_error is not None:
+ return ref_error
+ _owner = (_observe_manifest.get(ref) or {}).get("owner")
+ # In place, for the same reason act-by-mark does it: the persisted action's element_id,
+ # the submit watch, the repeat guard's key and the nudge all read this dict AFTER dispatch.
+ args["selector"] = resolved
+ durable = str((_observe_manifest.get(ref) or {}).get("selector") or "")
+ # Handed on for the same reason the typed-selector branch does it: the ref was validated
+ # against THIS page, and letting preflight resolve again lets a popup that became the working
+ # page in between become the one acted on. Cleared in the finally, so it cannot outlive the
+ # call. This was fixed in the sibling branch and missed here.
_prefetched_page.append(page)
- if realm is not page:
- _acted_realm[:] = [realm]
+ if _owner is not None:
+ _acted_realm[:] = [_owner]
+ # Resolution ends here, before the act. The latch makes this the reading the phase
+ # guard below reports, so the handler's own time is never billed to resolution.
+ record()
try:
result = await handler(args)
- await _note_frame_work(tool_name, realm, args.get("selector"), result)
+ # The DURABLE selector, not `args["selector"]`, which is still the transient
+ # data-tv3-act token here and is restored to `durable` by the finally below. The submit
+ # watch records that durable form, so `pending_marker` is later called with it -- keyed
+ # by the token, the ledger lookup never matches and the gate accepts a completion over an
+ # in-flight submit. The ledger would not have worked for framed submits at all.
+ await _note_frame_work(tool_name, _owner, durable or args.get("selector"), result)
return result
finally:
_acted_realm.clear()
_prefetched_page.clear()
- page, error = await _resolve_page()
- if error is not None:
- return error
- ref = int(match.group(1))
- resolved, ref_error = await _resolve_ref(page, ref)
- if ref_error is not None:
- return ref_error
- _owner = (_observe_manifest.get(ref) or {}).get("owner")
- # In place, for the same reason act-by-mark does it: the persisted action's element_id,
- # the submit watch, the repeat guard's key and the nudge all read this dict AFTER dispatch.
- args["selector"] = resolved
- durable = str((_observe_manifest.get(ref) or {}).get("selector") or "")
- # Handed on for the same reason the typed-selector branch does it: the ref was validated
- # against THIS page, and letting preflight resolve again lets a popup that became the working
- # page in between become the one acted on. Cleared in the finally, so it cannot outlive the
- # call. This was fixed in the sibling branch and missed here.
- _prefetched_page.append(page)
- if _owner is not None:
- _acted_realm[:] = [_owner]
- try:
- result = await handler(args)
- # The DURABLE selector, not `args["selector"]`, which is still the transient
- # data-tv3-act token here and is restored to `durable` by the finally below. The submit
- # watch records that durable form, so `pending_marker` is later called with it -- keyed
- # by the token, the ledger lookup never matches and the gate accepts a completion over an
- # in-flight submit. The ledger would not have worked for framed submits at all.
- await _note_frame_work(tool_name, _owner, durable or args.get("selector"), result)
- return result
+ # ...but those readers run turns LATER, and the act token is a stamp on one node: a
+ # control the page REPLACES after the act -- a submit button swapped for its
+ # "Submitting" version -- carries it away, and the in-flight probe fails open on a
+ # selector that resolves to nothing. Hand them back an address that re-resolves.
+ if durable:
+ args["selector"] = durable
finally:
- _acted_realm.clear()
- _prefetched_page.clear()
- # ...but those readers run turns LATER, and the act token is a stamp on one node: a
- # control the page REPLACES after the act -- a submit button swapped for its
- # "Submitting" version -- carries it away, and the in-flight probe fails open on a
- # selector that resolves to nothing. Hand them back an address that re-resolves.
- if durable:
- args["selector"] = durable
+ # Only when an address was actually supplied. This wrapper also sits on
+ # selector-OPTIONAL tools (whole-page get_html, unfocused press_key, page scroll, timed
+ # wait), and recording for those would make the field present on calls that had nothing
+ # to resolve -- absent has to keep one meaning, or a cohort selected by presence is
+ # contaminated by calls that never addressed anything.
+ if addressed:
+ record()
+ record_frame_perception(frame_perception)
return wrapped
@@ -11856,11 +12001,7 @@ def build_browser_tools(
_spec(
"observe",
_OBSERVE_DESCRIPTION_BASE
- + (
- _OBSERVE_DESCRIPTION_FRAME_REACH
- if settings.TASK_V3_FRAME_PERCEPTION
- else _OBSERVE_DESCRIPTION_NO_FRAME_REACH
- ),
+ + (_OBSERVE_DESCRIPTION_FRAME_REACH if frame_perception_enabled() else _OBSERVE_DESCRIPTION_NO_FRAME_REACH),
_obj({}),
observe,
),
@@ -12167,13 +12308,15 @@ def _apply_download_signal(tools: list[ToolSpec], downloads_dir: str | None) ->
# The flag lets the loop's action-loop guard treat the download as progress without
# sniffing the notice lines back out of the content string. Preserve screenshots so a
# result that also carried a look image (or any future image) is not silently dropped.
- return ToolResult(
- result.status,
- result.content + "\n" + "\n".join(capped),
+ # `replace`, not a positional rebuild: this is the OUTERMOST wrapper, so a rebuild
+ # that lists fields silently drops whatever the inner wrappers set -- the screenshots
+ # the old comment here guarded, and every field added since.
+ return dataclasses.replace(
+ result,
+ content=result.content + "\n" + "\n".join(capped),
# download_new marks a download detected on THIS call; a compactable tool
# replaying retained pending lines carries only download_notice.
- {**(result.data or {}), "download_notice": True, "download_new": bool(new_lines)},
- result.screenshots,
+ data={**(result.data or {}), "download_notice": True, "download_new": bool(new_lines)},
)
except Exception:
LOG.warning("taskv3 download signal computation failed", tool=_tool_name, exc_info=True)
diff --git a/tests/unit/test_agent_task_v3.py b/tests/unit/test_agent_task_v3.py
index ecd46f663..8be966f6b 100644
--- a/tests/unit/test_agent_task_v3.py
+++ b/tests/unit/test_agent_task_v3.py
@@ -19,9 +19,11 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from skyvern.config import settings
from skyvern.errors.errors import UserDefinedError
from skyvern.exceptions import MissingBrowserStatePage
from skyvern.forge import agent as agent_module
+from skyvern.forge import app
from skyvern.forge.agent import ForgeAgent
from skyvern.forge.sdk.artifact.manager import ArtifactManager
from skyvern.forge.sdk.core import skyvern_context
@@ -48,6 +50,7 @@ from skyvern.forge.sdk.workflow.models.block import (
from skyvern.forge.sdk.workflow.models.parameter import CredentialParameter, OutputParameter, ParameterType
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
from skyvern.forge.taskv3.engine import MIN_ACTION_STEPS
+from skyvern.forge.taskv3.frame_perception import FRAME_PERCEPTION_FLAG, frame_perception_enabled
from skyvern.forge.taskv3.loop import LoopOutcome, RoundAction
from skyvern.schemas.workflows import BlockStatus, BlockType
from skyvern.utils.secret_redaction import REDACTED_SECRET_PLACEHOLDER
@@ -108,6 +111,7 @@ async def _run_execute_task_v3(
# runs before any loop_raises, even when the loop goes on to raise).
loop_mock.context = context
loop_mock.active_credential_parameter_key_during_loop = context.active_credential_parameter_key
+ loop_mock.frame_perception_enabled_during_loop = frame_perception_enabled()
cb = kwargs.get("on_action_round")
if cb is not None and action_rounds:
for i, round_actions in enumerate(action_rounds):
@@ -200,6 +204,42 @@ async def _run_execute_task_v3(
return out_step, out_task, loop_mock, post_step_mock
+async def test_execute_task_v3_resolves_frame_perception_before_the_loop(monkeypatch: pytest.MonkeyPatch) -> None:
+ """`_execute_task_v3` must actually call `resolve_frame_perception` with the run's real
+ identity before the loop starts -- an accessor that reads a hand-pinned context correctly
+ proves nothing about whether the real call site still resolves it. `workflow_run_id` is set to
+ a value distinct from `task_id` so a passing distinct_id assertion pins the documented
+ precedence (workflow_run_id wins) rather than passing because the two happened to match.
+ """
+ monkeypatch.setattr(settings, "TASK_V3_FRAME_PERCEPTION", False)
+ provider = AsyncMock(return_value=True)
+ monkeypatch.setattr(app.EXPERIMENTATION_PROVIDER, "is_feature_enabled_cached", provider)
+
+ outcome = LoopOutcome(status="completed", reason="done", billable_actions=[])
+ step, task, loop_mock, _post = await _run_execute_task_v3(
+ monkeypatch,
+ outcome,
+ workflow_run_id="wr_frame_perception_reach",
+ data_extraction_goal=None,
+ extracted_information_schema=None,
+ )
+
+ assert task.workflow_run_id == "wr_frame_perception_reach"
+ assert task.workflow_run_id != task.task_id
+
+ # As seen from inside the loop, before context is reset.
+ assert loop_mock.context.frame_perception_resolved_run_id == task.workflow_run_id
+ assert loop_mock.context.frame_perception_flag is True
+ assert loop_mock.frame_perception_enabled_during_loop is True
+
+ provider.assert_awaited_once_with(
+ FRAME_PERCEPTION_FLAG,
+ task.workflow_run_id,
+ properties={"organization_id": task.organization_id},
+ )
+
+
@pytest.mark.asyncio
async def test_execute_task_v3_bills_per_browser_action(monkeypatch: pytest.MonkeyPatch) -> None:
outcome = LoopOutcome(
diff --git a/tests/unit/test_frame_perception.py b/tests/unit/test_frame_perception.py
new file mode 100644
index 000000000..a82f36049
--- /dev/null
+++ b/tests/unit/test_frame_perception.py
@@ -0,0 +1,284 @@
+"""Tests for the per-run resolution of TASK_V3_FRAME_PERCEPTION.
+
+Mirrors `tests/unit/test_planner_levers.py`'s conventions (patch `settings` and the
+provider's `is_feature_enabled_cached` directly) and `tests/unit/test_workflow_block_engine.py`'s
+NoOp-provider pattern (a real `NoOpExperimentationProvider` instance, spied so the test can prove
+it was never queried, since the provider itself would otherwise return False regardless).
+"""
+
+from __future__ import annotations
+
+import asyncio
+from collections.abc import Iterator
+from unittest.mock import AsyncMock
+
+import pytest
+
+from skyvern.config import settings
+from skyvern.forge import app
+from skyvern.forge.sdk.core import skyvern_context
+from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
+from skyvern.forge.sdk.experimentation.providers import NoOpExperimentationProvider
+from skyvern.forge.taskv3 import frame_perception
+from skyvern.forge.taskv3.frame_perception import (
+ FRAME_PERCEPTION_FLAG,
+ frame_perception_enabled,
+ resolve_frame_perception,
+)
+from skyvern.forge.taskv3.tools import build_browser_tools
+from tests.unit.test_taskv3_tools import _FakePage, _fixed_page_provider, _tool
+
+
+def scoped_context() -> Iterator[SkyvernContext]:
+ context = SkyvernContext()
+ skyvern_context.set(context)
+ try:
+ yield context
+ finally:
+ skyvern_context.reset()
+
+
+def test_env_true_forces_on_without_consulting_a_pinned_false_context(
+ scoped_context: SkyvernContext, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # The context is explicitly pinned OFF for this run; the env term must still win, because it
+ # short-circuits before the pin is read at all.
+ scoped_context.frame_perception_flag = False
+ scoped_context.frame_perception_resolved_run_id = "tsk_pinned_off"
+ provider = AsyncMock(return_value=False)
+ monkeypatch.setattr(settings, "TASK_V3_FRAME_PERCEPTION", True)
+ monkeypatch.setattr(app.EXPERIMENTATION_PROVIDER, "is_feature_enabled_cached", provider)
+
+ assert frame_perception_enabled() is True
+ provider.assert_not_awaited()
+
+
+async def test_env_false_and_provider_resolves_true(
+ scoped_context: SkyvernContext, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(settings, "TASK_V3_FRAME_PERCEPTION", False)
+ provider = AsyncMock(return_value=True)
+ monkeypatch.setattr(app.EXPERIMENTATION_PROVIDER, "is_feature_enabled_cached", provider)
+
+ await resolve_frame_perception(scoped_context, distinct_id="tsk_true", organization_id="org_1")
+
+ assert frame_perception_enabled() is True
+ provider.assert_awaited_once_with(FRAME_PERCEPTION_FLAG, "tsk_true", properties={"organization_id": "org_1"})
+
+
+def test_env_false_and_context_never_resolved_is_off(
+ scoped_context: SkyvernContext, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # No resolve_frame_perception call at all: a fresh context's resolved_run_id stays None.
+ monkeypatch.setattr(settings, "TASK_V3_FRAME_PERCEPTION", False)
+
+ assert scoped_context.frame_perception_resolved_run_id is None
+ assert frame_perception_enabled() is False
+
+
+def test_no_context_at_all_is_off_and_does_not_raise(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(settings, "TASK_V3_FRAME_PERCEPTION", False)
+ skyvern_context.reset()
+
+ assert skyvern_context.current() is None
+ assert frame_perception_enabled() is False
+
+
+async def test_same_distinct_id_pins_and_does_not_re_resolve(
+ scoped_context: SkyvernContext, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # The anti-re-evaluation guarantee: a second resolve for the same run must not re-query the
+ # provider, even if the provider would now answer differently. A cache-expiry or a mid-run ramp
+ # must not be able to flip an already-pinned run.
+ monkeypatch.setattr(settings, "TASK_V3_FRAME_PERCEPTION", False)
+ provider = AsyncMock(side_effect=[True, False])
+ monkeypatch.setattr(app.EXPERIMENTATION_PROVIDER, "is_feature_enabled_cached", provider)
+
+ await resolve_frame_perception(scoped_context, distinct_id="tsk_pin", organization_id="org_1")
+ assert frame_perception_enabled() is True
+
+ await resolve_frame_perception(scoped_context, distinct_id="tsk_pin", organization_id="org_1")
+ assert frame_perception_enabled() is True
+
+ provider.assert_awaited_once()
+
+
+async def test_a_different_distinct_id_re_resolves(
+ scoped_context: SkyvernContext, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(settings, "TASK_V3_FRAME_PERCEPTION", False)
+ provider = AsyncMock(side_effect=[True, False])
+ monkeypatch.setattr(app.EXPERIMENTATION_PROVIDER, "is_feature_enabled_cached", provider)
+
+ await resolve_frame_perception(scoped_context, distinct_id="tsk_a", organization_id="org_1")
+ assert frame_perception_enabled() is True
+
+ await resolve_frame_perception(scoped_context, distinct_id="tsk_b", organization_id="org_1")
+ assert frame_perception_enabled() is False
+
+ assert provider.await_count == 2
+
+
+async def test_provider_exception_resolves_off_and_still_pins(
+ scoped_context: SkyvernContext, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(settings, "TASK_V3_FRAME_PERCEPTION", False)
+ provider = AsyncMock(side_effect=RuntimeError("provider unavailable"))
+ monkeypatch.setattr(app.EXPERIMENTATION_PROVIDER, "is_feature_enabled_cached", provider)
+
+ await resolve_frame_perception(scoped_context, distinct_id="tsk_err", organization_id="org_1")
+
+ assert frame_perception_enabled() is False
+ assert scoped_context.frame_perception_resolved_run_id == "tsk_err"
+ provider.assert_awaited_once()
+
+
+async def test_noop_provider_is_off_without_ever_being_queried(
+ scoped_context: SkyvernContext, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(settings, "TASK_V3_FRAME_PERCEPTION", False)
+ provider = NoOpExperimentationProvider()
+ spy = AsyncMock(wraps=provider.is_feature_enabled_cached)
+ monkeypatch.setattr(provider, "is_feature_enabled_cached", spy)
+ monkeypatch.setattr(frame_perception.app, "EXPERIMENTATION_PROVIDER", provider)
+
+ await resolve_frame_perception(scoped_context, distinct_id="tsk_noop", organization_id="org_1")
+
+ assert frame_perception_enabled() is False
+ spy.assert_not_awaited()
+
+
+def test_the_pin_reaches_the_module_level_iframe_reach_clause(monkeypatch: pytest.MonkeyPatch) -> None:
+ from skyvern.forge.taskv3.tools import _iframe_reach_clause
+ from skyvern.forge.taskv3.tools import _Observation as Obs
+
+ monkeypatch.setattr(settings, "TASK_V3_FRAME_PERCEPTION", False)
+ observation = Obs({}, [], [], {}, {}, 0, 0)
+
+ context = SkyvernContext(frame_perception_flag=True, frame_perception_resolved_run_id="tsk_reach")
+ skyvern_context.set(context)
+ try:
+ assert "actionable by ref" in _iframe_reach_clause(observation)
+ finally:
+ skyvern_context.reset()
+
+ # Complement: same shape of context, but the run was never resolved -- must read as off.
+ unresolved = SkyvernContext()
+ skyvern_context.set(unresolved)
+ try:
+ assert "NOT reachable by selector" in _iframe_reach_clause(observation)
+ finally:
+ skyvern_context.reset()
+
+
+def test_the_pin_reaches_the_build_time_observe_tool_description(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(settings, "TASK_V3_FRAME_PERCEPTION", False)
+
+ pinned = SkyvernContext(frame_perception_flag=True, frame_perception_resolved_run_id="tsk_build")
+ skyvern_context.set(pinned)
+ try:
+ tools = build_browser_tools(_fixed_page_provider(_FakePage()))
+ description = _tool(tools, "observe").description
+ finally:
+ skyvern_context.reset()
+ assert "acted on by ref" in description
+ assert "cannot be observed or reached" not in description
+
+ # Complement: an unresolved run baked at build time must get the no-reach description.
+ unresolved = SkyvernContext()
+ skyvern_context.set(unresolved)
+ try:
+ tools = build_browser_tools(_fixed_page_provider(_FakePage()))
+ description = _tool(tools, "observe").description
+ finally:
+ skyvern_context.reset()
+ assert "cannot be observed or reached" in description
+ assert "acted on by ref" not in description
+
+
+async def test_parallel_branches_sharing_one_context_resolve_the_arm_once(
+ scoped_context: SkyvernContext, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # Parallel branches of one run share a SkyvernContext, so both reach resolve with the same
+ # distinct_id before either has pinned. Unless the first is single-flighted, the second queries
+ # the provider too and overwrites the arm the first already baked into its observe description
+ # -- and the provider's failure path answers False, so that overwrite is an ordinary network
+ # blip rather than a rare straddled ramp.
+ monkeypatch.setattr(settings, "TASK_V3_FRAME_PERCEPTION", False)
+ first_entered = asyncio.Event()
+ release_first = asyncio.Event()
+ answers = iter([True, False])
+
+ async def _racing_provider(flag: str, distinct_id: str, properties: dict | None = None) -> bool:
+ first_entered.set()
+ await release_first.wait()
+ return next(answers)
+
+ provider = AsyncMock(side_effect=_racing_provider)
+ monkeypatch.setattr(app.EXPERIMENTATION_PROVIDER, "is_feature_enabled_cached", provider)
+
+ winner = asyncio.create_task(
+ resolve_frame_perception(scoped_context, distinct_id="tsk_race", organization_id="org_1")
+ )
+ await first_entered.wait()
+ loser = asyncio.create_task(
+ resolve_frame_perception(scoped_context, distinct_id="tsk_race", organization_id="org_1")
+ )
+ for _ in range(5):
+ await asyncio.sleep(0)
+ release_first.set()
+ await asyncio.gather(winner, loser)
+
+ assert provider.await_count == 1
+ assert frame_perception_enabled() is True
+
+
+def test_no_module_outside_the_accessor_reads_the_env_setting_directly() -> None:
+ """The migration's own invariant, made mechanical rather than remembered.
+
+ Twelve sites moved from `settings.TASK_V3_FRAME_PERCEPTION` to `frame_perception_enabled()`, and
+ reverting any ONE of them is invisible to a behaviour test: with the flag at 0% the two
+ expressions agree everywhere except under a context pinned against the env setting, which only a
+ few sites are exercised under. Several of the rest -- the page fingerprint, the realm document
+ id, the frame-text tail -- have no on-arm observable at all without a real browser, so there is no
+ behaviour test to write for them in this suite.
+
+ This checks the property a revert actually breaks, for every site at once and for the thirteenth
+ site nobody has written yet. It is the enforcement the runbook's removal section says does not
+ exist.
+ """
+ import ast # noqa: PLC0415
+ import pathlib # noqa: PLC0415
+
+ import skyvern # noqa: PLC0415
+
+ repo_root = pathlib.Path(skyvern.__file__).resolve().parent.parent
+ accessor = "skyvern/forge/taskv3/frame_perception.py"
+ reads: set[str] = set()
+ for root in (repo_root / "skyvern", repo_root / "cloud"):
+ if not root.is_dir():
+ continue
+ for path in root.rglob("*.py"):
+ source = path.read_text(encoding="utf-8", errors="replace")
+ # A cheap prefilter, not the test: the attribute name is the thing being searched for, so
+ # any spelling that reaches it -- including through an aliased `settings` import -- still
+ # contains this literal.
+ if "TASK_V3_FRAME_PERCEPTION" not in source:
+ continue
+ for node in ast.walk(ast.parse(source)):
+ if isinstance(node, ast.Attribute) and node.attr == "TASK_V3_FRAME_PERCEPTION":
+ reads.add(path.relative_to(repo_root).as_posix())
+
+ # Anti-vacuity: a walk that matched nothing would satisfy the check below in silence. The
+ # accessor itself reads the setting three times and must always appear here.
+ assert accessor in reads, "the scan found no reads at all; it is not looking at the source"
+ assert reads == {accessor}, (
+ f"these read the env setting instead of frame_perception_enabled(): {sorted(reads - {accessor})}"
+ )
diff --git a/tests/unit/test_taskv3_engine.py b/tests/unit/test_taskv3_engine.py
index a0c8c80b1..d0cd44c17 100644
--- a/tests/unit/test_taskv3_engine.py
+++ b/tests/unit/test_taskv3_engine.py
@@ -1492,10 +1492,14 @@ def _stub_code_tool() -> ToolSpec:
return ToolSpec(CODE_TOOL_NAME, "run python", {"type": "object", "properties": {}}, handler)
-async def _run_to_finish(caller: _ScriptedCaller) -> None:
+async def _run_to_finish(caller: _ScriptedCaller, *, frame_perception: bool | None = None) -> None:
# A real run always carries a context with a run identity; the code tool is withheld without one,
# so a context-free call would exercise the identity gate rather than the surface under test.
- skyvern_context.set(SkyvernContext(task_id="tsk_surface"))
+ context = SkyvernContext(task_id="tsk_surface")
+ if frame_perception is not None:
+ context.frame_perception_flag = frame_perception
+ context.frame_perception_resolved_run_id = context.task_id
+ skyvern_context.set(context)
try:
await run_task_v3_agent_loop(
page_provider=_fixed_page_provider(_FakePage()),
@@ -1576,6 +1580,34 @@ async def test_frame_perception_withholds_the_code_tool(monkeypatch: pytest.Monk
assert _advertised(caller) == _SURFACE_OFF_TOOL_NAMES | {"finish"}, surface
+async def test_frame_perception_per_run_pin_withholds_the_code_tool(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Same guarantee as `test_frame_perception_withholds_the_code_tool`, but for the per-run arm.
+
+ The env override is the force-on term; a run pinned on by the per-run resolver instead (env
+ False) must be withheld identically, or the code tool ends up gated on how the run was turned
+ on rather than on whether it was.
+ """
+ asked = False
+
+ async def _build(**kwargs: Any) -> ToolSpec | None:
+ nonlocal asked
+ asked = True
+ return _stub_code_tool()
+
+ monkeypatch.setattr(app.AGENT_FUNCTION, "build_task_v3_code_tool", _build)
+ monkeypatch.setattr(settings, "TASK_V3_FRAME_PERCEPTION", False)
+
+ for surface in ("add", "replace"):
+ monkeypatch.setattr(settings, "TASK_V3_CODE_TOOL_SURFACE", surface)
+ caller = _ScriptedCaller([[("finish", {"status": "completed", "reason": "done"})]])
+ await _run_to_finish(caller, frame_perception=True)
+
+ assert not asked, surface
+ # And `replace` did not strip the action tools on its way to offering nothing.
+ assert _advertised(caller) == _SURFACE_OFF_TOOL_NAMES | {"finish"}, surface
+
+
@pytest.mark.asyncio
async def test_no_runner_leaves_every_surface_with_todays_tools(monkeypatch: pytest.MonkeyPatch) -> None:
"""Today's actual state: the deployment has no runner, so the hook returns None.
diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.py
index 1b5d4d881..ba5d268a2 100644
--- a/tests/unit/test_taskv3_loop.py
+++ b/tests/unit/test_taskv3_loop.py
@@ -13,6 +13,8 @@ import copy
import hashlib
import json
import random
+import subprocess
+import sys
import time
from types import SimpleNamespace
from typing import Any
@@ -69,8 +71,11 @@ from skyvern.forge.taskv3.loop import (
_PerceptionLedger,
_ProgressEvidence,
_ProgressLedger,
+ _raised_error_class,
_RevisitMemory,
make_finish_tool,
+ record_frame_perception,
+ record_resolve_seconds,
run_agent_tool_loop,
)
from skyvern.forge.taskv3.opaque_refs import mask_opaque_urls
@@ -9107,6 +9112,257 @@ async def test_a_completion_blocked_run_still_escapes_via_failed_at_production_w
assert state.giveup_deferrals == 0
+async def test_selector_kind_reports_the_address_the_model_sent_not_the_one_the_wrappers_left() -> None:
+ # The ref and act-by-mark wrappers rewrite args["selector"] IN PLACE, and ref resolution restores
+ # it to the manifest's durable CSS selector on the way out. Read after dispatch, every ref=N call
+ # would therefore record as "css" and the ref-vs-selector cost split would silently invert --
+ # with no test failing and no error anywhere. This pins the read to before dispatch.
+ async def rewrites_in_place(args: dict[str, Any]) -> ToolResult:
+ args["selector"] = '[data-x="durable"]' # what the real wrapper leaves behind
+ return ToolResult.ok("done")
+
+ click = ToolSpec(name="click", description="c", parameters={}, handler=rewrites_in_place, billable=True)
+ script = [
+ [("click", {"selector": "ref=12"})],
+ [("click", {"selector": "#plain"})],
+ [("click", {"mark": 3})],
+ [("finish", {"status": "completed", "reason": "ok"})],
+ ]
+ with capture_logs() as logs:
+ outcome, _ = await _run(script, [click, make_finish_tool()])
+ assert outcome.status == "completed"
+ records = [e for e in logs if e["event"] == "taskv3 tool call finished" and e["tool"] == "click"]
+ assert [e["selector_kind"] for e in records] == ["ref", "css", "mark"]
+ # The mark call carries selector_present=True even though the model sent no selector: the wrapper
+ # left its resolved selector in `args` and that field is read after dispatch. Pinned rather than
+ # fixed -- the two fields describe different moments, and a reader of the data needs to know.
+ assert [e["selector_present"] for e in records] == [True, True, True]
+
+
+async def test_a_failed_call_records_its_error_class_and_a_successful_one_records_none() -> None:
+ # error_class is what separates a stale-ref refusal from a driver timeout in the failure-cost
+ # read. It is never shown to the model, so a drift here is invisible except as a measurement
+ # that quietly reports every failure as "other".
+ async def stale(args: dict[str, Any]) -> ToolResult:
+ return ToolResult.error("gone", data={"page_state_changed": True}, error_class="stale_ref")
+
+ async def untagged(args: dict[str, Any]) -> ToolResult:
+ return ToolResult.error("something else")
+
+ async def fine(args: dict[str, Any]) -> ToolResult:
+ record_resolve_seconds(0.25)
+ record_frame_perception(True)
+ return ToolResult.ok("ok")
+
+ tools = [
+ ToolSpec(name="click", description="c", parameters={}, handler=stale, billable=True),
+ ToolSpec(name="hover", description="h", parameters={}, handler=untagged, billable=True),
+ ToolSpec(name="scroll", description="s", parameters={}, handler=fine),
+ make_finish_tool(),
+ ]
+ script = [
+ [("click", {"selector": "ref=1"})],
+ [("hover", {"selector": "#a"})],
+ [("scroll", {"selector": "#b"})],
+ [("finish", {"status": "completed", "reason": "ok"})],
+ ]
+ with capture_logs() as logs:
+ outcome, _ = await _run(script, tools)
+ assert outcome.status == "completed"
+ by_tool = {e["tool"]: e for e in logs if e["event"] == "taskv3 tool call finished"}
+ assert by_tool["click"]["tool_error_class"] == "stale_ref"
+ assert by_tool["hover"]["tool_error_class"] == "other"
+ # A successful call carries no error_class at all, and a call that resolved no address carries
+ # no resolve_seconds -- absent, not null, so the two are distinguishable in the read.
+ assert "error_class" not in by_tool["scroll"]
+ assert "tool_error_class" not in by_tool["scroll"]
+ assert by_tool["scroll"]["resolve_seconds"] == 0.25
+ assert "resolve_seconds" not in by_tool["click"]
+ # The measurement and the definition it was taken under travel together, or a dataset
+ # spanning the frame-perception ramp cannot separate the two meanings of a css row.
+ assert by_tool["scroll"]["frame_perception"] is True
+ assert "frame_perception" not in by_tool["click"]
+
+
+async def test_a_handler_that_raises_still_reports_the_time_it_spent_resolving_the_address() -> None:
+ # The cohort this telemetry exists to price is the one where the handler RAISES -- a driver
+ # timeout on a target that resolved fine. The loop builds that result itself, so anything the
+ # wrappers wrote onto the handler's return value is gone. Reading the resolution time off the
+ # context variable instead is what keeps the dominant failure cohort measurable; reading it off
+ # the result would silently report addressing as free exactly where it is not.
+ # The REAL driver error, not a look-alike: the classifier decides by driver-family TYPE, so a
+ # stand-in defined here would prove nothing about what is actually raised in production. The
+ # fork's arm cannot be exercised here (the package is absent outside the browser image) and is
+ # covered by construction -- `is_driver_timeout_error` enumerates both packages.
+ from playwright.async_api import TimeoutError as PlaywrightTimeoutError # noqa: PLC0415
+
+ async def times_out(args: dict[str, Any]) -> ToolResult:
+ record_resolve_seconds(0.75) # the wrapper resolved the address, then the act hung
+ raise PlaywrightTimeoutError("Timeout 30000ms exceeded")
+
+ async def fetch_times_out(args: dict[str, Any]) -> ToolResult:
+ record_resolve_seconds(0.25)
+ # file_upload awaits a source fetch that raises this, and on 3.11 asyncio.TimeoutError IS
+ # builtins.TimeoutError -- neither is a DRIVER timeout, and folding them into that cohort
+ # would corrupt the failed-action cost this field exists to produce.
+ raise TimeoutError("fetching the file took too long")
+
+ async def blows_up(args: dict[str, Any]) -> ToolResult:
+ record_resolve_seconds(0.5)
+ raise RuntimeError("something else entirely")
+
+ tools = [
+ ToolSpec(name="click", description="c", parameters={}, handler=times_out, billable=True),
+ ToolSpec(name="file_upload", description="u", parameters={}, handler=fetch_times_out, billable=True),
+ ToolSpec(name="type", description="t", parameters={}, handler=blows_up, billable=True),
+ make_finish_tool(),
+ ]
+ script = [
+ [("click", {"selector": "ref=1"})],
+ [("file_upload", {"selector": "ref=3"})],
+ [("type", {"selector": "ref=2"})],
+ [("finish", {"status": "completed", "reason": "ok"})],
+ ]
+ with capture_logs() as logs:
+ outcome, _ = await _run(script, tools)
+ assert outcome.status == "completed"
+ by_tool = {e["tool"]: e for e in logs if e["event"] == "taskv3 tool call finished"}
+ assert by_tool["click"]["tool_error_class"] == "driver_timeout"
+ assert by_tool["click"]["resolve_seconds"] == 0.75
+ # A bare TimeoutError is NOT driver evidence: it must not land in the driver cohort.
+ assert by_tool["file_upload"]["tool_error_class"] == "timeout_other"
+ assert by_tool["file_upload"]["resolve_seconds"] == 0.25
+ # Classified on the exception's module and CLASS name, never its message -- a message can carry
+ # page text, and this field is indexed.
+ assert by_tool["type"]["tool_error_class"] == "handler_raised"
+ assert by_tool["type"]["resolve_seconds"] == 0.5
+ # Per call, never carried over: finish resolved no address and must report none.
+ assert "resolve_seconds" not in by_tool["finish"]
+
+
+def test_every_driver_timeout_type_installed_here_classifies_as_a_driver_timeout() -> None:
+ # Written against the driver-type TABLE rather than a hard-coded package, because the hazard is
+ # precisely that CI and production do not install the same driver: the browser image repoints
+ # this repository's driver imports to the fork, so a test that names one package green-lights a
+ # classifier that is dead in production.
+ #
+ # STATED LIMIT, because green here is easy to over-read: CI installs only the un-forked driver,
+ # so in CI this test CANNOT tell a module-name check from a type check -- both pass. It reds on
+ # a dead driver arm, and it reds on a package-name check wherever the fork IS the installed
+ # driver, which is the environment that was broken. It is not a CI regression test for that
+ # case, and nothing available in CI could be.
+ import skyvern.forge.taskv3.tools # noqa: F401, PLC0415
+ from skyvern.webeye.browser_driver_errors import DRIVER_TIMEOUT_ERROR_TYPES # noqa: PLC0415
+ from skyvern.webeye.browser_driver_errors import is_driver_timeout_error # noqa: PLC0415
+
+ # The loop no longer imports the driver itself, so the cohort is only non-empty once the browser
+ # wiring has installed the predicate. Asserted explicitly rather than relied on: everything below
+ # would still pass on the driver-blind default if the classifier had quietly stopped being
+ # installed, and it would pass by reporting every driver timeout as something else.
+ assert loop_module._is_driver_timeout is is_driver_timeout_error
+ # Without this the loop below would pass vacuously on an empty table -- the failure mode where a
+ # driver timeout is classified as something else on every single call.
+ assert DRIVER_TIMEOUT_ERROR_TYPES, "no driver timeout types are installed; the classifier cannot work"
+ for driver_timeout in DRIVER_TIMEOUT_ERROR_TYPES:
+ assert _raised_error_class(driver_timeout("timed out")) == "driver_timeout", driver_timeout
+ # And the classes that merely LOOK like one stay out of that cohort.
+ assert _raised_error_class(TimeoutError("a source fetch, not the driver")) == "timeout_other"
+ assert _raised_error_class(RuntimeError("something else")) == "handler_raised"
+
+
+def test_every_error_class_written_anywhere_is_in_the_closed_set() -> None:
+ """The `Literal` alias is the declaration; this is what actually checks it.
+
+ `mypy.ini` sets `follow_imports = skip`, so `ToolResult` resolves to `Any` in every module that
+ imports it -- the annotation is enforced inside loop.py and nowhere else, and all but a handful
+ of the write sites are in tools.py. A typo or a near-synonym added there would split the facet
+ with nothing going red, which is the whole hazard of a closed vocabulary written at many sites.
+ Read out of the source rather than by calling, because the sites are error branches that a test
+ cannot all reach.
+
+ The population is DERIVED, not listed: every `ToolResult` construction under `skyvern/` and
+ `cloud/`, plus every `error_class=` kwarg anywhere in the taskv3 package. A named module list is
+ the same shape of hazard one level up -- it holds until someone writes the value somewhere the
+ list does not name, which is exactly what a tool registered through `extra_tools` does.
+ """
+ import ast # noqa: PLC0415
+ import pathlib # noqa: PLC0415
+ from typing import get_args # noqa: PLC0415
+
+ import skyvern # noqa: PLC0415
+ from skyvern.forge.taskv3.loop import ToolErrorClass # noqa: PLC0415
+
+ def _is_tool_result_call(node: ast.Call) -> bool:
+ func = node.func
+ if isinstance(func, ast.Name):
+ return func.id == "ToolResult"
+ return isinstance(func, ast.Attribute) and isinstance(func.value, ast.Name) and func.value.id == "ToolResult"
+
+ repo_root = pathlib.Path(skyvern.__file__).resolve().parent.parent
+ taskv3 = repo_root / "skyvern" / "forge" / "taskv3"
+ declared = set(get_args(ToolErrorClass))
+ written: set[str] = set()
+ for root in (repo_root / "skyvern", repo_root / "cloud"):
+ if not root.is_dir():
+ continue
+ for path in root.rglob("*.py"):
+ source = path.read_text(encoding="utf-8", errors="replace")
+ if "error_class" not in source:
+ continue
+ in_taskv3 = taskv3 in path.parents
+ for node in ast.walk(ast.parse(source)):
+ if not isinstance(node, ast.Call):
+ continue
+ # Scoped by the CALL, not by a list of modules. `auth_tools` and `captcha_tools`
+ # register through `extra_tools` into the same loop and land on the same facet, and a
+ # registrar could live outside this package entirely -- a named module list drops
+ # whichever site nobody thought to add. Scoping by `ToolResult` also keeps
+ # `cloud/webeye`'s unrelated `error_class` out, which is the collision the emitted
+ # field was renamed to escape.
+ if not (in_taskv3 or _is_tool_result_call(node)):
+ continue
+ for keyword in node.keywords:
+ value = keyword.value
+ if (
+ keyword.arg == "error_class"
+ and isinstance(value, ast.Constant)
+ and isinstance(value.value, str)
+ ):
+ written.add(value.value)
+
+ # Anti-vacuity: a walk that matched nothing would satisfy the subset check silently. These three
+ # live in tools.py, the module the subset check exists to cover.
+ assert {"stale_selector", "disabled", "ambiguous_frame"} <= written
+ assert written <= declared, f"error classes written but not declared: {sorted(written - declared)}"
+ # Produced by the loop's fallback for an erroring call whose site named nothing, not by a kwarg.
+ assert "other" in declared
+
+
+def test_the_loop_core_imports_with_no_browser_driver_installed() -> None:
+ """The module docstring's claim, made checkable.
+
+ The driver packages are in the `local`/`server` extras only, so any module-scope reach for one
+ from this file makes the loop unimportable in a base install and unusable with the scripted fakes
+ every test here is built on. A blocked meta-path entry stands in for that environment; a real one
+ cannot be built in-process, and the import graph read by eye is what let this through once.
+ """
+ probe = (
+ "import sys\n"
+ "class B:\n"
+ " def find_spec(self, name, path=None, target=None):\n"
+ " if name.split('.')[0] in ('playwright', 'patchright'):\n"
+ " raise ModuleNotFoundError(name)\n"
+ " return None\n"
+ "sys.meta_path.insert(0, B())\n"
+ "import skyvern.forge.taskv3.loop\n"
+ )
+ done = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True)
+ assert done.returncode == 0, done.stderr
+
+
def test_the_code_tool_is_treated_as_possibly_having_submitted() -> None:
"""The loop sees one call where any number of clicks and submits may have happened.
diff --git a/tests/unit/test_taskv3_tools.py b/tests/unit/test_taskv3_tools.py
index fbd3126c8..089b4ffe5 100644
--- a/tests/unit/test_taskv3_tools.py
+++ b/tests/unit/test_taskv3_tools.py
@@ -11118,7 +11118,7 @@ async def test_the_address_observe_prints_is_byte_identical_to_the_argument_the_
# will do exactly that. If the digest ever prints a form the resolver does not accept, the string
# falls through as CSS -- failing outright, or worse matching a page-authored attribute of the
# same name. One shape, both directions.
- from skyvern.forge.taskv3.tools import _REF_SELECTOR_RE # noqa: PLC0415
+ from skyvern.forge.taskv3.loop import REF_SELECTOR_RE # noqa: PLC0415
async with _content_page('<button id="go" style="width:80px;height:20px">Go</button>') as page:
tools = build_browser_tools(_fixed_page_provider(page))
@@ -11126,7 +11126,7 @@ async def test_the_address_observe_prints_is_byte_identical_to_the_argument_the_
line = next(ln for ln in r.content.splitlines() if "'Go'" in ln)
printed = line.split(" ", 1)[0]
- assert _REF_SELECTOR_RE.match(printed), f"observe printed {printed!r}, which no tool accepts"
+ assert REF_SELECTOR_RE.match(printed), f"observe printed {printed!r}, which no tool accepts"
clicked = await _tool(tools, "click").handler({"selector": printed})
assert clicked.status == "ok", clicked.content
@@ -23030,6 +23030,117 @@ def test_merging_caps_elements_page_wide_and_counts_what_it_dropped() -> None:
assert page["mergeCapDropped"] == 2
+async def test_the_download_notice_rebuild_keeps_every_field_the_inner_wrappers_set() -> None:
+ # _apply_download_signal is the OUTERMOST wrapper on every tool, and when it has a notice to
+ # deliver it returns a NEW ToolResult built from the old one. A rebuild that lists fields drops
+ # the ones it does not list -- which silently blanked error_class on every download-adjacent
+ # call, turning a classified failure into "other". Nothing else in the suite covers that seam.
+ import os # noqa: PLC0415
+ import tempfile # noqa: PLC0415
+
+ from skyvern.forge.taskv3.loop import ToolResult, ToolSpec # noqa: PLC0415
+ from skyvern.forge.taskv3.tools import _apply_download_signal # noqa: PLC0415
+
+ async def handler(args: dict[str, Any]) -> ToolResult:
+ return ToolResult.error("no", data={"page_state_changed": True}, error_class="stale_ref")
+
+ with tempfile.TemporaryDirectory() as downloads_dir:
+ spec = ToolSpec(name="click", description="c", parameters={}, handler=handler, billable=True)
+ _apply_download_signal([spec], downloads_dir)
+ # The baseline snapshot is taken inside the FIRST call, so the file has to appear after it --
+ # otherwise it is absorbed as pre-existing and the rebuild branch never executes.
+ first = await spec.handler({"selector": "ref=1"})
+ assert (first.data or {}).get("download_notice") is None
+ with open(os.path.join(downloads_dir, "statement.pdf"), "w") as fh:
+ fh.write("x")
+ result = await spec.handler({"selector": "ref=1"})
+
+ # The notice fired -- without this the assertions below would pass on the untouched result.
+ assert (result.data or {}).get("download_notice") is True
+ assert "Downloaded: statement.pdf" in result.content
+ assert result.error_class == "stale_ref"
+ assert (result.data or {}).get("page_state_changed") is True
+
+
+async def test_every_exit_from_address_resolution_records_exactly_one_stamped_reading(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The contract the phase guard replaced six hand-written `record(); raise` blocks to hold.
+
+ `record_resolve_seconds` ACCUMULATES, so recording twice inflates the row and recording zero
+ times drops it -- and neither is visible in the value, only in the count. Four of this PR's own
+ review findings were exits that recorded zero times, all found by reading rather than by a red.
+ """
+ readings: list[float] = []
+ stamps: list[bool] = []
+ monkeypatch.setattr(taskv3_tools, "record_resolve_seconds", lambda elapsed: readings.append(elapsed))
+ monkeypatch.setattr(taskv3_tools, "record_frame_perception", lambda enabled: stamps.append(enabled))
+ monkeypatch.setattr(settings, "TASK_V3_FRAME_PERCEPTION", False)
+
+ tools = {t.name: t for t in build_browser_tools(_fixed_page_provider(_FakePage()))}
+
+ # No address supplied: absent has to keep meaning "nothing to resolve".
+ readings.clear()
+ stamps.clear()
+ with contextlib.suppress(Exception):
+ await tools["get_html"].handler({})
+ assert readings == []
+ # ...and an unmeasured row must not be stamped either, or the two fields disagree about whether
+ # there was anything to describe.
+ assert stamps == []
+
+ # A plain selector, resolved later inside the handler: one reading, recorded before dispatch,
+ # stamped with the mode that decided where the resolution happens.
+ readings.clear()
+ stamps.clear()
+ with contextlib.suppress(Exception):
+ await tools["get_html"].handler({"selector": "#name"})
+ assert len(readings) == 1
+ assert stamps == [False]
+
+ # The same call under the other definition of that row -- the cut a ramp-spanning dataset needs.
+ monkeypatch.setattr(settings, "TASK_V3_FRAME_PERCEPTION", True)
+ framed = {t.name: t for t in build_browser_tools(_fixed_page_provider(_FakePage()))}
+ readings.clear()
+ stamps.clear()
+ with contextlib.suppress(Exception):
+ await framed["get_html"].handler({"selector": "#name"})
+ assert len(readings) == 1
+ assert stamps == [True]
+ monkeypatch.setattr(settings, "TASK_V3_FRAME_PERCEPTION", False)
+
+ # An address that fails to resolve still spent real time looking.
+ readings.clear()
+ failed = await tools["click"].handler({"selector": "ref=1"})
+ assert failed.status == "error"
+ assert len(readings) == 1
+
+ # The exit the guard exists for: the page provider raises mid-resolution rather than returning
+ # an error, so the loop builds the result itself and anything left unrecorded here is gone.
+ async def _page_lost() -> Any:
+ raise RuntimeError("unrecoverable mid-run page loss")
+
+ raising = {t.name: t for t in build_browser_tools(_page_lost)}
+ readings.clear()
+ stamps.clear()
+ with pytest.raises(RuntimeError):
+ await raising["click"].handler({"selector": "ref=1"})
+ assert len(readings) == 1
+ assert stamps == [False]
+
+ # A mark that never resolves returns from the OUTER wrapper, so the inner one -- which is where
+ # the stamp used to be written -- never runs. The row would carry a reading with nothing saying
+ # which definition produced it, which is the one thing the contract says cannot happen.
+ readings.clear()
+ stamps.clear()
+ rejected = await tools["click"].handler({"mark": "not-an-integer"})
+ assert rejected.status == "error"
+ assert len(readings) == 1
+ assert stamps == [False]
+
+
# Today's surface, written out rather than derived. A witness that derives the expected set from the
# same builder it checks cannot notice the set changing -- which is the whole thing these pin.
_SURFACE_OFF_TOOL_NAMES = frozenset(