Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-9978 Gate no-mutation TurnIntent tools (#6076)
Andrew Neilson9d7d5edec72e
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex 7484e80ce..88a552d25 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -55,7 +55,7 @@ from skyvern.forge.sdk.copilot.output_utils import (from skyvern.forge.sdk.copilot.request_policy import RequestPolicy, build_request_policy, redact_raw_secrets_for_promptfrom skyvern.forge.sdk.copilot.tracing_setup import _copilot_model_name, ensure_tracing_initialized, is_tracing_enabledfrom skyvern.forge.sdk.copilot.turn_context import TurnContextAssembler, TurnContextInputs, TurnContextPacket-from skyvern.forge.sdk.copilot.turn_intent import TurnIntent, build_turn_intent+from skyvern.forge.sdk.copilot.turn_intent import NO_MUTATION_TURN_INTENT_MODES, TurnIntent, build_turn_intentfrom skyvern.forge.sdk.schemas.persistent_browser_sessions import is_final_statusfrom skyvern.forge.sdk.schemas.workflow_copilot import (WorkflowCopilotChatHistoryMessage,@@ -493,6 +493,20 @@ def _build_tool_usage_guide(tool_names_and_descriptions: list[tuple[str, str]]))+def _turn_intent_disables_tools(turn_intent: TurnIntent | None) -> bool:+ if not isinstance(turn_intent, TurnIntent) or turn_intent.mode not in NO_MUTATION_TURN_INTENT_MODES:+ return False++ authority = turn_intent.authority+ return not authority.may_update_workflow and not authority.may_run_blocks+++def _native_tools_for_turn(native_tools: list[Any], turn_intent: TurnIntent | None) -> list[Any]:+ if _turn_intent_disables_tools(turn_intent):+ return []+ return list(native_tools)++def _is_explicit_false(value: Any) -> bool:# LLMs occasionally serialise JSON booleans as strings; coerce the common spellings.if value is False:@@ -1619,8 +1633,12 @@ async def _run_copilot_turn_impl(alias_map = get_skyvern_mcp_alias_map()overlays = _build_skyvern_mcp_overlays()+ if _turn_intent_disables_tools(ctx.turn_intent):+ alias_map = {}+ overlays = {}- tool_info: list[tuple[str, str]] = [(tool.name, tool.description or "") for tool in NATIVE_TOOLS]+ native_tools = _native_tools_for_turn(NATIVE_TOOLS, ctx.turn_intent)+ tool_info: list[tuple[str, str]] = [(tool.name, tool.description or "") for tool in native_tools]tool_info.extend((name, overlay.description or "") for name, overlay in overlays.items())tool_usage_guide = _build_tool_usage_guide(tool_info)@@ -1677,7 +1695,7 @@ async def _run_copilot_turn_impl(agent = Agent(name="workflow-copilot",instructions=system_prompt,- tools=list(NATIVE_TOOLS),+ tools=native_tools,mcp_servers=[mcp_server],model=attempt_model_name,output_guardrails=output_guardrails,diff --git a/skyvern/forge/sdk/copilot/tools.py b/skyvern/forge/sdk/copilot/tools.pyindex ee788f8b4..d8db0ac70 100644--- a/skyvern/forge/sdk/copilot/tools.py+++ b/skyvern/forge/sdk/copilot/tools.py@@ -68,6 +68,7 @@ from skyvern.forge.sdk.copilot.request_policy import RequestPolicyfrom skyvern.forge.sdk.copilot.runtime import AgentContext, ensure_browser_sessionfrom skyvern.forge.sdk.copilot.screenshot_utils import enqueue_screenshot_from_resultfrom skyvern.forge.sdk.copilot.tracing_setup import copilot_span+from skyvern.forge.sdk.copilot.turn_intent import NO_MUTATION_TURN_INTENT_MODES, TurnIntentfrom skyvern.forge.sdk.routes.workflow_copilot import _process_workflow_yamlfrom skyvern.forge.sdk.settings_manager import SettingsManagerfrom skyvern.forge.sdk.workflow.exceptions import BaseWorkflowHTTPException@@ -677,6 +678,8 @@ async def _attach_failed_block_screenshots(BLOCK_RUNNING_TOOLS = frozenset({"run_blocks_and_collect_debug", "update_and_run_blocks"})+WORKFLOW_MUTATION_TOOLS = frozenset({"update_workflow", "update_and_run_blocks"})+ANSWER_ONLY_CONTEXT_TOOLS = frozenset({"get_run_results"})def _copilot_seconds_remaining(ctx: AgentContext) -> float | None:@@ -842,6 +845,43 @@ def _request_policy_tool_error(ctx: AgentContext, tool_name: str) -> str | None:return None+def _turn_intent_tool_error(ctx: AgentContext, tool_name: str) -> str | None:+ intent = getattr(ctx, "turn_intent", None)+ if not isinstance(intent, TurnIntent) or intent.mode not in NO_MUTATION_TURN_INTENT_MODES:+ return None++ authority = intent.authority+ if authority.may_update_workflow or authority.may_run_blocks:+ return None++ blocks_update = tool_name in WORKFLOW_MUTATION_TOOLS and not authority.may_update_workflow+ blocks_run = tool_name in BLOCK_RUNNING_TOOLS and not authority.may_run_blocks+ blocks_context_read = tool_name in ANSWER_ONLY_CONTEXT_TOOLS+ if not blocks_update and not blocks_run and not blocks_context_read:+ return None++ if blocks_run:+ reason_code = "turn_intent_no_mutation_run_blocked"+ elif blocks_update:+ reason_code = "turn_intent_no_mutation_update_blocked"+ else:+ reason_code = "turn_intent_no_mutation_context_read_blocked"+ LOG.info(+ "copilot turn intent no-mutation gate blocked tool",+ turn_intent_mode=intent.mode.value,+ blocked_tool=tool_name,+ safe_reason_code=reason_code,+ )+ action = "ask the user" if authority.requires_user_input else "answer the user"+ detail = f" Ask: {intent.missing_context_question}" if intent.missing_context_question else ""+ return (+ f"TurnIntent classified this turn as `{intent.mode.value}`, so `{tool_name}` is not allowed "+ "for the latest user message. Do not update workflow YAML or run browser blocks, and do not "+ f"fetch additional run context with tools; {action} using the available context instead. "+ f"safe_reason_code={reason_code}.{detail}"+ )++_PARAMETER_TYPE_PLACEHOLDERS: dict[WorkflowParameterType, Any] = {WorkflowParameterType.STRING: "",WorkflowParameterType.INTEGER: 0,@@ -923,6 +963,10 @@ async def _update_workflow(*,allow_missing_credentials: bool | None = None,) -> dict[str, Any]:+ turn_intent_error = _turn_intent_tool_error(ctx, "update_workflow")+ if turn_intent_error is not None:+ return {"ok": False, "error": turn_intent_error}+policy_error = _request_policy_tool_error(ctx, "update_workflow")if policy_error is not None:return {"ok": False, "error": policy_error}@@ -3884,6 +3928,10 @@ async def run_blocks_tool("""copilot_ctx = ctx.contextarguments = {"block_labels": block_labels, "parameters": parameters or {}}+ turn_intent_error = _turn_intent_tool_error(copilot_ctx, "run_blocks_and_collect_debug")+ if turn_intent_error:+ return _diagnosis_repair_tool_error(copilot_ctx, "run_blocks_and_collect_debug", turn_intent_error)+policy_error = _request_policy_tool_error(copilot_ctx, "run_blocks_and_collect_debug")if policy_error:return _diagnosis_repair_tool_error(copilot_ctx, "run_blocks_and_collect_debug", policy_error)@@ -3945,6 +3993,9 @@ async def get_run_results_tool(loop_error = _tool_loop_error(copilot_ctx, "get_run_results", params)if loop_error:return json.dumps({"ok": False, "error": loop_error})+ turn_intent_error = _turn_intent_tool_error(copilot_ctx, "get_run_results")+ if turn_intent_error:+ return json.dumps({"ok": False, "error": turn_intent_error})result = await _get_run_results(params, copilot_ctx)_record_per_tool_budget_problem_blocks_from_results(copilot_ctx, result)@@ -4004,6 +4055,10 @@ async def update_and_run_blocks_tool("""copilot_ctx = ctx.contextarguments = {"workflow_yaml": workflow_yaml, "block_labels": block_labels, "parameters": parameters or {}}+ turn_intent_error = _turn_intent_tool_error(copilot_ctx, "update_and_run_blocks")+ if turn_intent_error:+ return _diagnosis_repair_tool_error(copilot_ctx, "update_and_run_blocks", turn_intent_error)+policy = getattr(copilot_ctx, "request_policy", None)skip_run_after_update = (isinstance(policy, RequestPolicy)diff --git a/skyvern/forge/sdk/copilot/turn_intent.py b/skyvern/forge/sdk/copilot/turn_intent.pyindex cca9c03f3..739748885 100644--- a/skyvern/forge/sdk/copilot/turn_intent.py+++ b/skyvern/forge/sdk/copilot/turn_intent.py@@ -23,6 +23,16 @@ class TurnIntentMode(StrEnum):UNKNOWN = "unknown"+NO_MUTATION_TURN_INTENT_MODES = frozenset(+ {+ TurnIntentMode.DOCS_ANSWER,+ TurnIntentMode.DIAGNOSE,+ TurnIntentMode.CLARIFY,+ TurnIntentMode.REFUSE,+ }+)++class RequiredContextKey(StrEnum):CURRENT_WORKFLOW = "current_workflow"PROPOSED_WORKFLOW = "proposed_workflow"@@ -52,6 +62,7 @@ class TurnIntentReasonCode(StrEnum):RUN_CONTEXT_PRESENT = "run_context_present"BROWSER_CONTEXT_PRESENT = "browser_context_present"KEYWORD_HEURISTIC = "keyword_heuristic"+ RAW_SECRET_REFUSAL = "raw_secret_refusal"class TurnIntentAuthority(BaseModel):@@ -131,9 +142,22 @@ class TurnIntent(BaseModel):_GOAL_MAX_CHARS = 240_BUILD_TERMS = ("build", "create", "make", "generate")+_NEW_BROWSER_TASK_TERMS = ("go to", "navigate to", "open", "visit", "search for")_EDIT_TERMS = ("edit", "update", "change", "modify", "replace", "fix")_DIAGNOSE_TERMS = ("debug", "diagnose", "failed", "failure", "error", "result")-_DOCS_TERMS = ("explain", "how do", "how does", "what is", "what are", "why", "docs", "documentation")+_DOCS_TERMS = (+ "explain",+ "how do",+ "how does",+ "what is",+ "what are",+ "why",+ "docs",+ "documentation",+ " vs ",+ " versus ",+ "difference between",+)def _normalize_user_goal(user_message: str) -> str:@@ -157,14 +181,16 @@ def _contains_any(text: str, terms: tuple[str, ...]) -> bool:def _mode_from_keywords(user_message: str, *, has_workflow: bool) -> tuple[TurnIntentMode, TurnIntentExpectedOutput] | None:+ if has_workflow and _contains_any(user_message, _EDIT_TERMS):+ return TurnIntentMode.EDIT, TurnIntentExpectedOutput.WORKFLOW_UPDATEif _contains_any(user_message, _DIAGNOSE_TERMS):return TurnIntentMode.DIAGNOSE, TurnIntentExpectedOutput.RUN_RESULTif _contains_any(user_message, _DOCS_TERMS):return TurnIntentMode.DOCS_ANSWER, TurnIntentExpectedOutput.EXPLANATION- if has_workflow and _contains_any(user_message, _EDIT_TERMS):- return TurnIntentMode.EDIT, TurnIntentExpectedOutput.WORKFLOW_UPDATEif _contains_any(user_message, _BUILD_TERMS):return TurnIntentMode.BUILD, TurnIntentExpectedOutput.WORKFLOW_DRAFT+ if not has_workflow and _contains_any(user_message, _NEW_BROWSER_TASK_TERMS):+ return TurnIntentMode.BUILD, TurnIntentExpectedOutput.WORKFLOW_DRAFTreturn None@@ -219,7 +245,14 @@ def build_turn_intent(confidence = 0.2 if (has_workflow or has_prior_context or chat_history) else 0.0missing_context_question = None- if request_policy.user_response_policy == "ask_clarification":+ if request_policy.raw_secret_detected:+ mode = TurnIntentMode.REFUSE+ expected_output = TurnIntentExpectedOutput.REFUSAL+ confidence = 0.9+ missing_context_question = request_policy.clarification_question+ authority.requires_user_input = True+ reason_codes.append(TurnIntentReasonCode.RAW_SECRET_REFUSAL)+ elif request_policy.user_response_policy == "ask_clarification":mode = TurnIntentMode.CLARIFYexpected_output = TurnIntentExpectedOutput.CLARIFICATIONconfidence = 0.8@@ -236,9 +269,16 @@ def build_turn_intent(reason_codes.append(TurnIntentReasonCode.KEYWORD_HEURISTIC)if mode == TurnIntentMode.DOCS_ANSWER:+ authority.may_update_workflow = False+ authority.may_run_blocks = Falserequired_context.append(RequiredContextKey.DOCS_CONTEXT)elif mode == TurnIntentMode.DIAGNOSE and RequiredContextKey.LATEST_RUN_RESULT not in required_context:+ authority.may_update_workflow = False+ authority.may_run_blocks = Falserequired_context.append(RequiredContextKey.LATEST_RUN_RESULT)+ elif mode == TurnIntentMode.DIAGNOSE:+ authority.may_update_workflow = False+ authority.may_run_blocks = Falsereturn TurnIntent(mode=mode,diff --git a/tests/unit/test_copilot_turn_intent.py b/tests/unit/test_copilot_turn_intent.pyindex 274584ba8..6f3ddf9a6 100644--- a/tests/unit/test_copilot_turn_intent.py+++ b/tests/unit/test_copilot_turn_intent.py@@ -1,12 +1,17 @@from __future__ import annotationsfrom datetime import datetime, timezone+from types import SimpleNamespacefrom unittest.mock import MagicMockimport pytestfrom pydantic import ValidationError-from skyvern.forge.sdk.copilot.agent import RequestPolicyGuardrailInputs, _store_request_policy_on_context+from skyvern.forge.sdk.copilot.agent import (+ RequestPolicyGuardrailInputs,+ _native_tools_for_turn,+ _store_request_policy_on_context,+)from skyvern.forge.sdk.copilot.context import CopilotContextfrom skyvern.forge.sdk.copilot.request_policy import RequestPolicyfrom skyvern.forge.sdk.copilot.turn_intent import (@@ -103,6 +108,32 @@ def test_build_turn_intent_uses_request_policy_clarification_without_changing_poassert TurnIntentReasonCode.REQUEST_POLICY_CLARIFICATION in intent.reason_codes+def test_build_turn_intent_routes_raw_secret_to_refuse_mode() -> None:+ policy = RequestPolicy(+ credential_input_kind="raw_secret",+ raw_secret_detected=True,+ user_response_policy="ask_clarification",+ allow_update_workflow=False,+ allow_run_blocks=False,+ clarification_question="Store the credential in the Credentials UI.",+ )++ intent = build_turn_intent(+ user_message="Use this password: hunter2 to sign in.",+ workflow_yaml="",+ chat_history=[],+ global_llm_context="",+ request_policy=policy,+ )++ assert intent.mode == TurnIntentMode.REFUSE+ assert intent.authority.may_update_workflow is False+ assert intent.authority.may_run_blocks is False+ assert intent.authority.requires_user_input is True+ assert intent.missing_context_question == "Store the credential in the Credentials UI."+ assert TurnIntentReasonCode.RAW_SECRET_REFUSAL in intent.reason_codes++def test_build_turn_intent_redacts_user_goal() -> None:intent = build_turn_intent(user_message="Use password: hunter2 and build the workflow",@@ -126,9 +157,40 @@ def test_build_turn_intent_marks_docs_context_for_docs_answer() -> None:)assert intent.mode == TurnIntentMode.DOCS_ANSWER+ assert intent.authority.may_update_workflow is False+ assert intent.authority.may_run_blocks is False+ assert RequiredContextKey.DOCS_CONTEXT in intent.required_context+++def test_build_turn_intent_marks_platform_comparison_as_docs_answer() -> None:+ intent = build_turn_intent(+ user_message="I meant run with code vs run with agent",+ workflow_yaml="blocks: []",+ chat_history=[],+ global_llm_context="",+ request_policy=RequestPolicy(),+ )++ assert intent.mode == TurnIntentMode.DOCS_ANSWER+ assert intent.authority.may_update_workflow is False+ assert intent.authority.may_run_blocks is Falseassert RequiredContextKey.DOCS_CONTEXT in intent.required_context+def test_build_turn_intent_marks_blank_workflow_browser_task_as_build() -> None:+ intent = build_turn_intent(+ user_message="Go to https://en.wikipedia.org and search for Bauhaus.",+ workflow_yaml="",+ chat_history=[],+ global_llm_context="",+ request_policy=RequestPolicy(),+ )++ assert intent.mode == TurnIntentMode.BUILD+ assert intent.authority.may_update_workflow is True+ assert intent.authority.may_run_blocks is True++def test_build_turn_intent_marks_run_context_for_diagnose() -> None:intent = build_turn_intent(user_message="Diagnose the failed run",@@ -139,9 +201,24 @@ def test_build_turn_intent_marks_run_context_for_diagnose() -> None:)assert intent.mode == TurnIntentMode.DIAGNOSE+ assert intent.authority.may_update_workflow is False+ assert intent.authority.may_run_blocks is Falseassert RequiredContextKey.LATEST_RUN_RESULT in intent.required_context+def test_build_turn_intent_keeps_explicit_fix_as_edit() -> None:+ intent = build_turn_intent(+ user_message="Fix the error after login.",+ workflow_yaml="blocks: []",+ chat_history=[],+ global_llm_context="",+ request_policy=RequestPolicy(),+ )++ assert intent.mode == TurnIntentMode.EDIT+ assert intent.authority.may_update_workflow is True++def test_store_request_policy_attaches_turn_intent_to_context() -> None:ctx = CopilotContext(organization_id="org-1",@@ -166,5 +243,21 @@ def test_store_request_policy_attaches_turn_intent_to_context() -> None:_store_request_policy_on_context(ctx, policy, inputs)assert ctx.turn_intent is not None- assert ctx.turn_intent.authority.may_update_workflow is True+ assert ctx.turn_intent.authority.may_update_workflow is Falseassert ctx.turn_intent.authority.may_run_blocks is False+++def test_answer_only_turn_intent_hides_get_run_results_tool() -> None:+ tools = [+ SimpleNamespace(name="update_workflow"),+ SimpleNamespace(name="get_run_results"),+ SimpleNamespace(name="list_credentials"),+ ]+ intent = TurnIntent(+ mode=TurnIntentMode.DIAGNOSE,+ authority=TurnIntentAuthority(may_update_workflow=False, may_run_blocks=False),+ )++ filtered = _native_tools_for_turn(tools, intent)++ assert filtered == []diff --git a/tests/unit/test_copilot_turn_intent_tool_gate.py b/tests/unit/test_copilot_turn_intent_tool_gate.pynew file mode 100644index 000000000..05bca780e--- /dev/null+++ b/tests/unit/test_copilot_turn_intent_tool_gate.py@@ -0,0 +1,112 @@+from __future__ import annotations++from types import SimpleNamespace+from unittest.mock import AsyncMock, patch++import pytest++from skyvern.forge.sdk.copilot.context import CopilotContext+from skyvern.forge.sdk.copilot.tools import _turn_intent_tool_error, _update_workflow+from skyvern.forge.sdk.copilot.turn_intent import TurnIntent, TurnIntentAuthority, TurnIntentMode+++def _ctx(turn_intent: TurnIntent) -> CopilotContext:+ return CopilotContext(+ organization_id="org-1",+ workflow_id="wf-1",+ workflow_permanent_id="wfp-1",+ workflow_yaml="title: Existing\nworkflow_definition:\n blocks: []\n",+ browser_session_id=None,+ stream=SimpleNamespace(), # type: ignore[arg-type]+ turn_intent=turn_intent,+ )+++ ("mode", "tool_name"),+ [+ (TurnIntentMode.DOCS_ANSWER, "update_workflow"),+ (TurnIntentMode.DIAGNOSE, "run_blocks_and_collect_debug"),+ (TurnIntentMode.CLARIFY, "update_and_run_blocks"),+ (TurnIntentMode.REFUSE, "update_and_run_blocks"),+ ],+)+def test_no_mutation_turn_intent_blocks_mutating_tools(mode: TurnIntentMode, tool_name: str) -> None:+ intent = TurnIntent(+ mode=mode,+ authority=TurnIntentAuthority(+ may_update_workflow=False,+ may_run_blocks=False,+ requires_user_input=mode in {TurnIntentMode.CLARIFY, TurnIntentMode.REFUSE},+ ),+ missing_context_question="Which target should I use?" if mode == TurnIntentMode.CLARIFY else None,+ )++ error = _turn_intent_tool_error(_ctx(intent), tool_name)++ assert error is not None+ assert f"`{mode.value}`" in error+ assert f"`{tool_name}`" in error+ assert "Do not update workflow YAML or run browser blocks" in error+ assert "safe_reason_code=turn_intent_no_mutation" in error+++def test_turn_intent_gate_allows_draft_update_without_run_authority() -> None:+ intent = TurnIntent(+ mode=TurnIntentMode.DRAFT_ONLY,+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=False),+ )++ assert _turn_intent_tool_error(_ctx(intent), "update_workflow") is None+++def test_turn_intent_gate_defers_partial_authority_to_request_policy() -> None:+ intent = TurnIntent(+ mode=TurnIntentMode.CLARIFY,+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=False, requires_user_input=True),+ )++ assert _turn_intent_tool_error(_ctx(intent), "update_and_run_blocks") is None+++async def test_update_workflow_stops_before_persisting_for_answer_only_intent() -> None:+ intent = TurnIntent(+ mode=TurnIntentMode.DOCS_ANSWER,+ authority=TurnIntentAuthority(may_update_workflow=False, may_run_blocks=False),+ )+ ctx = _ctx(intent)++ with patch("skyvern.forge.sdk.copilot.tools.app") as mock_app:+ mock_app.WORKFLOW_SERVICE.update_workflow_definition = AsyncMock()+ result = await _update_workflow({"workflow_yaml": ctx.workflow_yaml}, ctx)++ assert result["ok"] is False+ assert "`docs_answer`" in result["error"]+ mock_app.WORKFLOW_SERVICE.update_workflow_definition.assert_not_called()+++def test_update_and_run_blocks_reports_run_blocked_priority() -> None:+ intent = TurnIntent(+ mode=TurnIntentMode.DIAGNOSE,+ authority=TurnIntentAuthority(may_update_workflow=False, may_run_blocks=False),+ )+ error = _turn_intent_tool_error(_ctx(intent), "update_and_run_blocks")++ assert error is not None+ assert "turn_intent_no_mutation_run_blocked" in error+++def test_answer_only_diagnose_blocks_get_run_results_tool() -> None:+ intent = TurnIntent(+ mode=TurnIntentMode.DIAGNOSE,+ authority=TurnIntentAuthority(may_update_workflow=False, may_run_blocks=False),+ )++ error = _turn_intent_tool_error(_ctx(intent), "get_run_results")++ assert error is not None+ assert "`diagnose`" in error+ assert "`get_run_results`" in error+ assert "fetch additional run context with tools" in error+ assert "turn_intent_no_mutation_context_read_blocked" in error