Skip to content

Automate browser based workflows with AI

Add a web search helper for code blocks and the Copilot so lead-discovery workflows stop scraping Google and Bing (SKY-15737) (#8464)

Andrew Neilson35cb497c99dc
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index a474bf829..1e7168000 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -70,6 +70,7 @@ from skyvern.forge.sdk.services import (
from skyvern.forge.sdk.services.credentials import AuthenticatorTotpParseResult
from skyvern.forge.sdk.trace import traced
from skyvern.forge.sdk.workflow.models.block import BaseTaskBlock, BlockTypeVar
+from skyvern.forge.sdk.workflow.web_search import WebSearchProvider
from skyvern.schemas.run_enums import RunEngine, RunType
from skyvern.schemas.workflows import BlockResult, FileStorageType, FileUploadDestination
from skyvern.services.otp_email import EmailOTPSearchError, EmailOTPVerificationContext, build_email_otp_sources
@@ -1157,6 +1158,11 @@ class AgentFunction:
def page_operation_contracts(self) -> PageOperationContracts | None:
return None
+ def web_search_provider(self) -> WebSearchProvider | None:
+ """No search engine is configured in OSS; reading a provider's result markup is
+ deployment configuration. Cloud overrides this with its configured provider."""
+ return None
+
def redact_codeblock_parameter_values(self, value: Any, parameters: dict[str, Any]) -> Any:
"""Cloud overrides this with the runner's canonical parameter scrubber."""
return value
diff --git a/skyvern/forge/sdk/copilot/blocker_signal.py b/skyvern/forge/sdk/copilot/blocker_signal.py
index 074cb83c0..5168f68f4 100644
--- a/skyvern/forge/sdk/copilot/blocker_signal.py
+++ b/skyvern/forge/sdk/copilot/blocker_signal.py
@@ -80,6 +80,7 @@ _INTERNAL_TOOL_NAME_TOKENS: tuple[str, ...] = (
"get_run_results",
"inspect_page_for_composition",
"discover_workflow_entrypoint",
+ "search_web",
"get_browser_screenshot",
"list_credentials",
"list_integrations",
diff --git a/skyvern/forge/sdk/copilot/code_block_synthesis.py b/skyvern/forge/sdk/copilot/code_block_synthesis.py
index b5550510c..065fffd82 100644
--- a/skyvern/forge/sdk/copilot/code_block_synthesis.py
+++ b/skyvern/forge/sdk/copilot/code_block_synthesis.py
@@ -332,6 +332,7 @@ _RESERVED_PARAM_NAMES = frozenset(
"totp_identifier",
"otp",
"solve_captcha",
+ "search_web",
DOWNLOAD_CLAIM_HELPER_NAME,
"print",
"len",
diff --git a/skyvern/forge/sdk/copilot/narration.py b/skyvern/forge/sdk/copilot/narration.py
index 4fd9f3702..12969403d 100644
--- a/skyvern/forge/sdk/copilot/narration.py
+++ b/skyvern/forge/sdk/copilot/narration.py
@@ -106,6 +106,7 @@ _TOOL_ACTIVITY_DISPLAY_LABELS = {
"list_integrations": "Checking connected integrations",
"inspect_current_workflow": "Inspecting workflow",
"discover_workflow_entrypoint": "Finding the entry page",
+ "search_web": "Searching the web",
"inspect_page_for_composition": "Inspecting the page",
"inspect_locator_matches": "Comparing locator candidates",
"list_credentials": "Checking saved credentials",
diff --git a/skyvern/forge/sdk/copilot/tools/__init__.py b/skyvern/forge/sdk/copilot/tools/__init__.py
index 3e6d3df63..dcba8db57 100644
--- a/skyvern/forge/sdk/copilot/tools/__init__.py
+++ b/skyvern/forge/sdk/copilot/tools/__init__.py
@@ -232,6 +232,7 @@ from .scouting import _record_scouted_interaction as _record_scouted_interaction
from .scouting import _register_scout_interaction_observation as _register_scout_interaction_observation
from .scouting import _resolve_scout_role_name as _resolve_scout_role_name
from .scouting import _role_name_from_selector as _role_name_from_selector
+from .web_search import _search_web_impl as _search_web_impl
from .workflow_update import BlockObservationRef as BlockObservationRef
from .workflow_update import CodeArtifactMetadata as CodeArtifactMetadata
from .workflow_update import _code_artifact_metadata_as_tool_argument as _code_artifact_metadata_as_tool_argument
@@ -1322,6 +1323,37 @@ async def discover_workflow_entrypoint_tool(
return json.dumps(scrub_secrets_from_structure(ctx.context, result))
+@function_tool(name_override="search_web", strict_mode=False)
+async def search_web_tool(ctx: RunContextWrapper, query: str, max_results: int = 10) -> str:
+ """Search the web for pages matching a query, when you need candidate sites rather than one known page.
+
+ Use this while scouting -- to find companies, suppliers, listings, or
+ documentation pages the user described but did not name. ``results`` holds
+ up to ``max_results`` entries with ``title``, ``url`` and ``snippet``, each
+ ``url`` a direct absolute link to the result site.
+
+ The rest of the reply is what the search actually did, so you can tell the
+ cases apart yourself: ``extracted_count`` is how many results the page
+ carried, ``withheld_count`` how many of those were withheld because their
+ destination is not allowed, ``http_status`` how the page was served (null
+ here, since this tab does not report one), ``error_kind`` the failure if the
+ fetch itself failed, and ``page_title`` the title served. An empty
+ ``results`` with a non-zero ``withheld_count`` is a filtered page; with
+ ``extracted_count`` zero it is a page carrying no results, which is a
+ refusal page as often as a genuine miss -- ``page_title`` usually says
+ which. Do not report a failed fetch as "no matches".
+
+ This navigates the scouting tab away from whatever page it was on. The
+ same search is available inside a code block as
+ ``await search_web(query, max_results=10)``, returning the same shape.
+ """
+ authority_error = _authority_tool_error(ctx.context, "search_web")
+ if authority_error:
+ return _diagnosis_repair_tool_error(ctx.context, "search_web", authority_error)
+ result = await _search_web_impl(ctx.context, query, max_results)
+ return json.dumps(scrub_secrets_from_structure(ctx.context, result))
+
+
@function_tool(name_override="inspect_page_for_composition", strict_mode=False)
async def inspect_page_for_composition_tool(
ctx: RunContextWrapper,
@@ -1564,6 +1596,7 @@ NATIVE_TOOLS = [
get_run_results_tool,
update_and_run_blocks_tool,
discover_workflow_entrypoint_tool,
+ search_web_tool,
inspect_page_for_composition_tool,
inspect_locator_matches_tool,
fill_credential_field_tool,
diff --git a/skyvern/forge/sdk/copilot/tools/guardrails.py b/skyvern/forge/sdk/copilot/tools/guardrails.py
index 1c51c5f21..f7de50618 100644
--- a/skyvern/forge/sdk/copilot/tools/guardrails.py
+++ b/skyvern/forge/sdk/copilot/tools/guardrails.py
@@ -169,6 +169,7 @@ def _authority_tool_error(
"run_blocks_and_collect_debug",
"edit_block_and_run",
"discover_workflow_entrypoint",
+ "search_web",
}
and isinstance(policy, RequestPolicy)
and policy.raw_secret_detected
diff --git a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
index dcca9876f..fa983d816 100644
--- a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
+++ b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
@@ -65,6 +65,7 @@ from skyvern.forge.sdk.copilot.secret_scrub import (
scrub_secrets_from_structure,
)
from skyvern.forge.sdk.schemas.credentials import Credential
+from skyvern.forge.sdk.workflow.web_search import WEB_SEARCH_HELPER_CONTRACT
from skyvern.schemas.workflows import TaskBlockYAML
from ._shared import (
@@ -490,6 +491,7 @@ async def _get_block_schema_post_hook(
data["code_only_note"] = _code_only_browser_unavailable_summary()
data["code_only_guidance"] = _code_only_browser_schema_guidance()
data["download_claim_helper_contract"] = download_claim_helper_contract()
+ data["web_search_helper_contract"] = WEB_SEARCH_HELPER_CONTRACT
page_operation_contracts = app.AGENT_FUNCTION.page_operation_contracts()
if page_operation_contracts is not None:
data["page_operation_contracts"] = page_operation_contracts
diff --git a/skyvern/forge/sdk/copilot/tools/web_search.py b/skyvern/forge/sdk/copilot/tools/web_search.py
new file mode 100644
index 000000000..e972cf145
--- /dev/null
+++ b/skyvern/forge/sdk/copilot/tools/web_search.py
@@ -0,0 +1,43 @@
+from __future__ import annotations
+
+from typing import Any
+
+from skyvern.forge import app
+from skyvern.forge.sdk.copilot.context import CopilotContext
+from skyvern.forge.sdk.workflow.web_search import FetchedPage, WebSearchObservation, search_web
+
+from ._shared import _composition_get_html, _discovery_navigate
+
+
+class ScoutingTabTransport:
+ """Fetches on the copilot's scouting tab. It reports no HTTP status, so the observation
+ carries `http_status: None` rather than an invented one."""
+
+ def __init__(self, copilot_ctx: CopilotContext) -> None:
+ self._ctx = copilot_ctx
+
+ async def fetch(self, url: str) -> FetchedPage:
+ navigation = await _discovery_navigate(self._ctx, url)
+ if not navigation.get("ok"):
+ # The reason only: a navigation error embeds the URL, which carries the query.
+ return FetchedPage(url=url, title="", html="", error_kind="navigation_failed")
+ data = navigation.get("data")
+ title = str(data.get("title") or "") if isinstance(data, dict) else ""
+ html, read_error, truncated, _used_stripped = await _composition_get_html(self._ctx)
+ if read_error:
+ return FetchedPage(url=url, title=title, html="", error_kind="page_read_failed")
+ return FetchedPage(url=url, title=title, html=html, truncated=truncated)
+
+
+async def _search_web_impl(copilot_ctx: CopilotContext, query: str, max_results: int = 10) -> dict[str, Any]:
+ observation: WebSearchObservation = await search_web(
+ app.AGENT_FUNCTION.web_search_provider(),
+ ScoutingTabTransport(copilot_ctx),
+ query,
+ max_results,
+ )
+ if observation["error_kind"] == "not_configured":
+ # A capability this deployment does not have, not a search that returned nothing. The
+ # sibling discovery helpers report an unavailable capability the same way.
+ return {"ok": False, "data": None, "error": "no web search provider is configured"}
+ return {"ok": True, "data": observation, "error": None}
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 15d6f0100..5e39fce4d 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -160,6 +160,7 @@ from skyvern.forge.sdk.settings_manager import SettingsManager
from skyvern.forge.sdk.trace import traced
from skyvern.forge.sdk.utils.pdf_parser import extract_pdf_file, render_pdf_pages_as_images, validate_pdf_file
from skyvern.forge.sdk.utils.sanitization import sanitize_postgres_text
+from skyvern.forge.sdk.workflow import web_search
from skyvern.forge.sdk.workflow.code_block_safety import BLOCKED_ATTRS as CODE_BLOCK_BLOCKED_ATTRS
from skyvern.forge.sdk.workflow.code_block_safety import is_safe_code as _shared_is_safe_code
from skyvern.forge.sdk.workflow.constants import OUTPUT_PARAMETER_MAX_VALUE_BYTES
@@ -5076,6 +5077,25 @@ def _bind_code_block_download_claim(
return click_and_claim_download
+def _bind_code_block_search_web(
+ page: Page | RecordingPage | None,
+) -> Callable[[str, int], Awaitable[web_search.WebSearchObservation]]:
+ """Closure rather than a `partial`: a keyword default on a `partial` would let block code
+ override the page whose browser context the search is fetched through."""
+
+ async def search_web(query: str, max_results: int = 10) -> web_search.WebSearchObservation:
+ if page is None:
+ raise RuntimeError("search_web is only supported while the run browser is open.")
+ return await web_search.search_web(
+ app.AGENT_FUNCTION.web_search_provider(),
+ web_search.RunBrowserTransport(page.context),
+ query,
+ max_results,
+ )
+
+ return search_web
+
+
class CodeBlock(Block):
# There is a mypy bug with Literal. Without the type: ignore, mypy will raise an error:
# Parameter 1 of Literal[...] cannot be of type "Any"
@@ -5194,6 +5214,7 @@ class CodeBlock(Block):
"click_and_claim_download": _bind_code_block_download_claim(
organization_id=None, workflow_run_id=None, download_binding=None
),
+ "search_web": _bind_code_block_search_web(None),
}
def generate_async_user_function(
@@ -5253,6 +5274,7 @@ class CodeBlock(Block):
download_binding=download_binding,
download_evidence=download_evidence,
)
+ safe_vars["search_web"] = _bind_code_block_search_web(page)
parameter_defaults: dict[str, Any] = {}
if parameters:
for key, value in parameters.items():
diff --git a/skyvern/forge/sdk/workflow/web_search.py b/skyvern/forge/sdk/workflow/web_search.py
new file mode 100644
index 000000000..e0e19c087
--- /dev/null
+++ b/skyvern/forge/sdk/workflow/web_search.py
@@ -0,0 +1,236 @@
+from __future__ import annotations
+
+import asyncio
+from dataclasses import dataclass
+from typing import Any, Protocol, TypedDict
+
+import structlog
+
+from skyvern.forge.sdk.browser_egress_policy import DestinationBlockedError, classify_url_async
+from skyvern.utils.contained_effects import contained_effect
+
+LOG = structlog.get_logger()
+
+
+class SearchResult(TypedDict):
+ title: str
+ url: str
+ snippet: str
+
+
+class WebSearchObservation(TypedDict):
+ """What the search actually produced. Deliberately not a verdict: the caller reads the
+ facts and decides. A refused page, an error page and a page with no matches are different
+ observations, and no wording heuristic has to tell them apart."""
+
+ provider: str
+ http_status: int | None
+ error_kind: str | None
+ page_title: str
+ results: list[SearchResult]
+ extracted_count: int
+ withheld_count: int
+ capture_truncated: bool
+
+
+WEB_SEARCH_HELPER_CONTRACT: dict[str, Any] = {
+ "call": "await search_web(query, max_results=10)",
+ "parameters": {
+ "query": {"accepted_type": "str"},
+ "max_results": {"accepted_type": "int", "minimum": 1},
+ },
+ "returns": {
+ "results": ["title", "url", "snippet"],
+ "http_status": "status the search page was served with; null when the transport does not report one",
+ "error_kind": "exception class when the fetch itself failed, else null",
+ "page_title": "title of the page that was served",
+ "extracted_count": "results found on the page before any were withheld",
+ "withheld_count": "results withheld because their destination is not allowed",
+ "capture_truncated": "true when the page was too large to read in full",
+ },
+ "reading_the_result": (
+ "results is what you can use. extracted_count == 0 with a 2xx http_status means the page "
+ "carried no results, which is a refusal page as often as it is a genuine miss -- read "
+ "page_title. A non-2xx http_status or a non-null error_kind means the fetch failed and "
+ "says nothing about whether matches exist. withheld_count > 0 with an empty results list "
+ "means the page had results and they were filtered, not that the query found nothing."
+ ),
+}
+
+
+@dataclass(frozen=True)
+class FetchedPage:
+ """One page as a transport actually saw it."""
+
+ url: str
+ title: str
+ html: str
+ http_status: int | None = None
+ truncated: bool = False
+ error_kind: str | None = None
+
+
+class SearchTransport(Protocol):
+ """Fetches a URL on whichever browser the caller already owns."""
+
+ async def fetch(self, url: str) -> FetchedPage: ...
+
+
+class WebSearchProvider(Protocol):
+ """A search engine: how to ask it, and how to read its answer. Provider-specific parsing
+ lives with the provider so the generic path never guesses at result shape from anchors."""
+
+ name: str
+
+ def result_page_url(self, query: str) -> str: ...
+
+ def extract_results(self, html: str) -> list[SearchResult]: ...
+
+
+async def destination_allowed(url: str) -> bool:
+ """One result may not veto its siblings: a hostname the resolver cannot even encode is
+ dropped rather than raised, so a single malformed result does not discard the whole page."""
+ try:
+ return await classify_url_async(url) is None
+ except (DestinationBlockedError, UnicodeError, ValueError):
+ return False
+
+
+async def admit_results(results: list[SearchResult]) -> list[SearchResult]:
+ """Classify every result URL. Grouping by hostname would key the admitted set on a
+ different parse than the one that produced the verdict."""
+ verdicts = await asyncio.gather(*(destination_allowed(result["url"]) for result in results))
+ return [result for result, allowed in zip(results, verdicts) if allowed]
+
+
+def _validated_max_results(value: object) -> int | None:
+ """None means "every admitted result": the secure runner cannot carry the caller's limit
+ across the operation boundary, so it takes them all and the sandbox applies the limit --
+ after admission on both paths, so a withheld result never costs the caller a slot."""
+ if value is None:
+ return None
+ if isinstance(value, bool) or not isinstance(value, int) or value < 1:
+ raise ValueError("max_results must be a positive integer")
+ return value
+
+
+def _validated_query(value: object) -> str:
+ if not isinstance(value, str) or not value.strip():
+ raise ValueError("query must be a non-empty string")
+ return value
+
+
+async def search_web(
+ provider: WebSearchProvider | None,
+ transport: SearchTransport,
+ query: str,
+ max_results: int | None = 10,
+) -> WebSearchObservation:
+ """Fetch a search page and report what came back. Extraction runs only on a page that was
+ actually served, admission runs on every extracted result, and the caller's limit is applied
+ last so a withheld result is replaced by the next allowed one rather than lost."""
+ query = _validated_query(query)
+ max_results = _validated_max_results(max_results)
+ if provider is None:
+ return WebSearchObservation(
+ provider="",
+ http_status=None,
+ error_kind="not_configured",
+ page_title="",
+ results=[],
+ extracted_count=0,
+ withheld_count=0,
+ capture_truncated=False,
+ )
+ result_page_url = provider.result_page_url(query)
+ if not await destination_allowed(result_page_url):
+ return WebSearchObservation(
+ provider=provider.name,
+ http_status=None,
+ error_kind="endpoint_blocked",
+ page_title="",
+ results=[],
+ extracted_count=0,
+ withheld_count=0,
+ capture_truncated=False,
+ )
+ page = await transport.fetch(result_page_url)
+ served = page.error_kind is None and (page.http_status is None or 200 <= page.http_status < 300)
+ extracted = provider.extract_results(page.html) if served else []
+ admitted = await admit_results(extracted)
+ observation = WebSearchObservation(
+ provider=provider.name,
+ http_status=page.http_status,
+ error_kind=page.error_kind,
+ page_title=page.title,
+ results=admitted if max_results is None else admitted[:max_results],
+ extracted_count=len(extracted),
+ withheld_count=len(extracted) - len(admitted),
+ capture_truncated=page.truncated,
+ )
+ LOG.info(
+ "web_search.observed",
+ provider=observation["provider"],
+ http_status=observation["http_status"],
+ error_kind=observation["error_kind"],
+ extracted_count=observation["extracted_count"],
+ withheld_count=observation["withheld_count"],
+ returned_count=len(observation["results"]),
+ capture_truncated=observation["capture_truncated"],
+ query_len=len(query),
+ )
+ return observation
+
+
+_NAVIGATION_TIMEOUT_MS = 20_000
+
+
+class ResponseLike(Protocol):
+ @property
+ def status(self) -> int: ...
+
+
+class PageLike(Protocol):
+ async def goto(self, url: str, timeout: float) -> ResponseLike | None: ...
+
+ async def title(self) -> str: ...
+
+ async def content(self) -> str: ...
+
+ async def close(self) -> None: ...
+
+
+class BrowserContextLike(Protocol):
+ async def new_page(self) -> PageLike: ...
+
+
+class RunBrowserTransport:
+ """Fetches on the run's own browser context rather than opening a separate network path, so
+ the fetch inherits whatever that context is configured with. It is not itself a guard: the
+ endpoint and every returned result are screened by the egress policy in `search_web`."""
+
+ def __init__(self, context: BrowserContextLike) -> None:
+ self._context = context
+
+ async def fetch(self, url: str) -> FetchedPage:
+ page = None
+ try:
+ page = await self._context.new_page()
+ response = await page.goto(url, timeout=_NAVIGATION_TIMEOUT_MS)
+ return FetchedPage(
+ url=url,
+ title=await page.title(),
+ html=await page.content(),
+ http_status=response.status if response is not None else None,
+ )
+ except Exception as exc:
+ # The class name, never the message: a navigation error embeds the target URL,
+ # which carries the query, and this is persisted as ordinary block output.
+ return FetchedPage(url=url, title="", html="", error_kind=type(exc).__name__)
+ finally:
+ if page is not None:
+ try:
+ await page.close()
+ except Exception:
+ with contained_effect("search_web page close failure"):
+ LOG.warning("web_search temporary page close failed")
diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py
index 67910552e..2016723b5 100644
--- a/tests/unit/conftest.py
+++ b/tests/unit/conftest.py
@@ -497,3 +497,44 @@ def fake_api_request_context() -> Callable[[], object]:
return _FakeAPIRequestContext()
return _build
+
+
+class FakeSearchPage:
+ """Temporary tab a `search_web` call opens on the run's browser context."""
+
+ def __init__(self, html: str, page_title: str, goto_error: Exception | None, http_status: int = 200) -> None:
+ self._html = html
+ self._page_title = page_title
+ self._goto_error = goto_error
+ self.http_status = http_status
+ self.closed = False
+ self.requested_url: str | None = None
+
+ async def goto(self, url: str, timeout: float | None = None) -> SimpleNamespace:
+ self.requested_url = url
+ if self._goto_error is not None:
+ raise self._goto_error
+ return SimpleNamespace(status=self.http_status)
+
+ async def title(self) -> str:
+ return self._page_title
+
+ async def content(self) -> str:
+ return self._html
+
+ async def close(self) -> None:
+ self.closed = True
+
+
+class FakeSearchBrowserContext:
+ def __init__(
+ self, html: str = "", page_title: str = "", goto_error: Exception | None = None, http_status: int = 200
+ ) -> None:
+ self.page = FakeSearchPage(html, page_title, goto_error, http_status)
+
+ async def new_page(self) -> FakeSearchPage:
+ return self.page
+
+
+def read_unit_data_fixture(name: str) -> str:
+ return (Path(__file__).parent / "data" / name).read_text()
diff --git a/tests/unit/test_code_block_sandbox.py b/tests/unit/test_code_block_sandbox.py
index 7bf375121..d0e75d393 100644
--- a/tests/unit/test_code_block_sandbox.py
+++ b/tests/unit/test_code_block_sandbox.py
@@ -33,6 +33,7 @@ from skyvern.forge.sdk.workflow.models.parameter import (
)
from skyvern.schemas.workflows import BlockStatus
from skyvern.webeye.browser_artifacts import BrowserArtifacts
+from tests.unit.conftest import FakeSearchBrowserContext
from tests.unit.fake_workflow_run_context import FakeWorkflowRunContext
# ---------------------------------------------------------------------------
@@ -2594,3 +2595,48 @@ class TestFailedReadinessWaitPropagates:
assert result.status == BlockStatus.failed
assert "24 results found" not in json.dumps(persisted)
assert all(value in (None, {}) for value in persisted)
+
+
+class TestSearchWebHelperBinding:
+ @staticmethod
+ def _block() -> CodeBlock:
+ now = datetime.now(timezone.utc)
+ return CodeBlock(
+ label="search_block",
+ code="",
+ output_parameter=OutputParameter(
+ parameter_type=ParameterType.OUTPUT,
+ key="search_output",
+ description="test output",
+ output_parameter_id="op_search",
+ workflow_id="w_test",
+ created_at=now,
+ modified_at=now,
+ ),
+ )
+
+ def test_search_web_is_reserved_in_safe_vars(self) -> None:
+ assert "search_web" in CodeBlock.build_safe_vars()
+
+ @pytest.mark.asyncio
+ async def test_authored_code_reaches_the_search_helper_through_the_run_browser_context(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """OSS configures no search provider, so the observation says exactly that rather than
+ reporting a search that found nothing."""
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.block.app.AGENT_FUNCTION.web_search_provider",
+ lambda: None,
+ )
+ context = FakeSearchBrowserContext(html="<html>page</html>", page_title="Search results")
+ page = SimpleNamespace(context=context)
+ block = self._block()
+
+ user_function = block.generate_async_user_function(
+ 'found = await search_web("construction company", max_results=2)\nreturn found\n',
+ page, # type: ignore[arg-type]
+ )
+ result = await user_function()
+
+ assert result["error_kind"] == "not_configured"
+ assert result["results"] == []
diff --git a/tests/unit/test_copilot_raw_secret_safety.py b/tests/unit/test_copilot_raw_secret_safety.py
index 886cdf835..05e0febf3 100644
--- a/tests/unit/test_copilot_raw_secret_safety.py
+++ b/tests/unit/test_copilot_raw_secret_safety.py
@@ -755,7 +755,7 @@ async def _uncited_redaction_ctx(message: str = _RAW_SECRET_MESSAGE):
@pytest.mark.asyncio
@pytest.mark.parametrize(
"tool_name",
- ["run_blocks_and_collect_debug", "discover_workflow_entrypoint", "inspect_page_for_composition"],
+ ["run_blocks_and_collect_debug", "discover_workflow_entrypoint", "inspect_page_for_composition", "search_web"],
)
async def test_uncited_deterministic_redaction_does_not_block_browser_tools(tool_name: str) -> None:
ctx, policy = await _uncited_redaction_ctx()
@@ -779,7 +779,7 @@ async def test_uncited_deterministic_redaction_preserves_run_authority() -> None
@pytest.mark.asyncio
[email protected]("tool_name", ["run_blocks_and_collect_debug", "discover_workflow_entrypoint"])
[email protected]("tool_name", ["run_blocks_and_collect_debug", "discover_workflow_entrypoint", "search_web"])
async def test_verified_cited_raw_secret_blocks_browser_acting_tools(tool_name: str) -> None:
literal = "Hunter2Portal!"
policy, _ = await _build(
diff --git a/tests/unit/workflow/test_web_search.py b/tests/unit/workflow/test_web_search.py
new file mode 100644
index 000000000..75e82fc40
--- /dev/null
+++ b/tests/unit/workflow/test_web_search.py
@@ -0,0 +1,272 @@
+import pytest
+
+from skyvern.forge.sdk.browser_egress_policy import DestinationBlockedError
+from skyvern.forge.sdk.workflow import web_search
+from skyvern.forge.sdk.workflow.web_search import (
+ FetchedPage,
+ RunBrowserTransport,
+ SearchResult,
+ search_web,
+)
+from tests.unit.conftest import FakeSearchBrowserContext
+
+ENDPOINT = "https://search.example.test/html/"
+RESULTS = [
+ SearchResult(title="First", url="https://first.example/about", snippet="first snippet"),
+ SearchResult(title="Second", url="https://second.example/", snippet="second snippet"),
+ SearchResult(title="Third", url="https://third.example/team", snippet="third snippet"),
+]
+
+
+class StubProvider:
+ """Stands in for a deployment's configured engine. Extraction is the provider's job, so the
+ orchestration is tested against a fixed result set rather than any engine's markup."""
+
+ name = "stub"
+
+ def __init__(self, results: list[SearchResult] | None = None) -> None:
+ self._results = RESULTS if results is None else results
+
+ def result_page_url(self, query: str) -> str:
+ return f"{ENDPOINT}?q={query}"
+
+ def extract_results(self, html: str) -> list[SearchResult]:
+ return list(self._results) if html else []
+
+
+class StubTransport:
+ def __init__(self, page: FetchedPage) -> None:
+ self._page = page
+ self.requested_url: str | None = None
+
+ async def fetch(self, url: str) -> FetchedPage:
+ self.requested_url = url
+ return self._page
+
+
+def served(*, status: int | None = 200, truncated: bool = False, title: str = "results") -> StubTransport:
+ return StubTransport(
+ FetchedPage(url=ENDPOINT, title=title, html="<html>page</html>", http_status=status, truncated=truncated)
+ )
+
+
[email protected](autouse=True)
+def allow_every_destination(monkeypatch: pytest.MonkeyPatch) -> None:
+ async def allow(_url: str) -> str | None:
+ return None
+
+ monkeypatch.setattr(web_search, "classify_url_async", allow)
+
+
+async def test_a_page_that_was_not_served_extracts_nothing_and_says_why() -> None:
+ """An error page carries no results, and reporting that as "no matches" is the false
+ negative this helper exists to remove."""
+ observed = await search_web(StubProvider(), served(status=503), "anything")
+
+ assert observed["http_status"] == 503
+ assert observed["results"] == []
+ assert observed["extracted_count"] == 0
+
+
+async def test_a_transport_failure_reports_its_kind_not_an_empty_result_set() -> None:
+ transport = StubTransport(FetchedPage(url=ENDPOINT, title="", html="", error_kind="TimeoutError"))
+
+ observed = await search_web(StubProvider(), transport, "anything")
+
+ assert observed["error_kind"] == "TimeoutError"
+ assert observed["extracted_count"] == 0
+
+
+async def test_a_transport_that_reports_no_status_still_extracts() -> None:
+ observed = await search_web(StubProvider(), served(status=None), "anything")
+
+ assert observed["http_status"] is None
+ assert observed["extracted_count"] == 3
+
+
+async def test_a_page_carrying_no_results_is_reported_with_its_title_and_no_verdict() -> None:
+ observed = await search_web(StubProvider(results=[]), served(title="Just a moment..."), "anything")
+
+ assert observed["results"] == []
+ assert observed["extracted_count"] == 0
+ assert observed["withheld_count"] == 0
+ assert observed["page_title"] == "Just a moment..."
+
+
+async def test_a_truncated_capture_is_reported() -> None:
+ observed = await search_web(StubProvider(), served(truncated=True), "anything")
+
+ assert observed["capture_truncated"] is True
+
+
+async def test_withheld_results_are_counted_rather_than_read_as_an_empty_page(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def block_every_result(url: str) -> str | None:
+ return None if url.startswith(ENDPOINT) else "blocked egress to internal address"
+
+ monkeypatch.setattr(web_search, "classify_url_async", block_every_result)
+
+ observed = await search_web(StubProvider(), served(), "anything")
+
+ assert observed["results"] == []
+ assert observed["extracted_count"] == 3
+ assert observed["withheld_count"] == 3
+
+
+async def test_the_caller_limit_is_filled_from_later_results_when_an_earlier_one_is_withheld(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Admission runs before the limit, so a withheld result costs the caller nothing and both
+ execution paths return the same set for the same arguments."""
+
+ async def block_the_first(url: str) -> str | None:
+ return "blocked" if url == "https://first.example/about" else None
+
+ monkeypatch.setattr(web_search, "classify_url_async", block_the_first)
+
+ observed = await search_web(StubProvider(), served(), "anything", max_results=2)
+
+ assert [result["url"] for result in observed["results"]] == [
+ "https://second.example/",
+ "https://third.example/team",
+ ]
+ assert observed["withheld_count"] == 1
+
+
+async def test_one_unresolvable_result_does_not_discard_its_siblings(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A hostname the resolver cannot encode raises UnicodeError, which is not an OSError and
+ escapes the shared classifier. It drops that result, not the whole search."""
+
+ async def raise_for_the_first(url: str) -> str | None:
+ if url == "https://first.example/about":
+ raise UnicodeError("label too long")
+ return None
+
+ monkeypatch.setattr(web_search, "classify_url_async", raise_for_the_first)
+
+ observed = await search_web(StubProvider(), served(), "anything")
+
+ assert [result["url"] for result in observed["results"]] == [
+ "https://second.example/",
+ "https://third.example/team",
+ ]
+ assert observed["withheld_count"] == 1
+
+
+async def test_a_result_the_classifier_rejects_outright_is_withheld_not_raised(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def reject(url: str) -> str | None:
+ if url.startswith(ENDPOINT):
+ return None
+ raise DestinationBlockedError("blocked egress: URL has no host")
+
+ monkeypatch.setattr(web_search, "classify_url_async", reject)
+
+ observed = await search_web(StubProvider(), served(), "anything")
+
+ assert observed["results"] == []
+ assert observed["withheld_count"] == 3
+
+
+async def test_no_limit_returns_every_admitted_result() -> None:
+ """The secure runner cannot carry the caller's limit across the operation boundary, so it
+ admits them all and the sandbox slices the admitted set."""
+ observed = await search_web(StubProvider(), served(), "anything", max_results=None)
+
+ assert len(observed["results"]) == 3
+
+
+async def test_an_unconfigured_deployment_says_so_rather_than_reporting_an_empty_search() -> None:
+ observed = await search_web(None, served(), "anything")
+
+ assert observed["error_kind"] == "not_configured"
+ assert observed["results"] == []
+
+
[email protected]("query", [None, 7, "", " "])
+async def test_an_unusable_query_is_rejected_before_anything_is_fetched(query: object) -> None:
+ transport = served()
+
+ with pytest.raises(ValueError):
+ await search_web(StubProvider(), transport, query) # type: ignore[arg-type]
+
+ assert transport.requested_url is None
+
+
[email protected]("max_results", [0, -1, "3", 2.0, True])
+async def test_an_unusable_result_limit_is_rejected(max_results: object) -> None:
+ with pytest.raises(ValueError):
+ await search_web(StubProvider(), served(), "anything", max_results) # type: ignore[arg-type]
+
+
+async def test_the_provider_builds_the_url_the_transport_fetches() -> None:
+ transport = served()
+
+ await search_web(StubProvider(), transport, "roofing")
+
+ assert transport.requested_url == f"{ENDPOINT}?q=roofing"
+
+
+async def test_the_run_browser_transport_reports_the_served_status_and_closes_its_tab() -> None:
+ context = FakeSearchBrowserContext(html="<html>page</html>", page_title="results", http_status=200)
+
+ page = await RunBrowserTransport(context).fetch(ENDPOINT)
+
+ assert page.http_status == 200
+ assert page.title == "results"
+ assert context.page.closed is True
+
+
+async def test_the_run_browser_transport_reports_a_navigation_failure_without_its_message() -> None:
+ context = FakeSearchBrowserContext(goto_error=TimeoutError("navigating to https://engine/?q=secret"))
+
+ page = await RunBrowserTransport(context).fetch(ENDPOINT)
+
+ assert page.error_kind == "TimeoutError"
+ assert "secret" not in repr(page)
+ assert context.page.closed is True
+
+
+async def test_a_blocked_endpoint_is_reported_and_never_fetched(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The endpoint is screened by the same policy as the results, before any navigation."""
+
+ async def block_the_endpoint(url: str) -> str | None:
+ return "blocked egress to internal address" if url.startswith(ENDPOINT) else None
+
+ monkeypatch.setattr(web_search, "classify_url_async", block_the_endpoint)
+ transport = served()
+
+ observed = await search_web(StubProvider(), transport, "anything")
+
+ assert observed["error_kind"] == "endpoint_blocked"
+ assert observed["results"] == []
+ assert transport.requested_url is None
+
+
+async def test_the_caller_limit_truncates_a_longer_admitted_set() -> None:
+ """Pins the inline slice: without it the caller asking for one result gets three."""
+ observed = await search_web(StubProvider(), served(), "anything", max_results=1)
+
+ assert [result["url"] for result in observed["results"]] == ["https://first.example/about"]
+ assert observed["extracted_count"] == 3
+ assert observed["withheld_count"] == 0