Skip to content

Automate browser based workflows with AI

Let the screenshot supply a value the page can then address by that value (SKY-15537) (#8433)

Andrew Neilson2b850d10cfde
diff --git a/skyvern/forge/sdk/copilot/composition_browser_expressions.py b/skyvern/forge/sdk/copilot/composition_browser_expressions.py
index 737b969ac..fd15b3071 100644
--- a/skyvern/forge/sdk/copilot/composition_browser_expressions.py
+++ b/skyvern/forge/sdk/copilot/composition_browser_expressions.py
@@ -1345,6 +1345,64 @@ for (const target of REQUESTED_TARGETS) {
break;
}
}
+// A value the same call's screenshot pass read addresses a tile its label cannot: the label repeats
+// across hidden siblings, while exactly one visible leaf carries that magnitude.
+const witnessedLabelNear = (valueLeaf) => {
+ const wanted = new Set(REQUESTED_TARGETS.map((t) => String(t || '').trim().toLowerCase()).filter(Boolean));
+ if (!wanted.size) return { text: '', owner: null };
+ let branch = valueLeaf;
+ let ancestor = valueLeaf.parentElement;
+ while (ancestor && ancestor.tagName !== 'BODY' && ancestor.tagName !== 'HTML') {
+ for (const leaf of Array.from(ancestor.querySelectorAll('*'))) {
+ if (!isLeafEl(leaf) || withinEl(leaf, branch) || !elementVisible(leaf) || insidePageChrome(leaf)) continue;
+ const text = nodeText(leaf);
+ if (wanted.has(text.trim().toLowerCase())) return { text: text, owner: ancestor };
+ }
+ branch = ancestor;
+ ancestor = ancestor.parentElement;
+ }
+ return { text: '', owner: null };
+};
+const witnessedValueRelation = (valueLeaf) => {
+ const carrier = valueLeaf.parentElement;
+ if (!carrier) return null;
+ const kids = Array.from(carrier.children || []);
+ const childIndex = kids.indexOf(valueLeaf);
+ if (childIndex < 0) return null;
+ const sel = selectorFor(carrier);
+ if (!sel || sel.length > MAX_SELECTOR_CHARS) return null;
+ const matches = selectorMatchCount(sel);
+ if (!matches) return null;
+ let pos = -1;
+ try { pos = Array.from(document.querySelectorAll(sel)).indexOf(carrier); } catch (e) { pos = -1; }
+ if (pos < 0) return null;
+ const near = witnessedLabelNear(valueLeaf);
+ return { owner: carrier, relation: { key_text: near.text, selector_candidates: relationCandidatesFor(carrier, near.text), identity: identityFor(carrier), label_selector: '', label_child_index: -1, value_text: nodeText(valueLeaf), container_selector: sel, container_match_count: matches, container_position: pos, value_child_index: childIndex, direct_child_count: kids.length, visible: true, value_visible: true } };
+};
+const witnessedWanted = new Set(WITNESSED_VALUES);
+if (witnessedWanted.size) {
+ const witnessedLeaves = new Map();
+ for (const node of all) {
+ if (!isLeafEl(node)) continue;
+ const text = nodeText(node);
+ if (!witnessedWanted.has(text)) continue;
+ if (!elementVisible(node) || insidePageChrome(node) || insideMetricCard(node)) continue;
+ const seen = witnessedLeaves.get(text);
+ if (seen) seen.push(node);
+ else witnessedLeaves.set(text, [node]);
+ }
+ for (const value of WITNESSED_VALUES) {
+ if (keyValueRelations.length >= MAX_KEY_VALUE_RELATIONS) { keyValueRelationsTruncated = true; break; }
+ const leaves = witnessedLeaves.get(value);
+ if (!leaves || leaves.length !== 1) continue;
+ const found = witnessedValueRelation(leaves[0]);
+ if (!found) continue;
+ countFoldedKey(found.relation.key_text);
+ countWalkedValue(found.relation.value_text);
+ keyValueRelations.push(found.relation);
+ metricCardNodes.add(found.owner);
+ }
+}
for (const node of all) {
const tag = (node.tagName || '').toLowerCase();
if (keyValueSkipTags.has(tag) || !elementVisible(node) || insidePageChrome(node) || insideMetricCard(node)) continue;
@@ -1676,15 +1734,42 @@ return boundedStructuredEvidence(structuredEvidence);
"""
-def composition_structured_evidence_expression(requested_targets: tuple[str, ...] = ()) -> str:
- """The capture expression, told which labels the turn asked for.
+def composition_structured_evidence_expression(
+ requested_targets: tuple[str, ...] = (),
+ witnessed_values: tuple[str, ...] = (),
+) -> str:
+ """The capture expression, told which labels the turn asked for and which values were just seen.
- Capture that does not know the request can only guess which of a page's relations matters, and a
- tile whose shape it fails to recognise is replaced by whatever generic pair sits nearby.
+ Capture that does not know the request can only guess which relations matter, and a witnessed
+ value addresses a tile by the magnitude a screenshot read off it rather than by its shape.
"""
targets = [target.strip() for target in requested_targets if isinstance(target, str) and target.strip()]
- header = f"const REQUESTED_TARGETS={json.dumps(targets[:_MAX_KEY_VALUE_RELATIONS])};"
+ values = [value.strip() for value in witnessed_values if isinstance(value, str) and value.strip()]
+ header = (
+ f"const REQUESTED_TARGETS={json.dumps(targets[:_MAX_KEY_VALUE_RELATIONS])};"
+ f"const WITNESSED_VALUES={json.dumps(values[:_MAX_KEY_VALUE_RELATIONS])};"
+ )
return "(() => {" + header + _STRUCTURED_CONST_HEADER + _STRUCTURED_EVIDENCE_BODY + "})()"
COMPOSITION_STRUCTURED_EVIDENCE_EXPRESSION = composition_structured_evidence_expression()
+
+
+def value_witness_read_expression(container_selector: str, match_count: int, position: int, child_index: int) -> str:
+ """The page read that returns a witnessed relation's value, folding whitespace the way nodeText does.
+
+ A positional index only names the observed element while the selector still matches the same
+ number of nodes, so a page that grew or shed one reads nothing rather than the wrong element.
+ """
+ return (
+ "(() => { const nodes = document.querySelectorAll("
+ + json.dumps(container_selector)
+ + "); if (nodes.length !== "
+ + str(int(match_count))
+ + ") return null; const carrier = nodes["
+ + str(int(position))
+ + "]; if (!carrier) return null; const leaf = carrier.children["
+ + str(int(child_index))
+ + "]; if (!leaf) return null; "
+ + "return String(leaf.textContent || '').replace(/\\s+/g, ' ').trim(); })()"
+ )
diff --git a/skyvern/forge/sdk/copilot/composition_evidence.py b/skyvern/forge/sdk/copilot/composition_evidence.py
index c9083f117..b746ed14b 100644
--- a/skyvern/forge/sdk/copilot/composition_evidence.py
+++ b/skyvern/forge/sdk/copilot/composition_evidence.py
@@ -3,7 +3,7 @@
from __future__ import annotations
import re
-from collections.abc import Iterable
+from collections.abc import Iterable, Sequence
from typing import Any, Protocol
from urllib.parse import urljoin, urlparse
@@ -417,6 +417,16 @@ def _confirmed_visual_challenge(evidence: dict[str, Any], visual_summary: dict[s
)
+def unresolved_requested_targets(evidence: dict[str, Any], requested_targets: Sequence[str]) -> tuple[str, ...]:
+ """Requested labels the label-first pass could not address to a visible value on this page."""
+ resolved = {
+ str(relation.get("key_text") or "").strip().casefold()
+ for relation in evidence.get("key_value_relations") or []
+ if isinstance(relation, dict) and relation.get("visible") is True and relation.get("value_visible") is True
+ }
+ return tuple(target for target in requested_targets if target.strip() and target.strip().casefold() not in resolved)
+
+
def merge_visual_composition_evidence(
evidence: dict[str, Any],
*,
@@ -450,6 +460,15 @@ def merge_visual_composition_evidence(
summary = _bounded_string(visual_summary.get("summary"), _MAX_VISUAL_SUMMARY_CHARS)
if summary:
merged["visual_evidence_summary"] = summary
+ requested_values = [
+ {"label": _bounded_string(pair.get("label"), 240), "value": _bounded_string(pair.get("value"), 240)}
+ for pair in visual_summary.get("requested_values") or []
+ if isinstance(pair, dict)
+ and _bounded_string(pair.get("label"), 240)
+ and _bounded_string(pair.get("value"), 240)
+ ][:_MAX_KEY_VALUE_RELATIONS]
+ if requested_values:
+ merged["requested_values"] = requested_values
for item in visual_summary.get("omissions") or []:
bounded = _bounded_string(item, 160)
if bounded:
@@ -3496,6 +3515,8 @@ def model_visible_composition_evidence(evidence: dict[str, Any]) -> dict[str, An
facts retain their original order and values.
"""
+ # `expression` embeds a singular selector, its match count and its index in one string, so
+ # dropping only the scalar aliases would let the same facts cross as prose.
singular_selector_keys = {
"selector",
"selector_match_count",
@@ -3504,6 +3525,7 @@ def model_visible_composition_evidence(evidence: dict[str, Any]) -> dict[str, An
"label_selector",
"row_selector",
"expand_toggle_candidates",
+ "expression",
}
def project(value: Any) -> Any:
diff --git a/skyvern/forge/sdk/copilot/tools/__init__.py b/skyvern/forge/sdk/copilot/tools/__init__.py
index 91e0cabdd..66b31444d 100644
--- a/skyvern/forge/sdk/copilot/tools/__init__.py
+++ b/skyvern/forge/sdk/copilot/tools/__init__.py
@@ -11,7 +11,6 @@ import structlog
from agents import FunctionTool, function_tool
from agents.run_context import RunContextWrapper
from agents.tool_context import ToolContext
-from typing_extensions import TypedDict
from skyvern.forge import app as app
from skyvern.forge.sdk.copilot.browser_target import resolve_browser_session_binding
@@ -76,6 +75,8 @@ from ._shared import _DISCOVERY_PER_CALL_TIMEOUT_SECONDS as _DISCOVERY_PER_CALL_
from ._shared import _FAILED_BLOCK_STATUSES as _FAILED_BLOCK_STATUSES
from ._shared import BLOCK_RUNNING_TOOLS as BLOCK_RUNNING_TOOLS
from ._shared import RUN_BLOCKS_SAFETY_CEILING_SECONDS as RUN_BLOCKS_SAFETY_CEILING_SECONDS
+from ._shared import AdmittedOutputRead as AdmittedOutputRead
+from ._shared import RequestedOutputRead as RequestedOutputRead
from ._shared import _composition_get_html as _composition_get_html
from ._shared import _current_workflow_has_evidence_block as _current_workflow_has_evidence_block
from ._shared import _fallback_page_info as _fallback_page_info
@@ -84,6 +85,7 @@ from ._shared import _proxy_location_trace_value as _proxy_location_trace_value
from ._shared import _raw_yaml_proxy_location as _raw_yaml_proxy_location
from ._shared import _same_page_ignoring_fragment as _same_page_ignoring_fragment
from ._shared import _unverified_current_workflow_labels as _unverified_current_workflow_labels
+from ._shared import admitted_requested_output_reads
from .banned_blocks import _COPILOT_BANNED_BLOCK_TYPES as _COPILOT_BANNED_BLOCK_TYPES
from .banned_blocks import _banned_block_reject_message as _banned_block_reject_message
from .banned_blocks import _detect_new_banned_blocks as _detect_new_banned_blocks
@@ -666,39 +668,38 @@ async def delete_block_tool(ctx: RunContextWrapper, label: str) -> str:
)
-class RequestedOutputRead(TypedDict):
- """A requested output and the exact label/value the model sees on the current page."""
+SUPERSEDED_BY_VALUE_WITNESS = "superseded-by-value-witness"
- output_path: str
- value_text: str
- label: str
-
-_MAX_REQUESTED_OUTPUT_READS = 8
+def _witnessed_output_paths(data: object) -> frozenset[str]:
+ """Output paths this call's capture already addressed by the value its screenshot read."""
+ if not isinstance(data, dict):
+ return frozenset()
+ witnesses = data.get("value_witnesses")
+ if not isinstance(witnesses, list):
+ return frozenset()
+ return frozenset(
+ str(witness["output_path"])
+ for witness in witnesses
+ if isinstance(witness, dict) and str(witness.get("output_path") or "")
+ )
async def _verify_requested_output_reads(
copilot_ctx: CopilotContext,
reads: list[RequestedOutputRead],
+ witnessed_paths: frozenset[str] = frozenset(),
) -> tuple[list[dict[str, Any]], list[dict[str, str]]]:
"""Verify model-designated rendered values and return page facts without retaining a plan."""
verified: list[dict[str, Any]] = []
- unverified: list[dict[str, str]] = []
- seen_paths: set[str] = set()
- if len(reads) > _MAX_REQUESTED_OUTPUT_READS:
- unverified.append({"output_path": "", "reason": f"only-first-{_MAX_REQUESTED_OUTPUT_READS}-reads-verified"})
- for read in reads[:_MAX_REQUESTED_OUTPUT_READS]:
- raw_path = str(read.get("output_path") or "").strip()
- output_path = raw_path if raw_path.startswith("output.") else f"output.{raw_path}"
- value_text = str(read.get("value_text") or "").strip()
- label = str(read.get("label") or "").strip()
- if not raw_path or not value_text:
- unverified.append({"output_path": raw_path, "reason": "malformed"})
+ admitted, unverified = admitted_requested_output_reads(reads)
+ for read in admitted:
+ output_path = read.output_path
+ value_text = read.value_text
+ label = read.label
+ if output_path in witnessed_paths:
+ unverified.append({"output_path": output_path, "reason": SUPERSEDED_BY_VALUE_WITNESS})
continue
- if output_path in seen_paths:
- unverified.append({"output_path": output_path, "reason": "duplicate-output-path"})
- continue
- seen_paths.add(output_path)
server = copilot_ctx.discovery_mcp_server
if server is None:
unverified.append({"output_path": output_path, "reason": "no-browser"})
@@ -1350,15 +1351,23 @@ async def inspect_page_for_composition_tool(
authority_error = _authority_tool_error(ctx.context, "inspect_page_for_composition")
if authority_error:
return _diagnosis_repair_tool_error(ctx.context, "inspect_page_for_composition", authority_error)
- result = await _inspect_page_for_composition_impl(ctx.context, target_url)
+ admitted, _ = admitted_requested_output_reads(requested_output_reads or [])
+ result = await _inspect_page_for_composition_impl(ctx.context, target_url, admitted)
if requested_output_reads and result.get("ok"):
- verified, unverified = await _verify_requested_output_reads(ctx.context, requested_output_reads)
data = result.get("data")
+ witnessed_paths = _witnessed_output_paths(data)
+ verified, unverified = await _verify_requested_output_reads(
+ ctx.context, requested_output_reads, witnessed_paths
+ )
if isinstance(data, dict):
data["requested_output_designations"] = verified
if unverified:
data["unverified_output_designations"] = unverified
- retry_paths = [item["output_path"] for item in unverified if item.get("output_path")]
+ retry_paths = [
+ item["output_path"]
+ for item in unverified
+ if item.get("output_path") and item.get("reason") != SUPERSEDED_BY_VALUE_WITNESS
+ ]
if retry_paths:
data["requested_output_designation_capability"] = requested_output_designation_capability(
retry_paths
diff --git a/skyvern/forge/sdk/copilot/tools/_shared.py b/skyvern/forge/sdk/copilot/tools/_shared.py
index 5d6ecc009..11dd34dd0 100644
--- a/skyvern/forge/sdk/copilot/tools/_shared.py
+++ b/skyvern/forge/sdk/copilot/tools/_shared.py
@@ -2,12 +2,14 @@ from __future__ import annotations
import asyncio
import json
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Literal
from urllib.parse import urlparse
import structlog
import yaml
+from typing_extensions import TypedDict
from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal, stash_blocker_signal
from skyvern.forge.sdk.copilot.composition_browser_expressions import (
@@ -750,6 +752,53 @@ async def _composition_get_html(
return "", str(error) if error else None, False, True
+class RequestedOutputRead(TypedDict):
+ """A requested output and the exact label/value the model sees on the current page."""
+
+ output_path: str
+ value_text: str
+ label: str
+
+
+_MAX_REQUESTED_OUTPUT_READS = 8
+
+
+@dataclass(frozen=True)
+class AdmittedOutputRead:
+ output_path: str
+ value_text: str
+ label: str
+
+
+def admitted_requested_output_reads(
+ reads: Sequence[RequestedOutputRead],
+) -> tuple[tuple[AdmittedOutputRead, ...], list[dict[str, str]]]:
+ """Admit the designations this turn may act on, and say why the rest were refused.
+
+ Capture and the designation verifier read the same admission, so a turn cannot seed a target the
+ verifier would have rejected or probe one capture already addressed.
+ """
+ admitted: list[AdmittedOutputRead] = []
+ rejected: list[dict[str, str]] = []
+ seen_paths: set[str] = set()
+ if len(reads) > _MAX_REQUESTED_OUTPUT_READS:
+ rejected.append({"output_path": "", "reason": f"only-first-{_MAX_REQUESTED_OUTPUT_READS}-reads-verified"})
+ for read in reads[:_MAX_REQUESTED_OUTPUT_READS]:
+ raw_path = str(read.get("output_path") or "").strip()
+ value_text = str(read.get("value_text") or "").strip()
+ label = str(read.get("label") or "").strip()
+ if not raw_path or not value_text:
+ rejected.append({"output_path": raw_path, "reason": "malformed"})
+ continue
+ output_path = raw_path if raw_path.startswith("output.") else f"output.{raw_path}"
+ if output_path in seen_paths:
+ rejected.append({"output_path": output_path, "reason": "duplicate-output-path"})
+ continue
+ seen_paths.add(output_path)
+ admitted.append(AdmittedOutputRead(output_path=output_path, value_text=value_text, label=label))
+ return tuple(admitted), rejected
+
+
def _requested_capture_targets(copilot_ctx: object) -> tuple[str, ...]:
"""The labels this turn asked for, so capture resolves them rather than guessing which relations matter."""
if not isinstance(copilot_ctx, AgentContext):
@@ -779,6 +828,8 @@ async def _composition_get_structured_evidence_result(
inspected_url: str,
current_url: str,
timeout_seconds: float | None = None,
+ requested_targets: tuple[str, ...] | None = None,
+ witnessed_values: tuple[str, ...] = (),
) -> tuple[dict[str, Any] | None, str | None]:
"""Capture composition evidence and preserve why the observation failed.
@@ -794,7 +845,12 @@ async def _composition_get_structured_evidence_result(
evaluate = _call_internal_browser_tool(
server,
"skyvern_evaluate",
- {"expression": composition_structured_evidence_expression(_requested_capture_targets(copilot_ctx))},
+ {
+ "expression": composition_structured_evidence_expression(
+ _requested_capture_targets(copilot_ctx) if requested_targets is None else requested_targets,
+ witnessed_values,
+ )
+ },
)
if timeout_seconds is None:
result, outcome = await evaluate
diff --git a/skyvern/forge/sdk/copilot/tools/composition_capture.py b/skyvern/forge/sdk/copilot/tools/composition_capture.py
index 6a57cfcda..f6536dbea 100644
--- a/skyvern/forge/sdk/copilot/tools/composition_capture.py
+++ b/skyvern/forge/sdk/copilot/tools/composition_capture.py
@@ -16,7 +16,11 @@ from skyvern.forge.sdk.copilot.challenge_evidence import ChallengeKind, challeng
from skyvern.forge.sdk.copilot.composition_browser_expressions import (
COMPOSITION_VISUAL_OBSTRUCTION_CANDIDATES_EXPRESSION as _COMPOSITION_VISUAL_OBSTRUCTION_CANDIDATES_EXPRESSION,
)
+from skyvern.forge.sdk.copilot.composition_browser_expressions import (
+ value_witness_read_expression,
+)
from skyvern.forge.sdk.copilot.composition_evidence import (
+ _MAX_KEY_VALUE_RELATIONS,
CONSENT_OBSTRUCTION_KIND,
has_bounded_page_schema,
has_satisfiable_collapsed_disclosure_path,
@@ -27,11 +31,13 @@ from skyvern.forge.sdk.copilot.composition_evidence import (
page_records_share_location,
parse_composition_html,
stamp_page_evidence_provenance,
+ unresolved_requested_targets,
)
from skyvern.forge.sdk.copilot.context import CopilotContext
-from skyvern.forge.sdk.copilot.enforcement import _RECENT_TOOL_OUTPUT_CHAR_CAP
+from skyvern.forge.sdk.copilot.enforcement import _RECENT_TOOL_OUTPUT_CHAR_CAP, _requested_output_labels_by_path
from skyvern.forge.sdk.copilot.llm_config import resolve_fast_copilot_handler
from skyvern.forge.sdk.copilot.loop_detection import record_tool_step_result_for_ctx
+from skyvern.forge.sdk.copilot.output_extraction_plan import _exact_path, _value_witness_bindings
from skyvern.forge.sdk.copilot.runtime import (
SENSITIVE_ORIGIN_ACTIVE_RUN_PAGE_ERROR,
SENSITIVE_ORIGIN_PAGE_ERROR,
@@ -63,6 +69,7 @@ from skyvern.forge.sdk.copilot.tracing_setup import copilot_span
from ._shared import (
_CURRENT_PAGE_INSPECTION_TARGETS,
_DISCOVERY_PER_CALL_TIMEOUT_SECONDS,
+ AdmittedOutputRead,
_append_flow_evidence,
_call_internal_browser_tool,
_composition_evidence_page_url,
@@ -77,7 +84,7 @@ from ._shared import (
from .blockers import _allows_post_run_current_page_inspection_budget_bypass
from .discovery import _resolve_discovery_entry_url
from .guardrails import _authority_tool_error
-from .mcp_hooks import _bind_login_credential_for_observed_url
+from .mcp_hooks import _bind_login_credential_for_observed_url, _record_scouted_read
from .scouting import (
_clear_pending_browser_interaction_observation,
_consume_pending_browser_interaction_observation,
@@ -177,7 +184,7 @@ def _composition_extract_screenshot_b64(result: dict[str, Any]) -> str:
return ""
-def _composition_visual_prompt(evidence: dict[str, Any]) -> str:
+def _composition_visual_prompt(evidence: dict[str, Any], requested_targets: tuple[str, ...] = ()) -> str:
# The DOM challenge_state / anti-bot token hits are deliberately NOT fed in:
# the vision pass classifies obstruction-vs-challenge from the screenshot
# alone instead of confirming the detector's anchor.
@@ -189,13 +196,23 @@ def _composition_visual_prompt(evidence: dict[str, Any]) -> str:
"page_obstruction_count": len(evidence.get("page_obstructions") or []),
"visual_obstruction_candidate_count": len(evidence.get("visual_obstruction_candidates") or []),
"schema_empty_page": evidence.get("schema_empty_page") is True,
+ "requested_labels": list(requested_targets),
}
+ requested_values_key = "requested_values, " if requested_targets else ""
+ requested_values_rule = (
+ "requested_values is a list of {label, value} objects, at most one per entry in the DOM "
+ "context's requested_labels, carrying that label's value exactly as rendered on screen; omit "
+ "a label whose value is not legibly visible. "
+ if requested_targets
+ else ""
+ )
return (
"Summarize this screenshot for Workflow Copilot build-time page evidence. "
- "Return JSON only with keys: summary, challenge_detected, challenge_kind, "
+ f"Return JSON only with keys: summary, {requested_values_key}challenge_detected, challenge_kind, "
"challenge_location, submit_blocked, blocked_submit_controls, empty_page_visible, "
"loading_state_visible, page_obstruction_detected, obstruction_kind, "
"obstruction_location, underlying_page_blocked, visible_dismiss_controls, omissions. "
+ f"{requested_values_rule}"
"In summary, include the visible page state that would help verify an end-state outcome, "
"such as cart items, "
"record rows, visible identifiers, quantities, statuses, prices, confirmations, search results, "
@@ -234,6 +251,21 @@ async def _composition_visual_handler(ctx: CopilotContext) -> Any | None:
)
+def _normalize_requested_values(value: Any) -> list[dict[str, str]]:
+ """Keep only label/value string pairs, in the order the vision pass returned them."""
+ if not isinstance(value, list):
+ return []
+ pairs = [(item.get("label"), item.get("value")) for item in value if isinstance(item, dict)]
+ kept: list[dict[str, str]] = []
+ for label, observed in pairs:
+ if not isinstance(label, str) or not isinstance(observed, str) or not label.strip() or not observed.strip():
+ continue
+ kept.append({"label": label.strip()[:240], "value": observed.strip()[:240]})
+ if len(kept) >= _MAX_KEY_VALUE_RELATIONS:
+ break
+ return kept
+
+
def _normalize_visual_summary(value: Any) -> dict[str, Any] | None:
if not isinstance(value, dict):
return None
@@ -253,6 +285,7 @@ def _normalize_visual_summary(value: Any) -> dict[str, Any] | None:
omissions = value.get("omissions")
return {
"summary": summary if isinstance(summary, str) else "",
+ "requested_values": _normalize_requested_values(value.get("requested_values")),
"challenge_detected": challenge_detected if isinstance(challenge_detected, bool) else None,
"challenge_kind": challenge_kind if isinstance(challenge_kind, str) else "",
"challenge_location": challenge_location if isinstance(challenge_location, str) else "",
@@ -278,6 +311,7 @@ async def _composition_summarize_screenshot(
*,
evidence: dict[str, Any],
screenshot_b64: str,
+ requested_targets: tuple[str, ...] = (),
) -> tuple[dict[str, Any] | None, str | None]:
handler = await _composition_visual_handler(ctx)
if handler is None:
@@ -289,7 +323,7 @@ async def _composition_summarize_screenshot(
try:
response = await asyncio.wait_for(
handler(
- prompt=_composition_visual_prompt(evidence),
+ prompt=_composition_visual_prompt(evidence, requested_targets),
prompt_name=_COMPOSITION_VISUAL_SUMMARY_PROMPT_NAME,
screenshots=[screenshot_bytes],
organization_id=getattr(ctx, "organization_id", None),
@@ -308,22 +342,26 @@ async def _composition_summarize_screenshot(
return normalized, None
-async def _augment_composition_evidence_with_visual_fallback(
+@dataclass(frozen=True)
+class VisualSummaryCapture:
+ summary: dict[str, Any] | None = None
+ error: str | None = None
+ frame: CapturedFrame | None = None
+ screenshot_failure: str | None = None
+
+
+async def _composition_capture_visual_summary(
ctx: CopilotContext,
evidence: dict[str, Any],
-) -> tuple[dict[str, Any], CapturedFrame | None]:
+ requested_targets: tuple[str, ...] = (),
+) -> VisualSummaryCapture:
capture_started_at = time.monotonic()
capture_url = evidence.get("current_url") or evidence.get("inspected_url")
capture_session_id = getattr(ctx, "browser_session_id", None)
screenshot_result = await _composition_get_screenshot(ctx, dispatch_session_id=capture_session_id)
if not screenshot_result.get("ok"):
- return (
- _composition_add_visual_capture_omission(
- evidence,
- "screenshot_capture_failed",
- f"screenshot_capture_failed: {screenshot_result.get('error', 'unknown')}",
- ),
- None,
+ return VisualSummaryCapture(
+ screenshot_failure=f"screenshot_capture_failed: {screenshot_result.get('error', 'unknown')}"
)
screenshot_b64 = _composition_extract_screenshot_b64(screenshot_result)
producer_url, producer_session_id, session_binding = screenshot_result_facts(
@@ -349,9 +387,28 @@ async def _augment_composition_evidence_with_visual_fallback(
ctx,
evidence=evidence,
screenshot_b64=screenshot_b64,
+ requested_targets=requested_targets,
)
- merged = merge_visual_composition_evidence(evidence, visual_summary=visual_summary, visual_error=visual_error)
- return merged, captured_frame
+ return VisualSummaryCapture(summary=visual_summary, error=visual_error, frame=captured_frame)
+
+
+def _merge_visual_summary_capture(
+ evidence: dict[str, Any],
+ captured: VisualSummaryCapture,
+) -> dict[str, Any]:
+ if captured.screenshot_failure is not None:
+ return _composition_add_visual_capture_omission(
+ evidence, "screenshot_capture_failed", captured.screenshot_failure
+ )
+ return merge_visual_composition_evidence(evidence, visual_summary=captured.summary, visual_error=captured.error)
+
+
+async def _augment_composition_evidence_with_visual_fallback(
+ ctx: CopilotContext,
+ evidence: dict[str, Any],
+) -> tuple[dict[str, Any], CapturedFrame | None]:
+ captured = await _composition_capture_visual_summary(ctx, evidence)
+ return _merge_visual_summary_capture(evidence, captured), captured.frame
def _composition_add_evidence_omission(evidence: dict[str, Any], message: str) -> dict[str, Any]:
@@ -393,11 +450,16 @@ async def _composition_evidence_after_navigation_failure(
*,
inspected_url: str,
navigation_error: str,
+ requested_reads: tuple[AdmittedOutputRead, ...] = (),
) -> tuple[dict[str, Any], CapturedFrame | None] | None:
current_url, _ = await _fallback_page_info(ctx)
current_url = current_url or inspected_url
+ requested_targets = _seeded_capture_targets(ctx, requested_reads)
structured, structured_error = await _composition_get_structured_evidence_result(
- ctx, inspected_url=inspected_url, current_url=current_url
+ ctx,
+ inspected_url=inspected_url,
+ current_url=current_url,
+ requested_targets=requested_targets,
)
if structured is not None and has_bounded_page_schema(structured):
evidence = _composition_add_inspection_warning(
@@ -431,7 +493,7 @@ async def _composition_evidence_after_navigation_failure(
html,
inspected_url=inspected_url,
current_url=current_url,
- requested_targets=_requested_capture_targets(ctx),
+ requested_targets=requested_targets,
)
evidence = _composition_add_inspection_warning(
evidence,
@@ -615,6 +677,200 @@ async def _augment_composition_evidence_with_computed_obstruction_candidates(
return _merge_visual_obstruction_candidates(evidence, candidates)
+@dataclass(frozen=True)
+class ValueWitness:
+ label: str
+ value: str
+ output_path: str
+
+
+def _seeded_capture_targets(copilot_ctx: object, requested_reads: tuple[AdmittedOutputRead, ...]) -> tuple[str, ...]:
+ """The labels this turn asked capture to resolve, from declared criteria and this call's designations.
+
+ Only a label can resolve: a target is answered by a relation whose key_text equals it, and no pass
+ mints a relation keyed by a bare magnitude.
+ """
+ targets = list(_requested_capture_targets(copilot_ctx))
+ for read in requested_reads:
+ if read.label and read.label not in targets:
+ targets.append(read.label)
+ return tuple(targets)
+
+
+def _seeded_label_owners(copilot_ctx: object, requested_reads: tuple[AdmittedOutputRead, ...]) -> dict[str, str]:
+ """Each requested label exactly one output path claims, keyed to that path."""
+ paths_by_label: dict[str, set[str]] = {}
+ for read in requested_reads:
+ if read.label:
+ paths_by_label.setdefault(read.label, set()).add(read.output_path)
+ owned = {label: next(iter(paths)) for label, paths in paths_by_label.items() if len(paths) == 1}
+ owned.update(_singly_owned_requested_labels(copilot_ctx))
+ return owned
+
+
+def _singly_owned_requested_labels(copilot_ctx: object) -> dict[str, str]:
+ """Requested labels exactly one output path owns, keyed to that path."""
+ if not isinstance(copilot_ctx, AgentContext):
+ return {}
+ labels_by_path = _requested_output_labels_by_path(copilot_ctx)
+ owned: dict[str, str] = {}
+ for labels in labels_by_path.values():
+ for label in labels:
+ path = _exact_path(label, labels_by_path)
+ if path is not None and label.strip():
+ owned[label.strip()] = path
+ return owned
+
+
+def _witnesses_from_visual_summary(
+ visual_summary: dict[str, Any],
+ owned_labels: dict[str, str],
+ unresolved: tuple[str, ...],
+) -> tuple[list[ValueWitness], int]:
+ """Pair each unresolved label with the value the screenshot read for it, keeping only the unambiguous.
+
+ Aliases of one output reading one value address the same tile once, while a value two outputs
+ claim, or an output whose aliases read different values, names no single element.
+ """
+ # The pass echoes the label as the tile renders it, while the request mints it case-folded.
+ wanted = {target.strip().casefold() for target in unresolved}
+ owners_by_folded_label = {label.strip().casefold(): path for label, path in owned_labels.items()}
+ seen: set[tuple[str, str]] = set()
+ by_value: dict[str, list[ValueWitness]] = {}
+ dropped = 0
+ for pair in visual_summary.get("requested_values") or []:
+ label = str(pair.get("label") or "").strip()
+ value = str(pair.get("value") or "").strip()
+ if not label or not value:
+ continue
+ folded_label = label.casefold()
+ if folded_label not in wanted or folded_label not in owners_by_folded_label:
+ dropped += 1
+ continue
+ if (folded_label, value) in seen:
+ continue
+ seen.add((folded_label, value))
+ by_value.setdefault(value, []).append(ValueWitness(label, value, owners_by_folded_label[folded_label]))
+ witnesses: list[ValueWitness] = []
+ for owners in by_value.values():
+ if len({owner.output_path for owner in owners}) == 1:
+ witnesses.append(owners[0])
+ dropped += len(owners) - 1
+ else:
+ dropped += len(owners)
+ values_by_path: dict[str, set[str]] = {}
+ for witness in witnesses:
+ values_by_path.setdefault(witness.output_path, set()).add(witness.value)
+ kept = [witness for witness in witnesses if len(values_by_path[witness.output_path]) == 1]
+ return kept, dropped + len(witnesses) - len(kept)
+
+
+async def _evaluate_witness_read(copilot_ctx: object, expression: str) -> str | None:
+ server = getattr(copilot_ctx, "discovery_mcp_server", None)
+ if server is None:
+ return None
+ try:
+ result = await asyncio.wait_for(
+ server.call_internal_tool("skyvern_evaluate", {"expression": expression}),
+ timeout=_DISCOVERY_PER_CALL_TIMEOUT_SECONDS,
+ )
+ except Exception:
+ return None
+ if not isinstance(result, dict) or not result.get("ok"):
+ return None
+ value = (result.get("data") or {}).get("result")
+ return value if isinstance(value, str) else None
+
+
+async def _value_witness_records(
+ copilot_ctx: object,
+ evidence: dict[str, Any],
+ witnesses: list[ValueWitness],
+) -> list[dict[str, str]]:
+ """The page read that returns each witnessed value, kept only when running it returns that value.
+
+ The recorded expression is emitted verbatim into generated workflow code, so an unexecuted read
+ is a claim about the page rather than an observation of it.
+ """
+ labels_by_path = {witness.output_path: witness.label for witness in witnesses}
+ values_by_path = {witness.output_path: witness.value for witness in witnesses}
+ bindings = _value_witness_bindings(
+ evidence,
+ values_by_path,
+ channel_intact=evidence.get("key_value_relations_truncated") is not True,
+ )
+ records: list[dict[str, str]] = []
+ for binding in bindings:
+ expression = value_witness_read_expression(
+ binding.selector,
+ binding.selector_count,
+ binding.selector_index,
+ binding.child_index,
+ )
+ value = values_by_path[binding.output_path]
+ if await _evaluate_witness_read(copilot_ctx, expression) != value:
+ continue
+ records.append(
+ {
+ "label": labels_by_path[binding.output_path],
+ "value": value,
+ "output_path": binding.output_path,
+ "expression": expression,
+ }
+ )
+ return records
+
+
+async def _witness_unresolved_requested_targets(
+ copilot_ctx: object,
+ evidence: dict[str, Any],
+ *,
+ captured: VisualSummaryCapture,
+ unresolved: tuple[str, ...],
+ owned_labels: dict[str, str],
+ requested_targets: tuple[str, ...],
+ inspected_url: str,
+ current_url: str,
+) -> dict[str, Any]:
+ """Re-read the page for the values this call's screenshot just read off the unresolved tiles.
+
+ The model cannot run this itself, because a live figure ticks between calls and only the capture
+ that took the frame can key a DOM pass on what the frame showed.
+ """
+ summary = captured.summary or {}
+ witnesses, dropped = _witnesses_from_visual_summary(summary, owned_labels, unresolved)
+ LOG.info(
+ "copilot_composition_requested_values_seen",
+ unresolved_target_count=len(unresolved),
+ pair_count=len(summary.get("requested_values") or []),
+ witness_count=len(witnesses),
+ dropped_count=dropped,
+ )
+ if not witnesses:
+ return evidence
+ witnessed_evidence, witness_error = await _composition_get_structured_evidence_result(
+ copilot_ctx,
+ inspected_url=inspected_url,
+ current_url=current_url,
+ requested_targets=requested_targets,
+ witnessed_values=tuple(witness.value for witness in witnesses),
+ )
+ if witnessed_evidence is None:
+ LOG.info("copilot_composition_value_witness_extract_failed", error_present=bool(witness_error))
+ return evidence
+ merged = _merge_visual_summary_capture(witnessed_evidence, captured)
+ records = await _value_witness_records(copilot_ctx, merged, witnesses)
+ if not records:
+ LOG.info("copilot_composition_value_witness_records_dropped", witness_count=len(witnesses))
+ return evidence
+ # The replacement has to clear the same gate the retry loop cleared for the packet it displaces.
+ if not _composition_capture_settled(merged):
+ LOG.info("copilot_composition_value_witness_replacement_unsettled", witness_count=len(witnesses))
+ return evidence
+ merged["value_witnesses"] = records
+ return merged
+
+
def _composition_capture_settled(evidence: dict[str, Any]) -> bool:
return (
has_bounded_page_schema(evidence) or has_satisfiable_collapsed_disclosure_path(evidence)
@@ -626,19 +882,25 @@ async def _capture_composition_evidence(
*,
inspected_url: str,
current_url: str,
+ requested_reads: tuple[AdmittedOutputRead, ...] = (),
) -> CompositionEvidenceCapture:
"""Capture page evidence, using HTML only to enrich a valid but unsettled structured packet."""
capture_session_id = copilot_ctx.browser_session_id if isinstance(copilot_ctx, AgentContext) else None
capture_session_generation = (
copilot_ctx.browser_session_continuity_generation if isinstance(copilot_ctx, AgentContext) else None
)
+ requested_targets = _seeded_capture_targets(copilot_ctx, requested_reads)
+ owned_labels = _seeded_label_owners(copilot_ctx, requested_reads)
evidence: dict[str, Any] | None = None
html_truncated = False
used_structured = False
skip_raw = False
for attempt in range(_COMPOSITION_HOLLOW_RECAPTURE_RETRIES + 1):
structured, structured_error = await _composition_get_structured_evidence_result(
- copilot_ctx, inspected_url=inspected_url, current_url=current_url
+ copilot_ctx,
+ inspected_url=inspected_url,
+ current_url=current_url,
+ requested_targets=requested_targets,
)
if structured_error is not None:
if evidence is not None:
@@ -675,7 +937,7 @@ async def _capture_composition_evidence(
html,
inspected_url=inspected_url,
current_url=current_url,
- requested_targets=_requested_capture_targets(copilot_ctx),
+ requested_targets=requested_targets,
)
used_structured = False
if _composition_capture_settled(evidence):
@@ -688,11 +950,28 @@ async def _capture_composition_evidence(
if evidence is not None and not used_structured:
evidence = await _augment_composition_evidence_with_computed_obstruction_candidates(copilot_ctx, evidence)
frame: CapturedFrame | None = None
+ unresolved = unresolved_requested_targets(evidence, requested_targets) if evidence is not None else ()
if evidence is not None and (
page_evidence_needs_visual_fallback(evidence)
or (evidence.get("schema_empty_page") is True and not has_bounded_page_schema(evidence))
+ or (used_structured and unresolved)
):
- evidence, frame = await _augment_composition_evidence_with_visual_fallback(copilot_ctx, evidence)
+ captured = await _composition_capture_visual_summary(copilot_ctx, evidence, unresolved)
+ merged = _merge_visual_summary_capture(evidence, captured)
+ frame = captured.frame
+ if used_structured and unresolved and captured.summary is not None:
+ evidence = await _witness_unresolved_requested_targets(
+ copilot_ctx,
+ merged,
+ captured=captured,
+ unresolved=unresolved,
+ owned_labels=owned_labels,
+ requested_targets=requested_targets,
+ inspected_url=inspected_url,
+ current_url=current_url,
+ )
+ else:
+ evidence = merged
if (
isinstance(copilot_ctx, AgentContext)
and evidence is not None
@@ -843,18 +1122,84 @@ def _same_inspect_target(live_url: str | None, target_url: str | None) -> bool:
async def _inspect_page_for_composition_impl(
copilot_ctx: Any,
target_url: str,
+ requested_reads: tuple[AdmittedOutputRead, ...] = (),
) -> dict[str, Any]:
# Named navigation is the only route that may release sensitive-page custody. Keep navigation,
# release, capture, and evidence admission atomic with sensitive-run registration so this call
# cannot clear a newer run's taint after its navigation returns.
async with browser_page_custody_lock(copilot_ctx):
async with browser_evidence_commit_lock(copilot_ctx):
- return await _inspect_page_for_composition_under_custody(copilot_ctx, target_url)
+ return await _inspect_page_for_composition_under_custody(copilot_ctx, target_url, requested_reads)
+
+
+def _record_value_witnesses(
+ copilot_ctx: object,
+ evidence: dict[str, Any],
+ *,
+ url: str,
+ capture_session_id: str | None,
+ run_page_source_session_id: str | None,
+) -> None:
+ """Keep the witnessed pairs this capture could record as scouted reads, and drop the rest.
+
+ A witness left in the packet cancels the designation probe for its path, so a pair read through
+ the run's browser, or one whose session moved mid-capture, must not survive here.
+ """
+ records = evidence.get("value_witnesses")
+ if not isinstance(records, list) or not records:
+ _drop_uncorroborated_screenshot_values(evidence)
+ return
+ provenance = evidence.get("browser_session_provenance")
+ kept: list[dict[str, Any]] = []
+ same_session = (
+ isinstance(copilot_ctx, AgentContext)
+ and run_page_source_session_id is None
+ and copilot_ctx.browser_session_id == capture_session_id
+ and not (isinstance(provenance, dict) and provenance.get("mixed") is True)
+ )
+ if same_session and isinstance(copilot_ctx, AgentContext):
+ for record in records:
+ if not isinstance(record, dict):
+ continue
+ output_path = str(record.get("output_path") or "")
+ recorded = _record_scouted_read(
+ copilot_ctx,
+ expression=str(record.get("expression") or ""),
+ data={"result": record.get("value")},
+ url=url,
+ declared_output_path=output_path or None,
+ )
+ # `_record_scouted_read` may bind the fact elsewhere; a witness only cancels the
+ # designation probe for the path the read actually answered.
+ bound_output_path = str(recorded.get("read_output_path") or "") if recorded is not None else ""
+ LOG.info(
+ "copilot_composition_value_witness_recorded",
+ recorded=recorded is not None,
+ declared_output_path_present=bool(output_path),
+ bound_to_declared_path=bool(output_path) and bound_output_path == output_path,
+ )
+ if recorded is not None and output_path and bound_output_path == output_path:
+ kept.append({key: value for key, value in record.items() if key != "expression"})
+ if kept:
+ evidence["value_witnesses"] = kept
+ else:
+ _drop_uncorroborated_screenshot_values(evidence)
+
+
+def _drop_uncorroborated_screenshot_values(evidence: dict[str, Any]) -> None:
+ """Take the screenshot's label/value pairs back out once no witness survived the page lookup.
+
+ The pairs are what the frame appeared to say. Leaving them in the packet offers the model a
+ magnitude nothing on the page corroborated, which it can copy into a step instead of reading.
+ """
+ evidence.pop("value_witnesses", None)
+ evidence.pop("requested_values", None)
async def _inspect_page_for_composition_under_custody(
copilot_ctx: Any,
target_url: str,
+ requested_reads: tuple[AdmittedOutputRead, ...] = (),
) -> dict[str, Any]:
"""Inspect a known target page and store form/search evidence on ctx.
@@ -953,7 +1298,10 @@ async def _inspect_page_for_composition_under_custody(
)
else:
capture = await _capture_composition_evidence(
- copilot_ctx, inspected_url=entry_url, current_url=current_url
+ copilot_ctx,
+ inspected_url=entry_url,
+ current_url=current_url,
+ requested_reads=requested_reads,
)
evidence, observation_error, visual_fallback_frame = _capture_result_parts(capture)
else:
@@ -979,6 +1327,7 @@ async def _inspect_page_for_composition_under_custody(
copilot_ctx,
inspected_url=entry_url,
navigation_error=nav_error,
+ requested_reads=requested_reads,
)
if failure_capture is None:
result = {
@@ -994,7 +1343,10 @@ async def _inspect_page_for_composition_under_custody(
current_url = _discovery_extract_current_url(nav_result, entry_url)
clear_sensitive_origin_page_taint(copilot_ctx)
capture = await _capture_composition_evidence(
- copilot_ctx, inspected_url=entry_url, current_url=current_url
+ copilot_ctx,
+ inspected_url=entry_url,
+ current_url=current_url,
+ requested_reads=requested_reads,
)
evidence, observation_error, visual_fallback_frame = _capture_result_parts(capture)
@@ -1094,6 +1446,13 @@ async def _inspect_page_for_composition_under_custody(
observation_step = _append_flow_evidence(copilot_ctx, evidence, reached_via=reached_via)
if observation_step is None:
LOG.warning("copilot_flow_evidence_append_failed_no_trajectory")
+ _record_value_witnesses(
+ copilot_ctx,
+ evidence,
+ url=str(evidence.get("current_url") or current_url or ""),
+ capture_session_id=capture_session_id,
+ run_page_source_session_id=run_page_source_session_id,
+ )
# Surface the reached page at the top level so the model registers that the
# inspection already navigated there and does not re-issue navigate_browser.
current_url = evidence.get("current_url") or evidence.get("inspected_url") or ""
diff --git a/skyvern/forge/sdk/db/models.py b/skyvern/forge/sdk/db/models.py
index 5cf64cf29..3923e7b99 100644
--- a/skyvern/forge/sdk/db/models.py
+++ b/skyvern/forge/sdk/db/models.py
@@ -1235,11 +1235,14 @@ class WorkflowRunBlockModel(Base):
# Accumulates LLM cost for block-scoped calls (no step/thought attribution).
llm_cost = Column(Numeric, default=0, nullable=False)
- # Per-block cached-script execution state. Written (via the writer bridge
- # in `services/script_service.py::_update_workflow_block`) when a script
- # block falls back to AI mid-execution. Always null for blocks that ran
- # cleanly from cache or were always-agent. Mirrors the `script_run`
- # column on `WorkflowRunModel` but at block granularity.
+ # Per-block cached-script execution state, and the execution-mode marker:
+ # non-null iff the block was created by the cached-script path. Stamped with
+ # the initial `ai_fallback_triggered=false` state at block creation in
+ # `services/script_service.py`, then overwritten with `true` by the writer
+ # bridge (`_update_workflow_block`) if the block falls back to AI
+ # mid-execution. Null for always-agent blocks, whose execution mode is
+ # instead carried by `engine`. Mirrors the `script_run` column on
+ # `WorkflowRunModel` but at block granularity.
script_run = Column(JSON, nullable=True)
# Scalar mirror of output["downloaded_files"] length: the JSON output column is
diff --git a/skyvern/forge/sdk/db/repositories/observer.py b/skyvern/forge/sdk/db/repositories/observer.py
index 7c6ec17ca..adcc4db11 100644
--- a/skyvern/forge/sdk/db/repositories/observer.py
+++ b/skyvern/forge/sdk/db/repositories/observer.py
@@ -417,6 +417,7 @@ class ObserverRepository(BaseRepository):
engine: RunEngine | None = None,
current_value: str | None = None,
current_index: int | None = None,
+ ai_fallback_triggered: bool | None = None,
) -> WorkflowRunBlock:
if output is not None:
output = truncate_oversized_jsonb_value(
@@ -437,6 +438,9 @@ class ObserverRepository(BaseRepository):
engine=engine,
current_value=current_value,
current_index=current_index,
+ script_run=ScriptRunResponse(ai_fallback_triggered=ai_fallback_triggered).model_dump(mode="json")
+ if ai_fallback_triggered is not None
+ else None,
)
session.add(new_workflow_run_block)
await session.commit()
diff --git a/skyvern/services/script_service.py b/skyvern/services/script_service.py
index 1f142f232..2cafa4320 100644
--- a/skyvern/services/script_service.py
+++ b/skyvern/services/script_service.py
@@ -651,6 +651,12 @@ async def _create_workflow_block_run_and_task(
label=label,
current_value=current_value_str,
current_index=current_index_val,
+ # Blocks created here always execute from a cached script and never resolve an engine,
+ # so `engine IS NULL` alone cannot distinguish them from an agent block whose engine was
+ # never written. Stamping the initial (no-fallback-yet) state at creation makes
+ # `script_run` the execution-mode marker; the fallback paths overwrite it with True.
+ # Mirrors the run-level `ai_fallback_triggered=False` initialization in `execute_script`.
+ ai_fallback_triggered=False,
)
workflow_run_block_id = workflow_run_block.workflow_run_block_id
diff --git a/tests/unit/test_copilot_composition_evidence.py b/tests/unit/test_copilot_composition_evidence.py
index b0f2c6439..c8c406cad 100644
--- a/tests/unit/test_copilot_composition_evidence.py
+++ b/tests/unit/test_copilot_composition_evidence.py
@@ -63,6 +63,7 @@ from skyvern.forge.sdk.copilot.composition_evidence import (
page_evidence_needs_visual_fallback,
parse_composition_html,
parse_composition_structured,
+ unresolved_requested_targets,
)
from skyvern.forge.sdk.copilot.output_extraction_plan import _relation_label_child_index, candidate_page_context
from skyvern.forge.sdk.copilot.page_identity import page_location_fingerprint
@@ -7245,3 +7246,37 @@ def test_composition_gate_falls_back_to_observed_page_for_a_stale_ref_on_an_unre
)
assert composition_page_evidence_error(ctx, workflow_yaml) is None
+
+
+def test_merge_visual_composition_evidence_keeps_only_typed_requested_value_pairs() -> None:
+ parsed = parse_composition_html(
+ "<html><body><div>Sessions Started</div></body></html>",
+ inspected_url="https://example.com/metrics",
+ current_url="https://example.com/metrics",
+ )
+
+ merged = merge_visual_composition_evidence(
+ parsed,
+ visual_summary={
+ "summary": "One metric panel.",
+ "requested_values": [
+ {"label": "Sessions Started", "value": "72.51k"},
+ {"label": "Failure rate", "value": ""},
+ {"label": 7, "value": "3"},
+ "Sessions Started=72.51k",
+ ],
+ },
+ )
+
+ assert merged["requested_values"] == [{"label": "Sessions Started", "value": "72.51k"}]
+
+
+def test_unresolved_requested_targets_ignores_case_and_invisible_relations() -> None:
+ evidence = {
+ "key_value_relations": [
+ {"key_text": "sessions started", "value_text": "72.51k", "visible": True, "value_visible": True},
+ {"key_text": "Failure rate", "value_text": "0.4%", "visible": True, "value_visible": False},
+ ]
+ }
+
+ assert unresolved_requested_targets(evidence, ("Sessions Started", "Failure rate", " ")) == ("Failure rate",)
diff --git a/tests/unit/test_copilot_composition_scrape.py b/tests/unit/test_copilot_composition_scrape.py
index a295593fd..676887016 100644
--- a/tests/unit/test_copilot_composition_scrape.py
+++ b/tests/unit/test_copilot_composition_scrape.py
@@ -6,6 +6,7 @@ served in a real scout because the agent acts between inspects.)
from __future__ import annotations
import asyncio
+import base64
import json
import time
from types import SimpleNamespace
@@ -21,9 +22,14 @@ from skyvern.forge.sdk.copilot.composition_evidence import (
has_bounded_page_schema,
parse_composition_structured,
)
+from skyvern.forge.sdk.copilot.context import CopilotContext
+from skyvern.forge.sdk.copilot.request_policy import CompletionCriterion, RequestPolicy
from skyvern.forge.sdk.copilot.tools import _normalized_inspect_url, _same_inspect_target
from skyvern.forge.sdk.copilot.tools import _shared as shared_module
-from skyvern.forge.sdk.copilot.tools._shared import _composition_get_structured_evidence_result
+from skyvern.forge.sdk.copilot.tools._shared import (
+ _composition_get_structured_evidence_result,
+ admitted_requested_output_reads,
+)
from skyvern.forge.sdk.copilot.tools.scouting import _page_evidence_location_fingerprint
from tests.unit.copilot_test_helpers import make_copilot_ctx
@@ -752,3 +758,578 @@ def test_inspection_regression_guard_uses_current_location_after_leave_and_retur
assert refusal is not None
assert refusal["data"]["current_url"] == reached_url
assert refusal["data"]["observation_step"] == 0
+
+
+def _tile_packet(*, with_relation: bool, match_count: int = 1, position: int = 0) -> dict:
+ relations = (
+ [
+ {
+ "key_text": "Sessions Started",
+ "value_text": "72.51k",
+ "container_selector": "div.query-value__container",
+ "container_match_count": match_count,
+ "container_position": position,
+ "value_child_index": 0,
+ "direct_child_count": 1,
+ "visible": True,
+ "value_visible": True,
+ "selector_candidates": [],
+ "identity": {},
+ }
+ ]
+ if with_relation
+ else []
+ )
+ packet = parse_composition_structured(
+ {
+ "page_title": "Fleet Metrics",
+ "forms": [],
+ "navigation_targets": [{"text": "Overview", "href": "https://example.com/overview", "selector": "a"}],
+ "key_value_relations": relations,
+ },
+ inspected_url="https://example.com/metrics",
+ current_url="https://example.com/metrics",
+ )
+ assert packet is not None
+ return packet
+
+
+def _requested_tile_ctx() -> CopilotContext:
+ ctx = make_copilot_ctx()
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=[
+ CompletionCriterion(
+ id="c0",
+ outcome="return the sessions started figure",
+ output_path="output.sessions_started",
+ requested_output_label="Sessions Started",
+ )
+ ]
+ )
+ return ctx
+
+
+def _install_tile_vision(
+ monkeypatch: pytest.MonkeyPatch, calls: dict[str, int], label: str = "Sessions Started"
+) -> None:
+ async def screenshot(ctx: object, *, dispatch_session_id: object) -> dict:
+ calls["screenshot"] += 1
+ return {"ok": True, "data": {"screenshot_base64": base64.b64encode(b"frame").decode()}}
+
+ async def handler(**_kwargs: object) -> dict:
+ calls["vision"] += 1
+ return {
+ "summary": "One metric panel over a dashboard grid.",
+ "requested_values": [{"label": label, "value": "72.51k"}],
+ }
+
+ async def visual_handler(ctx: object) -> object:
+ return handler
+
+ monkeypatch.setattr(tools.composition_capture, "_composition_get_screenshot", screenshot)
+ monkeypatch.setattr(tools.composition_capture, "_composition_visual_handler", visual_handler)
+
+
+def _install_witness_read(ctx: CopilotContext, returns: str | None = "72.51k") -> list[str]:
+ expressions: list[str] = []
+
+ async def call_internal_tool(_tool_name: str, arguments: dict) -> dict:
+ expressions.append(arguments["expression"])
+ return {"ok": True, "data": {"result": returns}}
+
+ ctx.discovery_mcp_server = SimpleNamespace(call_internal_tool=call_internal_tool)
+ return expressions
+
+
+async def test_screenshot_read_value_addresses_the_tile_the_label_alone_could_not(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ calls = {"screenshot": 0, "vision": 0}
+ witnessed_per_call: list[tuple[str, ...]] = []
+
+ async def structured(ctx: object, **kwargs: object) -> tuple[dict, None]:
+ witnessed = tuple(kwargs.get("witnessed_values") or ())
+ witnessed_per_call.append(witnessed)
+ return _tile_packet(with_relation=bool(witnessed)), None
+
+ monkeypatch.setattr(tools.composition_capture, "_composition_get_structured_evidence_result", structured)
+ _install_tile_vision(monkeypatch, calls)
+ ctx = _requested_tile_ctx()
+ reads = _install_witness_read(ctx)
+
+ evidence, error = await tools._capture_composition_evidence(
+ ctx,
+ inspected_url="https://example.com/metrics",
+ current_url="https://example.com/metrics",
+ )
+
+ assert error is None
+ assert evidence is not None
+ assert (calls["screenshot"], calls["vision"]) == (1, 1)
+ assert witnessed_per_call == [(), ("72.51k",)]
+ assert evidence["requested_values"] == [{"label": "Sessions Started", "value": "72.51k"}]
+ assert [
+ (witness["label"], witness["value"], witness["output_path"]) for witness in evidence["value_witnesses"]
+ ] == [("Sessions Started", "72.51k", "output.sessions_started")]
+ assert len(reads) == 1
+ assert "div.query-value__container" in reads[0]
+ projected = tools.composition_capture.model_visible_composition_evidence(evidence)
+ assert "expression" not in projected["value_witnesses"][0]
+
+
+async def test_witness_read_that_does_not_return_the_witnessed_value_records_nothing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ calls = {"screenshot": 0, "vision": 0}
+
+ async def structured(ctx: object, **kwargs: object) -> tuple[dict, None]:
+ return _tile_packet(with_relation=bool(kwargs.get("witnessed_values"))), None
+
+ monkeypatch.setattr(tools.composition_capture, "_composition_get_structured_evidence_result", structured)
+ _install_tile_vision(monkeypatch, calls)
+ ctx = _requested_tile_ctx()
+ reads = _install_witness_read(ctx, returns="72.7k")
+
+ evidence, error = await tools._capture_composition_evidence(
+ ctx,
+ inspected_url="https://example.com/metrics",
+ current_url="https://example.com/metrics",
+ )
+
+ assert error is None
+ assert evidence is not None
+ assert len(reads) == 1
+ assert "value_witnesses" not in evidence
+
+
+ "damage",
+ [
+ {"value_truncated": True},
+ {"container_match_count": 1, "container_position": 3},
+ {"direct_child_count": 1, "value_child_index": 4},
+ ],
+)
+async def test_a_relation_whose_channel_or_coordinates_are_broken_witnesses_nothing(damage: dict) -> None:
+ relation = {
+ "key_text": "Sessions Started",
+ "value_text": "72.51k",
+ "container_selector": "div.query-value__container",
+ "container_match_count": 2,
+ "container_position": 1,
+ "value_child_index": 0,
+ "direct_child_count": 1,
+ "visible": True,
+ "value_visible": True,
+ **damage,
+ }
+ ctx = _requested_tile_ctx()
+ reads = _install_witness_read(ctx)
+
+ records = await tools.composition_capture._value_witness_records(
+ ctx,
+ {"key_value_relations": [relation]},
+ [tools.composition_capture.ValueWitness("Sessions Started", "72.51k", "output.sessions_started")],
+ )
+
+ assert records == []
+ assert reads == []
+
+
+async def test_witness_read_pins_the_selector_cardinality_it_was_observed_at(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ calls = {"screenshot": 0, "vision": 0}
+
+ async def structured(ctx: object, **kwargs: object) -> tuple[dict, None]:
+ return _tile_packet(with_relation=bool(kwargs.get("witnessed_values")), match_count=4, position=2), None
+
+ monkeypatch.setattr(tools.composition_capture, "_composition_get_structured_evidence_result", structured)
+ _install_tile_vision(monkeypatch, calls)
+ ctx = _requested_tile_ctx()
+ reads = _install_witness_read(ctx)
+
+ evidence, error = await tools._capture_composition_evidence(
+ ctx,
+ inspected_url="https://example.com/metrics",
+ current_url="https://example.com/metrics",
+ )
+
+ assert error is None
+ assert evidence is not None
+ assert len(reads) == 1
+ expression = reads[0]
+ assert "nodes.length !== 4" in expression
+ assert "nodes[2]" in expression
+ projected = tools.composition_capture.model_visible_composition_evidence(evidence)
+ assert "expression" not in projected["value_witnesses"][0]
+
+
+async def test_failed_second_look_keeps_the_evidence_the_first_one_captured(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ calls = {"screenshot": 0, "vision": 0}
+
+ async def structured(ctx: object, **kwargs: object) -> tuple[dict | None, str | None]:
+ if kwargs.get("witnessed_values"):
+ return None, "skyvern_evaluate timed out"
+ return _tile_packet(with_relation=False), None
+
+ monkeypatch.setattr(tools.composition_capture, "_composition_get_structured_evidence_result", structured)
+ _install_tile_vision(monkeypatch, calls)
+
+ evidence, error = await tools._capture_composition_evidence(
+ _requested_tile_ctx(),
+ inspected_url="https://example.com/metrics",
+ current_url="https://example.com/metrics",
+ )
+
+ assert error is None
+ assert evidence is not None
+ assert evidence["page_title"] == "Fleet Metrics"
+ assert "value_witnesses" not in evidence
+ assert "value_witness_extract_failed" not in (evidence.get("inspection_warnings") or [])
+
+
+async def test_label_the_page_already_answers_takes_no_screenshot(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls = {"screenshot": 0, "vision": 0}
+
+ async def structured(ctx: object, **_kwargs: object) -> tuple[dict, None]:
+ return _tile_packet(with_relation=True), None
+
+ monkeypatch.setattr(tools.composition_capture, "_composition_get_structured_evidence_result", structured)
+ _install_tile_vision(monkeypatch, calls)
+
+ evidence, error = await tools._capture_composition_evidence(
+ _requested_tile_ctx(),
+ inspected_url="https://example.com/metrics",
+ current_url="https://example.com/metrics",
+ )
+
+ assert error is None
+ assert evidence is not None
+ assert (calls["screenshot"], calls["vision"]) == (0, 0)
+ assert "value_witnesses" not in evidence
+
+
+async def test_structured_evidence_read_carries_the_witnessed_values_into_the_page_expression() -> None:
+ expressions: list[str] = []
+
+ async def call_internal_tool(_tool_name: str, arguments: dict) -> dict:
+ expressions.append(arguments["expression"])
+ return {"ok": True, "data": {"result": json.dumps(_bounded_example_page_payload())}}
+
+ await _composition_get_structured_evidence_result(
+ SimpleNamespace(discovery_mcp_server=SimpleNamespace(call_internal_tool=call_internal_tool)),
+ inspected_url="https://example.com/",
+ current_url="https://example.com/",
+ witnessed_values=("72.51k",),
+ )
+
+ assert 'const WITNESSED_VALUES=["72.51k"];' in expressions[0]
+
+
+def _witness_packet(**extra: object) -> dict:
+ packet: dict = {
+ "value_witnesses": [
+ {
+ "label": "Sessions Started",
+ "value": "72.51k",
+ "output_path": "output.sessions_started",
+ "expression": "x",
+ }
+ ],
+ "requested_values": [{"label": "Sessions Started", "value": "72.51k"}],
+ }
+ packet.update(extra)
+ return packet
+
+
+ ("packet", "capture_session_id"),
+ [
+ (_witness_packet(browser_session_provenance={"mixed": True}), None),
+ (_witness_packet(), "a-different-session"),
+ ],
+)
+def test_witness_the_capture_cannot_record_leaves_no_witness_in_the_packet(
+ monkeypatch: pytest.MonkeyPatch, packet: dict, capture_session_id: str | None
+) -> None:
+ recorded: list[str] = []
+ monkeypatch.setattr(
+ tools.composition_capture,
+ "_record_scouted_read",
+ lambda ctx, *, expression, data, url, declared_output_path=None: recorded.append(expression),
+ )
+ ctx = _requested_tile_ctx()
+
+ tools.composition_capture._record_value_witnesses(
+ ctx,
+ packet,
+ url="https://example.com/metrics",
+ capture_session_id=capture_session_id,
+ run_page_source_session_id=None,
+ )
+
+ assert recorded == []
+ assert "value_witnesses" not in packet
+ assert "requested_values" not in packet
+ assert tools._witnessed_output_paths(packet) == frozenset()
+
+
+def test_a_read_bound_to_another_path_leaves_its_path_to_the_designation_probe(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ tools.composition_capture,
+ "_record_scouted_read",
+ lambda ctx, *, expression, data, url, declared_output_path=None: {
+ "tool_name": "read_value",
+ "read_expression": expression,
+ "read_output_path": "output.a_different_field",
+ },
+ )
+ ctx = _requested_tile_ctx()
+ packet = _witness_packet()
+
+ tools.composition_capture._record_value_witnesses(
+ ctx,
+ packet,
+ url="https://example.com/metrics",
+ capture_session_id=ctx.browser_session_id,
+ run_page_source_session_id=None,
+ )
+
+ assert "value_witnesses" not in packet
+ assert "requested_values" not in packet
+ assert tools._witnessed_output_paths(packet) == frozenset()
+
+
+def test_a_declined_recording_leaves_its_path_to_the_designation_probe(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ tools.composition_capture,
+ "_record_scouted_read",
+ lambda ctx, *, expression, data, url, declared_output_path=None: None,
+ )
+ ctx = _requested_tile_ctx()
+ packet = _witness_packet()
+
+ tools.composition_capture._record_value_witnesses(
+ ctx,
+ packet,
+ url="https://example.com/metrics",
+ capture_session_id=ctx.browser_session_id,
+ run_page_source_session_id=None,
+ )
+
+ assert "value_witnesses" not in packet
+ assert "requested_values" not in packet
+ assert tools._witnessed_output_paths(packet) == frozenset()
+
+
+def test_two_labels_reading_one_value_witness_nothing() -> None:
+ summary = {
+ "requested_values": [
+ {"label": "Sessions Started", "value": "72.51k"},
+ {"label": "Retries Queued", "value": "72.51k"},
+ ]
+ }
+ owned = {"Sessions Started": "output.a", "Retries Queued": "output.b"}
+
+ witnesses, dropped = tools.composition_capture._witnesses_from_visual_summary(
+ summary, owned, ("Sessions Started", "Retries Queued")
+ )
+
+ assert witnesses == []
+ assert dropped == 2
+
+
+def test_two_names_for_one_output_reading_one_value_witness_it_once() -> None:
+ summary = {
+ "requested_values": [
+ {"label": "Sessions Started", "value": "72.51k"},
+ {"label": "panel metric", "value": "72.51k"},
+ ]
+ }
+ owned = {"Sessions Started": "output.sessions_started", "panel metric": "output.sessions_started"}
+
+ witnesses, dropped = tools.composition_capture._witnesses_from_visual_summary(
+ summary, owned, ("Sessions Started", "panel metric")
+ )
+
+ assert [(witness.value, witness.output_path) for witness in witnesses] == [("72.51k", "output.sessions_started")]
+ assert dropped == 1
+
+
+def test_a_designated_label_seeds_a_capture_target_and_never_a_witness_value() -> None:
+ reads = [
+ {"output_path": f"output.metric_{index}", "value_text": f"value {index}", "label": f"label {index}"}
+ for index in range(9)
+ ]
+ admitted, rejected = admitted_requested_output_reads(reads)
+
+ targets = tools.composition_capture._seeded_capture_targets(make_copilot_ctx(), admitted)
+
+ assert len(admitted) == 8
+ assert rejected[0]["reason"] == "only-first-8-reads-verified"
+ assert targets == tuple(f"label {index}" for index in range(8))
+ assert not hasattr(tools.composition_capture, "_designated_values")
+
+
+async def test_designated_read_seeds_the_screenshot_pass_when_the_turn_declared_no_criteria(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ calls = {"screenshot": 0, "vision": 0}
+ seeded_targets: list[tuple[str, ...]] = []
+ seeded_values: list[tuple[str, ...]] = []
+
+ async def structured(ctx: object, **kwargs: object) -> tuple[dict, None]:
+ seeded_targets.append(tuple(kwargs.get("requested_targets") or ()))
+ seeded_values.append(tuple(kwargs.get("witnessed_values") or ()))
+ return _tile_packet(with_relation=bool(kwargs.get("witnessed_values"))), None
+
+ monkeypatch.setattr(tools.composition_capture, "_composition_get_structured_evidence_result", structured)
+ _install_tile_vision(monkeypatch, calls, label="panel metric")
+ admitted, _ = admitted_requested_output_reads(
+ [{"output_path": "output.sessions_started", "value_text": "Sessions Started", "label": "panel metric"}]
+ )
+ ctx = make_copilot_ctx()
+ _install_witness_read(ctx)
+
+ evidence, error = await tools._capture_composition_evidence(
+ ctx,
+ inspected_url="https://example.com/metrics",
+ current_url="https://example.com/metrics",
+ requested_reads=admitted,
+ )
+
+ assert error is None
+ assert evidence is not None
+ assert seeded_targets[0] == ("panel metric",)
+ assert seeded_values[0] == ()
+ assert (calls["screenshot"], calls["vision"]) == (1, 1)
+ assert [(witness["value"], witness["output_path"]) for witness in evidence["value_witnesses"]] == [
+ ("72.51k", "output.sessions_started")
+ ]
+
+
+async def test_inspect_tool_forwards_the_designated_read_into_capture(monkeypatch: pytest.MonkeyPatch) -> None:
+ forwarded: list[tuple[str, ...]] = []
+ ctx = make_copilot_ctx()
+
+ async def capture(_ctx: object, **kwargs: object) -> tuple[dict, None]:
+ reads = kwargs.get("requested_reads") or ()
+ forwarded.append(tuple(read.output_path for read in reads))
+ return _tile_packet(with_relation=True), None
+
+ async def page_info(_ctx: object, _session_id: str | None = None) -> tuple[str, str]:
+ return "https://example.com/metrics", "Fleet Metrics"
+
+ async def navigate(_ctx: object, url: str, **_kwargs: object) -> dict[str, object]:
+ return {"ok": True, "data": {"url": url}}
+
+ monkeypatch.setattr(tools, "_authority_tool_error", lambda *_args: None)
+ monkeypatch.setattr(tools.composition_capture, "_authority_tool_error", lambda *_args: None)
+ monkeypatch.setattr(tools.composition_capture, "_fallback_page_info", page_info)
+ monkeypatch.setattr(tools.composition_capture, "_discovery_navigate", navigate)
+ monkeypatch.setattr(tools.composition_capture, "_capture_composition_evidence", capture)
+
+ for target_url in ("current_page", "https://example.com/other"):
+ raw = await tools.inspect_page_for_composition_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="inspect_page_for_composition"),
+ json.dumps(
+ {
+ "target_url": target_url,
+ "requested_output_reads": [
+ {"output_path": "sessions_started", "value_text": "Sessions Started", "label": "panel metric"}
+ ],
+ }
+ ),
+ )
+ assert json.loads(raw)["ok"] is True
+
+ assert forwarded == [("output.sessions_started",), ("output.sessions_started",)]
+
+
+async def test_witnessed_output_path_is_not_probed_again_by_the_designation_verifier() -> None:
+ probes: list[str] = []
+
+ async def call_internal_tool(_tool_name: str, arguments: dict) -> dict:
+ probes.append(arguments["expression"])
+ return {"ok": True, "data": {"result": json.dumps({"text": "72.51k", "selector_candidates": ["#v"]})}}
+
+ ctx = make_copilot_ctx()
+ ctx.discovery_mcp_server = SimpleNamespace(call_internal_tool=call_internal_tool)
+ reads = [
+ {"output_path": "output.sessions_started", "value_text": "72.51k", "label": "Sessions Started"},
+ {"output_path": "output.failures", "value_text": "3", "label": "Failures"},
+ ]
+
+ verified, unverified = await tools._verify_requested_output_reads(
+ ctx, reads, frozenset({"output.sessions_started"})
+ )
+
+ assert [fact["output_path"] for fact in verified] == ["output.failures"]
+ assert unverified == [{"output_path": "output.sessions_started", "reason": "superseded-by-value-witness"}]
+ assert len(probes) == 1
+
+
+async def test_capture_after_a_failed_navigation_still_asks_for_the_designated_read(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ seeded_targets: list[tuple[str, ...]] = []
+ seeded_values: list[tuple[str, ...]] = []
+
+ async def structured(ctx: object, **kwargs: object) -> tuple[dict, None]:
+ seeded_targets.append(tuple(kwargs.get("requested_targets") or ()))
+ seeded_values.append(tuple(kwargs.get("witnessed_values") or ()))
+ return _tile_packet(with_relation=True), None
+
+ async def page_info(_ctx: object, _session_id: str | None = None) -> tuple[str, str]:
+ return "https://example.com/metrics", "Fleet Metrics"
+
+ monkeypatch.setattr(tools.composition_capture, "_composition_get_structured_evidence_result", structured)
+ monkeypatch.setattr(tools.composition_capture, "_fallback_page_info", page_info)
+ admitted, _ = admitted_requested_output_reads(
+ [{"output_path": "output.sessions_started", "value_text": "Sessions Started", "label": "panel metric"}]
+ )
+
+ captured = await tools.composition_capture._composition_evidence_after_navigation_failure(
+ make_copilot_ctx(),
+ inspected_url="https://example.com/metrics",
+ navigation_error="timeout",
+ requested_reads=admitted,
+ )
+
+ assert captured is not None
+ assert seeded_targets == [("panel metric",)]
+ # A designated value is the model's own claim, so it never keys the page's value-first pass.
+ assert seeded_values == [()]
+
+
+def test_one_output_whose_names_read_different_values_witnesses_nothing() -> None:
+ summary = {
+ "requested_values": [
+ {"label": "Sessions Started", "value": "72.51k"},
+ {"label": "panel metric", "value": "0.4%"},
+ ]
+ }
+ owned = {"Sessions Started": "output.sessions_started", "panel metric": "output.sessions_started"}
+
+ witnesses, dropped = tools.composition_capture._witnesses_from_visual_summary(
+ summary, owned, ("Sessions Started", "panel metric")
+ )
+
+ assert witnesses == []
+ assert dropped == 2
diff --git a/tests/unit/test_copilot_diagnosis_repair_contract.py b/tests/unit/test_copilot_diagnosis_repair_contract.py
index 7e078fdd9..ce06f28c0 100644
--- a/tests/unit/test_copilot_diagnosis_repair_contract.py
+++ b/tests/unit/test_copilot_diagnosis_repair_contract.py
@@ -2884,7 +2884,7 @@ async def _drive_inspect_page(
capture_raises: bool = False,
) -> dict[str, object]:
async def fake_capture(
- inner_ctx: CopilotContext, *, inspected_url: str, current_url: str
+ inner_ctx: CopilotContext, *, inspected_url: str, current_url: str, **_kwargs: object
) -> tuple[dict[str, object] | None, None]:
if capture_clears_session:
inner_ctx.browser_session_id = None
diff --git a/tests/unit/test_copilot_discovery.py b/tests/unit/test_copilot_discovery.py
index 0b50b12d5..639a75140 100644
--- a/tests/unit/test_copilot_discovery.py
+++ b/tests/unit/test_copilot_discovery.py
@@ -807,6 +807,7 @@ async def test_target_url_inspection_uses_visual_summary_for_generic_obstruction
*,
evidence: dict[str, Any],
screenshot_b64: str,
+ requested_targets: tuple[str, ...] = (),
) -> tuple[dict[str, Any], None]:
assert screenshot_b64 == _VALID_PNG_B64
assert evidence["visual_obstruction_candidates"][0]["coverage"] == "viewport"
@@ -878,6 +879,7 @@ async def test_post_run_visual_fallback_binds_the_observed_run_session(
*,
evidence: dict[str, Any],
screenshot_b64: str,
+ requested_targets: tuple[str, ...] = (),
) -> tuple[dict[str, Any], None]:
assert screenshot_b64 == _VALID_PNG_B64
return {
diff --git a/tests/unit/test_copilot_evaluate_page_evidence.py b/tests/unit/test_copilot_evaluate_page_evidence.py
index a65f9f173..69a55869e 100644
--- a/tests/unit/test_copilot_evaluate_page_evidence.py
+++ b/tests/unit/test_copilot_evaluate_page_evidence.py
@@ -342,6 +342,7 @@ async def test_current_page_inspection_finalizes_runtime_repair_context_for_next
*,
inspected_url: str,
current_url: str,
+ **_kwargs: object,
) -> tuple[dict[str, object], None]:
return (
{
@@ -757,6 +758,7 @@ async def test_inspecting_a_login_page_binds_the_credential_that_page_vouches_fo
*,
inspected_url: str,
current_url: str,
+ **_kwargs: object,
) -> tuple[dict[str, object], None]:
return (
{
diff --git a/tests/unit/test_workflow_block_engine.py b/tests/unit/test_workflow_block_engine.py
index aadd97c6e..0f9ae28ec 100644
--- a/tests/unit/test_workflow_block_engine.py
+++ b/tests/unit/test_workflow_block_engine.py
@@ -7,6 +7,7 @@ from __future__ import annotations
from collections.abc import Callable, Iterator
from datetime import UTC, datetime
+from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
@@ -50,6 +51,7 @@ from skyvern.forge.sdk.workflow.models.block import (
from skyvern.forge.sdk.workflow.service import WorkflowService
from skyvern.schemas.run_enums import RunEngine
from skyvern.schemas.workflows import BlockResult, BlockType
+from skyvern.services import script_service
from tests.unit.helpers import make_organization
from tests.unit.test_agent_task_v3 import _make_block, _make_output_parameter, _run_execute_step_gate
from tests.unit.test_block_description_caching import _block_result, _setup_mocks
@@ -735,3 +737,60 @@ async def test_branch_eval_synthetic_block_defaults_to_v1_without_override(scope
)
assert captured_engines == [RunEngine.skyvern_v1]
+
+
+async def test_script_create_site_stamps_the_script_run_marker(scoped_context: SkyvernContext) -> None:
+ """A cached-script block never resolves an engine, so `engine IS NULL` alone cannot separate
+ a script-executed block from an agent-executed one whose engine was never written. The script
+ create-site stamps `script_run` at creation, making (engine NULL, script_run NULL) a genuine
+ anomaly instead of an ordinary script run.
+ """
+ scoped_context.workflow_run_id = "wr_script_marker"
+ scoped_context.organization_id = "o_test"
+
+ with patch("skyvern.services.script_service.app") as mock_app:
+ mock_app.DATABASE.observer.create_workflow_run_block = AsyncMock(
+ return_value=SimpleNamespace(workflow_run_block_id="wrb_script_marker")
+ )
+ mock_app.DATABASE.observer.update_workflow_run_block = AsyncMock()
+ mock_app.DATABASE.tasks.create_task = AsyncMock(
+ return_value=SimpleNamespace(task_id="tsk_script_marker", workflow_run_id="wr_script_marker")
+ )
+ mock_app.DATABASE.tasks.create_step = AsyncMock(return_value=SimpleNamespace(step_id="stp_script_marker"))
+ mock_app.BROWSER_MANAGER.get_for_workflow_run.return_value = None
+
+ block_id, task_id, step_id = await script_service._create_workflow_block_run_and_task(
+ block_type=BlockType.NAVIGATION,
+ label="nav",
+ )
+
+ # Everything after the create call is wrapped in a try/except that collapses to
+ # (None, None, None); asserting the ids proves the whole path ran rather than bailing early.
+ assert (block_id, task_id, step_id) == ("wrb_script_marker", "tsk_script_marker", "stp_script_marker")
+ create_kwargs = mock_app.DATABASE.observer.create_workflow_run_block.await_args.kwargs
+ assert create_kwargs["ai_fallback_triggered"] is False
+ assert create_kwargs.get("engine") is None
+
+
+async def test_agent_create_site_leaves_the_script_run_marker_unset(scoped_context: SkyvernContext) -> None:
+ """The other half of the discriminator: an agent-executed block must NOT carry the marker,
+ or `script_run IS NOT NULL` stops meaning "script-executed". A forward guard on the agent
+ create-site, which this change deliberately leaves alone -- it passes with or without it."""
+ scoped_context.workflow_block_engine_resolved_run_id = "wr_agent_marker"
+ scoped_context.workflow_block_engine_override = RunEngine.skyvern_v3
+ block = _make_block(TaskBlock, label="agent_marker_block")
+
+ with (
+ patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app,
+ patch.object(BaseTaskBlock, "execute", new_callable=AsyncMock, return_value=_block_result()),
+ patch.object(Block, "_generate_workflow_run_block_description", new_callable=AsyncMock),
+ ):
+ _setup_mocks(mock_app)
+
+ await block.execute_safe(workflow_run_id="wr_agent_marker")
+
+ create_kwargs = mock_app.DATABASE.observer.create_workflow_run_block.await_args.kwargs
+ assert create_kwargs["engine"] == RunEngine.skyvern_v3
+ assert create_kwargs.get("ai_fallback_triggered") is None