Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-11286 add Copilot page API preflight diagnostics (#6763)
Andrew Neilson7b0624e6f5be
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2index b5514cee6..4d3862bac 100644--- a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2@@ -72,6 +72,7 @@ CRITICAL RULES WHEN USING DIRECT BROWSER TOOLS:- If you call navigate_browser, you MUST call at least one observation tool (evaluate, get_browser_screenshot, click, type_text, scroll, select_option, press_key, or console_messages) before responding.- NEVER answer questions about page content, link counts, link targets, or page structure from memory or training data. Use evaluate or get_browser_screenshot.- Use evaluate for reading/inspection; do NOT use evaluate to click or type. Use click and type_text for interactions.+- Direct browser `evaluate` is for scouting only. Persisted workflow `code` blocks must not use `page.evaluate`, `page.evaluate_handle`, `page.request`, or `page.context`; use `page.locator(...)`, `page.get_by_role(...)`, and locator DOM-reading methods such as `inner_text`, `text_content`, `get_attribute`, `count`, and `is_visible`.- CSS SELECTORS vs AI INTENT (cost-aware): a CSS-selector-ONLY click/type is an instant deterministic action. Passing an `intent` (alone, or alongside a selector) routes the action through a slower full-page AI scan that scrolls and screenshots the whole page to locate the element — even when the element is already on screen. So once `evaluate`/inspection evidence has identified the target, act by a CSS selector ALONE; reserve `intent` only for when you genuinely cannot derive a selector. When a shared class matches many elements (e.g. one Add-to-Cart per result row), scope the selector to the specific item (its container, a unique attribute, or `:nth-of-type`) rather than passing an `intent` to disambiguate. Do the "which element" reasoning in `evaluate` (read the DOM), not in a click `intent`. jQuery pseudo-selectors (:contains(), :eq(), :first, :visible, :has()) are NOT valid — use standard selectors like 'button.classname', 'a[href*="keyword"]', '#id', 'tr:nth-of-type(2) td a'.- SCROLL: Use scroll to reveal content below the fold. Provide direction (up/down/left/right) and optionally amount in pixels, a selector for the scrollable container, or intent to scroll a specific element into view.- SELECT_OPTION: Use select_option for <select> dropdowns. Provide the value and use selector or intent to target the element. For free-text inputs, use type_text instead.diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex 6aa72a5b1..ad6ffc760 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -179,7 +179,11 @@ def _render_code_only_browser_authoring_prompt() -> str:"interactions you scouted as deterministic Playwright. Persist that block VERBATIM\n""via update_workflow / update_and_run_blocks — do not rewrite, reorder, or\n""re-derive its locators. Only hand-author the steps it does not cover, such as the\n"- "extraction or report block that returns the structured result."+ "extraction or report block that returns the structured result. Direct browser\n"+ "evaluate is a scouting tool; persisted code blocks must not use page.evaluate,\n"+ "page.evaluate_handle, page.request, or page.context. Use locators and locator\n"+ "DOM-reading methods such as inner_text, text_content, get_attribute, count, and\n"+ "is_visible instead.")diff --git a/skyvern/forge/sdk/copilot/code_block_preflight.py b/skyvern/forge/sdk/copilot/code_block_preflight.pyindex db4f303ca..aef6e0272 100644--- a/skyvern/forge/sdk/copilot/code_block_preflight.py+++ b/skyvern/forge/sdk/copilot/code_block_preflight.py@@ -14,6 +14,7 @@ from pathlib import Pathfrom types import SimpleNamespacefrom typing import Iterable+from skyvern.forge.sdk.copilot.code_block_security import CodeBlockSecurityError, author_time_code_security_errorsfrom skyvern.forge.sdk.workflow.models.block import CodeBlock@@ -275,7 +276,7 @@ def author_time_code_block_diagnostics(code: str) -> list[CodeBlockPreflightDiagtree, _ = _parse_static_ast(code)if tree is None:return []- return _author_time_ast_diagnostics(tree)+ return [*_author_time_security_diagnostics(code), *_author_time_ast_diagnostics(tree)]def _static_ast_diagnostics(code: str) -> list[CodeBlockPreflightDiagnostic]:@@ -285,7 +286,7 @@ def _static_ast_diagnostics(code: str) -> list[CodeBlockPreflightDiagnostic]:if tree is None:return []- diagnostics = _author_time_ast_diagnostics(tree)+ diagnostics = [*_author_time_security_diagnostics(code), *_author_time_ast_diagnostics(tree)]for node in ast.walk(tree):if not isinstance(node, ast.Call):continue@@ -318,6 +319,24 @@ def _parse_static_ast(code: str) -> tuple[ast.AST | None, CodeBlockPreflightDiagreturn tree, None+def _author_time_security_diagnostics(code: str) -> list[CodeBlockPreflightDiagnostic]:+ normalized_code = textwrap.dedent(code).strip()+ return [+ _author_time_security_diagnostic(error)+ for error in author_time_code_security_errors(label="code", code=normalized_code)+ ]+++def _author_time_security_diagnostic(error: CodeBlockSecurityError) -> CodeBlockPreflightDiagnostic:+ return CodeBlockPreflightDiagnostic(+ code=error.reason_code,+ message=(+ f"{error.reason_code}: {error.surface} is not allowed in persisted workflow code blocks. "+ "Use locators and locator DOM-reading methods instead."+ ),+ )++def _author_time_ast_diagnostics(tree: ast.AST) -> list[CodeBlockPreflightDiagnostic]:diagnostics: list[CodeBlockPreflightDiagnostic] = []broad_table_scan = _broad_table_record_scan_diagnostic(tree)diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.pyindex 6b6844250..9c7bcff57 100644--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py@@ -806,6 +806,32 @@ def _code_block_safety_errors(workflow_yaml: str | None, prior_yaml: str | None)return errors+def _human_facing_code_safety_errors(errors: list[str | CodeBlockSecurityError]) -> list[str | CodeBlockSecurityError]:+ preflight_reason_codes = {+ reason_code for error in errors if (reason_code := _generated_code_preflight_reason_code(error)) is not None+ }+ if not preflight_reason_codes:+ return errors+ return [+ error+ for error in errors+ if not isinstance(error, CodeBlockSecurityError) or error.reason_code not in preflight_reason_codes+ ]+++def _generated_code_preflight_reason_code(error: str | CodeBlockSecurityError) -> str | None:+ if isinstance(error, CodeBlockSecurityError):+ return None+ marker = "failed the generated-code preflight check: "+ if marker not in error:+ return None+ detail = error.split(marker, 1)[1]+ reason_code = detail.split(":", 1)[0]+ if not reason_code.startswith("AUTHOR_PAGE_"):+ return None+ return reason_code++_CHURN_REASON_CODES = frozenset({"code_authoring_guardrail_churn", "credential_priority_authoring_churn"})@@ -3248,7 +3274,14 @@ async def _update_workflow("diagnostic_code_safety_errors": code_safety_errors,},}- seam_errors = [error for error in (code_artifact_metadata_error, *code_safety_errors) if error]+ seam_errors = [+ error+ for error in (+ code_artifact_metadata_error,+ *_human_facing_code_safety_errors(code_safety_errors),+ )+ if error+ ]if seam_errors:return {"ok": False,diff --git a/tests/unit/test_copilot_code_block_persist_seam.py b/tests/unit/test_copilot_code_block_persist_seam.pyindex fd7a7fc54..29b69540f 100644--- a/tests/unit/test_copilot_code_block_persist_seam.py+++ b/tests/unit/test_copilot_code_block_persist_seam.py@@ -493,6 +493,22 @@ class TestCodeSafetySeam:def test_safe_code_passes(self) -> None:assert _code_block_safety_errors(_SAFE_CODE_YAML, None) == []+ @pytest.mark.asyncio+ async def test_denied_page_api_attribute_is_repairable_preflight_error_without_duplicate_generic_message(+ self,+ ) -> None:+ result = await _update_workflow(+ {"workflow_yaml": _code_yaml("text = await page.evaluate('() => document.body.innerText')")},+ _standard_ctx(),+ )++ assert result["ok"] is False+ joined = result["error"]+ assert "AUTHOR_PAGE_EVALUATE" in joined+ assert "failed the generated-code preflight check" in joined+ assert joined.count("failed the sandbox safety check") == 0+ assert joined.count("page.evaluate is not allowed") == 1+def test_unresolved_sandbox_names_are_seam_errors(self) -> None:errors = _code_block_safety_errors(_code_yaml(diff --git a/tests/unit/test_copilot_code_block_synthesis.py b/tests/unit/test_copilot_code_block_synthesis.pyindex be5928601..a380fccdb 100644--- a/tests/unit/test_copilot_code_block_synthesis.py+++ b/tests/unit/test_copilot_code_block_synthesis.py@@ -9,11 +9,13 @@ import astimport jsonimport keywordimport sys+import textwrapfrom typing import Anyimport pytestfrom skyvern.forge.sdk.copilot.code_block_preflight import preflight_code_block+from skyvern.forge.sdk.copilot.code_block_security import author_time_code_security_errorsfrom skyvern.forge.sdk.copilot.code_block_synthesis import (_DOWNLOAD_VAR_BASE,_MAX_STEPS,@@ -1361,6 +1363,47 @@ class TestPreflightSurfacesSyntaxError:diagnostics = preflight_code_block('await page.goto("unterminated)\n', parameter_keys=())assert any(d.code == "SYNTAX_ERROR" for d in diagnostics)+ @pytest.mark.parametrize(+ ("code", "reason"),+ [+ ("await page.request.post('https://example.com/collect')", "AUTHOR_PAGE_REQUEST"),+ ("state = await page.context.storage_state()", "AUTHOR_PAGE_CONTEXT"),+ ("text = await page.evaluate('() => document.body.innerText')", "AUTHOR_PAGE_EVALUATE"),+ ("handle = await page.evaluate_handle('() => document.body')", "AUTHOR_PAGE_EVALUATE"),+ ],+ )+ def test_denied_page_api_attributes_surface_preflight_reason_codes(self, code: str, reason: str) -> None:+ diagnostics = preflight_code_block(code, parameter_keys=())++ assert [diagnostic.code for diagnostic in diagnostics if diagnostic.code.startswith("AUTHOR_PAGE_")] == [reason]+ assert any("not allowed in persisted workflow code blocks" in diagnostic.message for diagnostic in diagnostics)++ def test_denied_page_api_preflight_reason_codes_match_author_time_security_source(self) -> None:+ code = """+ await page.request.post("https://example.com/collect")+ state = await page.context.storage_state()+ text = await page.evaluate("() => document.body.innerText")+ handle = await page.evaluate_handle("() => document.body")+ """++ normalized_code = textwrap.dedent(code).strip()+ diagnostics = preflight_code_block(code, parameter_keys=())+ security_errors = author_time_code_security_errors(label="search_registry", code=normalized_code)++ preflight_reasons = {+ diagnostic.code for diagnostic in diagnostics if diagnostic.code.startswith("AUTHOR_PAGE_")+ }+ security_reasons = {error.reason_code for error in security_errors}+ assert (+ preflight_reasons+ == security_reasons+ == {+ "AUTHOR_PAGE_REQUEST",+ "AUTHOR_PAGE_CONTEXT",+ "AUTHOR_PAGE_EVALUATE",+ }+ )+def test_broad_body_text_wait_for_function_surfaces_selection_diagnostic(self) -> None:code = ("await page.wait_for_function("