Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(copilot): catch block YAML leaked into chat reply (SKY-9925) (#6096)
Andrew Neilson72e4b9a7ba5a
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex 9db6e5e9d..a1a592ce7 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -718,6 +718,10 @@ _INTERNAL_BLOCK_TAXONOMY_REPLY = ("Describe the page action, data to collect, sign-in step, or check you want, and I'll translate that into ""a supported workflow update.")+_BLOCK_YAML_IN_REPLY_REWRITE_NO_PROPOSAL = (+ "I drafted a change to the workflow but haven't applied it yet. Want me to update the workflow now?"+)+_BLOCK_YAML_IN_REPLY_REWRITE_WITH_PROPOSAL = "I made the change you described to the workflow."_PROPOSAL_ACCEPT_UI_ACTION_RE = re.compile(r"\b(?:accept|always\s+accept)\b", re.IGNORECASE)_PROPOSAL_REJECT_UI_ACTION_RE = re.compile(r"\b(?:reject|discard)\b", re.IGNORECASE)_UNVALIDATED_PROPOSAL_AFFORDANCE = (@@ -1038,6 +1042,14 @@ def _translate_to_agent_result(user_response = _INTERNAL_BLOCK_TAXONOMY_REPLYsoft_rewrite_reasons.append(OutputPolicyReason.INTERNAL_BLOCK_TAXONOMY_LEAK)output_policy_verdict.remove(OutputPolicyReason.INTERNAL_BLOCK_TAXONOMY_LEAK)+ if OutputPolicyReason.WORKFLOW_YAML_IN_REPLY in output_policy_verdict.reason_codes:+ user_response = (+ _BLOCK_YAML_IN_REPLY_REWRITE_WITH_PROPOSAL+ if last_workflow is not None+ else _BLOCK_YAML_IN_REPLY_REWRITE_NO_PROPOSAL+ )+ soft_rewrite_reasons.append(OutputPolicyReason.WORKFLOW_YAML_IN_REPLY)+ output_policy_verdict.remove(OutputPolicyReason.WORKFLOW_YAML_IN_REPLY)# Preserve the unbacked-proposal correction when both soft rewrites apply:# a reply must not imply a workflow exists when no proposal was produced.if OutputPolicyReason.UNBACKED_WORKFLOW_DELIVERY_CLAIM in output_policy_verdict.reason_codes:diff --git a/skyvern/forge/sdk/copilot/output_policy.py b/skyvern/forge/sdk/copilot/output_policy.pyindex 3c4ffc322..89d01671f 100644--- a/skyvern/forge/sdk/copilot/output_policy.py+++ b/skyvern/forge/sdk/copilot/output_policy.py@@ -7,7 +7,10 @@ from typing import Any, castfrom urllib.parse import urlparsefrom skyvern.forge.sdk.copilot.context import COPILOT_RESPONSE_TYPES, ResponseType-from skyvern.forge.sdk.copilot.output_utils import looks_like_workflow_delivery_claim+from skyvern.forge.sdk.copilot.output_utils import (+ looks_like_workflow_delivery_claim,+ looks_like_workflow_yaml_in_chat,+)from skyvern.forge.sdk.copilot.request_policy import RAW_SECRET_PATTERNS, RequestPolicy, contains_email_password_pairfrom skyvern.utils.yaml_loader import safe_load_no_dates@@ -102,6 +105,7 @@ class OutputPolicyReason(StrEnum):INTERNAL_TOOL_INSTRUCTION_LEAK = "internal_tool_instruction_leak"OUTPUT_POLICY_CONTEXT_MISSING = "output_policy_context_missing"INTERNAL_BLOCK_TAXONOMY_LEAK = "internal_block_taxonomy_leak"+ WORKFLOW_YAML_IN_REPLY = "workflow_yaml_in_reply"@dataclass@@ -326,6 +330,8 @@ def evaluate_output_policy(verdict.add(OutputPolicyReason.MISSING_UNVALIDATED_PROPOSAL_AFFORDANCE)if _contains_internal_block_taxonomy_leak(user_response, output_kind):verdict.add(OutputPolicyReason.INTERNAL_BLOCK_TAXONOMY_LEAK)+ if response_type in ("REPLY", "ASK_QUESTION") and looks_like_workflow_yaml_in_chat(user_response):+ verdict.add(OutputPolicyReason.WORKFLOW_YAML_IN_REPLY)if isinstance(request_policy, RequestPolicy):if request_policy.user_response_policy == "ask_clarification" and response_type != "ASK_QUESTION":diff --git a/skyvern/forge/sdk/copilot/output_utils.py b/skyvern/forge/sdk/copilot/output_utils.pyindex 0b98bd73b..69722f167 100644--- a/skyvern/forge/sdk/copilot/output_utils.py+++ b/skyvern/forge/sdk/copilot/output_utils.py@@ -12,6 +12,7 @@ from typing import TYPE_CHECKING, Anyfrom skyvern.forge.sdk.agents.context import sanitize_agent_tool_result_for_llm as sanitize_generic_tool_result_for_llmfrom skyvern.forge.sdk.copilot.context import COPILOT_RESPONSE_TYPESfrom skyvern.forge.sdk.copilot.loop_detection import LOOP_DETECTED_MARKER+from skyvern.schemas.workflows import BlockTypeif TYPE_CHECKING:from agents.result import RunResultStreaming@@ -170,6 +171,26 @@ def looks_like_workflow_delivery_claim(text: Any) -> bool:return any(pattern.search(text) for pattern in _WORKFLOW_DELIVERY_CLAIM_PATTERNS)+# A `block_type:` line whose value is a real BlockType, or a `workflow_definition:`+# line — both keyed to canonical identifiers and anchored at line start, so inline+# prose ("the block_type field") cannot trip them. The optional quote group also+# matches the JSON serialization (`"block_type": "navigation"`).+_BLOCK_TYPE_LINE_RE = re.compile(+ r'^\s*-?\s*["\']?block_type["\']?\s*:\s*["\']?(?:' + "|".join(re.escape(bt.value) for bt in BlockType) + r")\b",+ re.MULTILINE,+)+_WORKFLOW_DEFINITION_LINE_RE = re.compile(r'^\s*["\']?workflow_definition["\']?\s*:', re.MULTILINE)+++def looks_like_workflow_yaml_in_chat(text: Any) -> bool:+ """Return True when ``text`` contains serialized Skyvern workflow YAML/JSON."""+ if not isinstance(text, str):+ return False+ if "block_type" not in text and "workflow_definition" not in text:+ return False+ return bool(_WORKFLOW_DEFINITION_LINE_RE.search(text) or _BLOCK_TYPE_LINE_RE.search(text))++def extract_screenshot_b64(result: dict[str, Any]) -> str | None:"""Extract screenshot_base64 from a copilot result dict, if present."""data = result.get("data")diff --git a/tests/unit/test_copilot_output_policy.py b/tests/unit/test_copilot_output_policy.pyindex 5ad4b81b2..e02873f94 100644--- a/tests/unit/test_copilot_output_policy.py+++ b/tests/unit/test_copilot_output_policy.py@@ -288,6 +288,51 @@ def test_classifies_unbacked_workflow_delivery_claim() -> None:assert OutputPolicyReason.MISSING_PROPOSAL_STATE in verdict.reason_codes+def test_flags_block_yaml_pasted_into_user_response() -> None:+ user_response = (+ "I've now updated the workflow to also accept the form's URL as a parameter, named `form_url`. "+ "Here's how the block now looks:\n\n"+ " - label: navigate_and_fill_form\n"+ " block_type: navigation\n"+ " navigation_goal: Fill the abuse form using the supplied data.\n"+ ' url: "{{ form_url }}"\n'+ " parameter_keys:\n"+ " - name\n"+ " - email\n"+ " - form_url\n"+ )++ verdict = evaluate_output_policy(+ request_policy=_policy(),+ response_type="REPLY",+ user_response=user_response,+ has_workflow_proposal=False,+ )++ assert not verdict.allowed+ assert OutputPolicyReason.WORKFLOW_YAML_IN_REPLY in verdict.reason_codes+++def test_block_yaml_in_reply_is_not_hard_blocking() -> None:+ verdict = evaluate_output_policy(+ request_policy=_policy(),+ response_type="ASK_QUESTION",+ user_response=(+ "Here is the change I'd make:\n\n"+ "```yaml\n"+ "block_type: navigation\n"+ "navigation_goal: Submit the form.\n"+ "label: submit_form\n"+ "```\n"+ ),+ has_workflow_proposal=False,+ )++ assert OutputPolicyReason.WORKFLOW_YAML_IN_REPLY in verdict.reason_codes+ hard = hard_block_output_policy_verdict(verdict)+ assert OutputPolicyReason.WORKFLOW_YAML_IN_REPLY not in hard.reason_codes++def test_allows_workflow_delivery_language_after_failed_workflow_attempt() -> None:verdict = evaluate_output_policy(request_policy=_policy(),@@ -1077,6 +1122,75 @@ def test_translate_to_agent_result_prioritizes_unbacked_workflow_claim_over_taxoassert agent_result.updated_workflow is None+def test_translate_to_agent_result_rewrites_block_yaml_pasted_in_reply() -> None:+ leak = (+ "I've now updated the workflow to also accept the form's URL as a parameter, named `form_url`. "+ "Here's how the block now looks:\n\n"+ " - label: navigate_and_fill_form\n"+ " block_type: navigation\n"+ " navigation_goal: Fill the abuse form.\n"+ ' url: "{{ form_url }}"\n'+ " parameter_keys:\n"+ " - name\n"+ " - form_url\n"+ )+ result = _fake_run_result({"type": "REPLY", "user_response": leak})++ with patch("skyvern.forge.sdk.copilot.agent.LOG.info") as log_info:+ agent_result = agent_module._translate_to_agent_result(+ result,+ _ctx(),+ global_llm_context=None,+ chat_request=_chat_request(),+ organization_id="org-1",+ )++ assert "block_type" not in agent_result.user_response+ assert "navigation_goal" not in agent_result.user_response+ assert "parameter_keys" not in agent_result.user_response+ assert "haven't applied it yet" in agent_result.user_response+ assert agent_result.updated_workflow is None+ final_log = next(call for call in log_info.call_args_list if call.args[0] == "copilot output policy final verdict")+ assert final_log.kwargs["soft_rewrite_reason_codes"] == ["workflow_yaml_in_reply"]+ assert final_log.kwargs["contained_failure"] is True+ assert agent_result.output_policy_diagnostics["soft_rewrite_reason_codes"] == ["workflow_yaml_in_reply"]+ assert agent_result.output_policy_diagnostics["final_output_policy_allowed"] is True+++def test_translate_to_agent_result_rewrites_block_yaml_when_workflow_attached() -> None:+ leak = (+ "I've now updated the workflow to also accept the form's URL as a parameter, named `form_url`. "+ "Here's how the block now looks:\n\n"+ " - label: navigate_and_fill_form\n"+ " block_type: navigation\n"+ " navigation_goal: Fill the abuse form.\n"+ " parameter_keys:\n"+ " - form_url\n"+ )+ result = _fake_run_result({"type": "REPLY", "user_response": leak})++ workflow = SimpleNamespace(name="draft")+ ctx = _ctx()+ ctx.last_workflow = workflow+ ctx.last_workflow_yaml = _workflow_yaml()+ ctx.last_test_ok = True++ agent_result = agent_module._translate_to_agent_result(+ result,+ ctx,+ global_llm_context=None,+ chat_request=_chat_request(),+ organization_id="org-1",+ )++ assert "block_type" not in agent_result.user_response+ assert "navigation_goal" not in agent_result.user_response+ assert "parameter_keys" not in agent_result.user_response+ assert "haven't applied it yet" not in agent_result.user_response+ assert "made the change" in agent_result.user_response+ assert agent_result.updated_workflow is workflow++def test_translate_to_agent_result_adds_unvalidated_affordance() -> None:workflow = SimpleNamespace(name="draft")result = _fake_run_result({"type": "REPLY", "user_response": "I drafted the workflow."})diff --git a/tests/unit/test_copilot_output_utils.py b/tests/unit/test_copilot_output_utils.pyindex eb8db9167..a47a174ba 100644--- a/tests/unit/test_copilot_output_utils.py+++ b/tests/unit/test_copilot_output_utils.py@@ -7,6 +7,7 @@ from unittest.mock import MagicMockfrom skyvern.forge.sdk.copilot.output_utils import (_INTERNAL_RUN_CANCELLED_BY_WATCHDOG_KEY,format_tool_result_for_user,+ looks_like_workflow_yaml_in_chat,parse_final_response,sanitize_tool_result_for_llm,summarize_tool_result,@@ -778,3 +779,82 @@ class TestParseFinalResponse:text = "I'm not sure how to help with that."parsed = parse_final_response(text)assert parsed == {"type": "REPLY", "user_response": text}+++class TestLooksLikeWorkflowYamlInChat:+ def test_detects_block_yaml_with_navigation_goal(self) -> None:+ text = (+ "Here's how the block now looks:\n\n"+ " - label: fill_form\n"+ " block_type: navigation\n"+ " navigation_goal: Fill the abuse form.\n"+ " url: https://example.test/abuse\n"+ " parameter_keys:\n"+ " - name\n"+ )+ assert looks_like_workflow_yaml_in_chat(text) is True++ def test_detects_block_yaml_inside_fenced_code(self) -> None:+ text = (+ "I've drafted the change:\n\n"+ "```yaml\n"+ "block_type: extraction\n"+ "data_extraction_goal: Pull the table.\n"+ "label: extract_data\n"+ "```\n"+ )+ assert looks_like_workflow_yaml_in_chat(text) is True++ def test_detects_full_workflow_definition_paste(self) -> None:+ text = (+ "workflow_definition:\n"+ " parameters: []\n"+ " blocks:\n"+ " - block_type: validation\n"+ " complete_criterion: The page shows a thank-you message.\n"+ )+ assert looks_like_workflow_yaml_in_chat(text) is True++ def test_does_not_flag_inline_block_type_mention(self) -> None:+ text = (+ "I'll use a navigation block to fill the form. The block_type field on a "+ "navigation block accepts goals like a navigation_goal string — but the user "+ "doesn't need to see the YAML directly."+ )+ assert looks_like_workflow_yaml_in_chat(text) is False++ def test_does_not_flag_short_prose(self) -> None:+ assert looks_like_workflow_yaml_in_chat("Sure, I can do that.") is False++ def test_does_not_flag_empty_or_non_string(self) -> None:+ assert looks_like_workflow_yaml_in_chat("") is False+ assert looks_like_workflow_yaml_in_chat(None) is False+ assert looks_like_workflow_yaml_in_chat(12345) is False++ def test_detects_bare_block_type_line(self) -> None:+ text = "Here's a small snippet:\n\n - block_type: navigation\n label: open_page\n"+ assert looks_like_workflow_yaml_in_chat(text) is True++ def test_unknown_block_type_value_does_not_trip(self) -> None:+ text = "Diagnostic note:\n\n block_type: experimental_thing\n detail: not a real block\n"+ assert looks_like_workflow_yaml_in_chat(text) is False++ def test_detects_json_shape_block_paste(self) -> None:+ text = (+ "Here is the block as JSON:\n\n"+ "```json\n"+ "{\n"+ ' "block_type": "navigation",\n'+ ' "navigation_goal": "Fill the form.",\n'+ ' "parameter_keys": ["name"]\n'+ "}\n"+ "```\n"+ )+ assert looks_like_workflow_yaml_in_chat(text) is True++ def test_inline_field_mention_does_not_trip(self) -> None:+ text = (+ "When the navigation_goal field is unset and the block_type is wrong, the block "+ "will fail validation — those fields need to come from the user."+ )+ assert looks_like_workflow_yaml_in_chat(text) is False