Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-9927 Carry docs intent across bare confirmations in TurnIntent (#6093)
Andrew Neilson7df21a9437bf
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex 924a64000..3bc6d74ad 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -61,7 +61,12 @@ from skyvern.forge.sdk.copilot.request_policy import ()from 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 NO_MUTATION_TURN_INTENT_MODES, TurnIntent, build_turn_intent+from skyvern.forge.sdk.copilot.turn_intent import (+ NO_MUTATION_TURN_INTENT_MODES,+ TurnIntent,+ TurnIntentMode,+ build_turn_intent,+)from skyvern.forge.sdk.schemas.persistent_browser_sessions import is_final_statusfrom skyvern.forge.sdk.schemas.workflow_copilot import (WorkflowCopilotChatHistoryMessage,@@ -366,7 +371,7 @@ def _build_dynamic_system_prompt(tool_usage_guide: str, config: CopilotConfig) -if not isinstance(policy, RequestPolicy):return base_system_promptpolicy_summary = escape_code_fences(redact_raw_secrets_for_prompt(policy.prompt_summary()))- return (+ prompt = (base_system_prompt+ "\n\nREQUEST POLICY:\n```yaml\n"+ policy_summary@@ -377,10 +382,24 @@ def _build_dynamic_system_prompt(tool_usage_guide: str, config: CopilotConfig) -+ "workflow and skip the browser run with a credential setup message. "+ "If `resolved_credentials` are present, use those `credential_id` values.")+ return prompt + _docs_answer_turn_directive(getattr(ctx, "turn_intent", None))return instructions+def _docs_answer_turn_directive(turn_intent: TurnIntent | None) -> str:+ """Prompt-side complement to the no-mutation tool gate — keeps a docs-answer+ turn from substituting a routing question or build offer for the inline answer."""+ if not isinstance(turn_intent, TurnIntent) or turn_intent.mode != TurnIntentMode.DOCS_ANSWER:+ return ""+ return (+ "\n\nTURN INTENT: docs_answer\n"+ "This turn is a documentation or explanation question. Answer it inline in the user's language. "+ "Do not ask whether the user wants a workflow change instead, do not re-ask a confirmation the "+ "prior turn already covered, and do not offer to build an example workflow in place of answering."+ )++def _build_user_context(workflow_yaml: str,chat_history_text: str,diff --git a/skyvern/forge/sdk/copilot/turn_intent.py b/skyvern/forge/sdk/copilot/turn_intent.pyindex f3b43d6cf..21a38758f 100644--- a/skyvern/forge/sdk/copilot/turn_intent.py+++ b/skyvern/forge/sdk/copilot/turn_intent.py@@ -1,5 +1,6 @@from __future__ import annotations+import functoolsimport refrom enum import StrEnumfrom typing import Any@@ -67,6 +68,7 @@ class TurnIntentReasonCode(StrEnum):RUN_CONTEXT_PRESENT = "run_context_present"BROWSER_CONTEXT_PRESENT = "browser_context_present"KEYWORD_HEURISTIC = "keyword_heuristic"+ CONFIRMATION_CARRYOVER = "confirmation_carryover"RAW_SECRET_REFUSAL = "raw_secret_refusal"@@ -186,9 +188,18 @@ def _has_latest_assistant_turn(chat_history: list[WorkflowCopilotChatHistoryMess)[email protected]_cache(maxsize=None)+def _word_boundary_pattern(terms: tuple[str, ...]) -> re.Pattern[str]:+ alternation = "|".join(re.escape(term.strip()) for term in terms)+ # Boundaries are alphanumeric-only so `_` separates words: the edit+ # term `update` matches a block label like `update_card`. Optional+ # trailing `s` matches plurals (`errors`) but deliberately not `-ed`+ # forms (`fixed` must not match `fix`).+ return re.compile(rf"(?<![a-z0-9])(?:{alternation})s?(?![a-z0-9])")++def _contains_any(text: str, terms: tuple[str, ...]) -> bool:- normalized = text.lower()- return any(term in normalized for term in terms)+ return _word_boundary_pattern(terms).search(text.lower()) is not Nonedef _workflow_block_labels(workflow_yaml: str | None) -> set[str]:@@ -290,6 +301,56 @@ def _mode_from_keywords(return None+_AFFIRMATIVE_REPLIES = frozenset(+ {+ "yes",+ "y",+ "yeah",+ "yep",+ "yup",+ "sure",+ "ok",+ "okay",+ "confirm",+ "confirmed",+ "i confirm",+ "correct",+ "right",+ "thats right",+ "that's right",+ "go ahead",+ "do it",+ "please do",+ "sounds good",+ "affirmative",+ }+)+++def _is_bare_affirmative(user_message: str) -> bool:+ """True when the message is only a confirmation token (no new instruction)."""+ normalized = (user_message or "").strip().lower().rstrip(".!,;: ")+ return normalized in _AFFIRMATIVE_REPLIES+++def _carryover_mode_from_prior_turn(+ chat_history: list[WorkflowCopilotChatHistoryMessage], *, has_workflow: bool+) -> tuple[TurnIntentMode, TurnIntentExpectedOutput] | None:+ """Mode of the most recent prior user turn that keyword-classifies. A bare+ confirmation carries no keywords of its own, so it inherits the turn it confirms."""+ for message in reversed(chat_history):+ if message.sender != WorkflowCopilotChatSender.USER:+ continue+ content = (message.content or "").strip()+ # Skip earlier confirmations so a chain of "yes"/"confirm" turns walks+ # back to the substantive request, not to the nearest confirmation.+ if not content or _is_bare_affirmative(content):+ continue+ if carried := _mode_from_keywords(content, has_workflow=has_workflow):+ return carried+ return None++def build_turn_intent(*,user_message: str,@@ -364,6 +425,12 @@ def build_turn_intent(mode, expected_output = keyword_modeconfidence = 0.35reason_codes.append(TurnIntentReasonCode.KEYWORD_HEURISTIC)+ elif _is_bare_affirmative(user_message) and (+ carried_mode := _carryover_mode_from_prior_turn(chat_history, has_workflow=has_workflow)+ ):+ mode, expected_output = carried_mode+ confidence = 0.3+ reason_codes.append(TurnIntentReasonCode.CONFIRMATION_CARRYOVER)if mode == TurnIntentMode.EDIT:unresolved_block_refs = _unresolved_explicit_block_refs(user_message, workflow_yaml)diff --git a/tests/unit/test_copilot_turn_intent.py b/tests/unit/test_copilot_turn_intent.pyindex ce4d0b08e..8bf20907d 100644--- a/tests/unit/test_copilot_turn_intent.py+++ b/tests/unit/test_copilot_turn_intent.py@@ -9,6 +9,7 @@ from pydantic import ValidationErrorfrom skyvern.forge.sdk.copilot.agent import (RequestPolicyGuardrailInputs,+ _docs_answer_turn_directive,_native_tools_for_turn,_store_request_policy_on_context,)@@ -37,6 +38,14 @@ def _user_message(content: str) -> WorkflowCopilotChatHistoryMessage:)+def _ai_message(content: str) -> WorkflowCopilotChatHistoryMessage:+ return WorkflowCopilotChatHistoryMessage(+ sender=WorkflowCopilotChatSender.AI,+ content=content,+ created_at=datetime.now(timezone.utc),+ )++def test_turn_intent_defaults_to_unknown_shadow_contract() -> None:intent = TurnIntent()@@ -264,6 +273,112 @@ workflow_definition:assert UNRESOLVED_BLOCK_REF_TARGET_ENTITY not in intent.target_entities+def test_build_turn_intent_carries_docs_mode_onto_bare_confirmation() -> None:+ intent = build_turn_intent(+ user_message="I confirm.",+ workflow_yaml="blocks: []",+ chat_history=[+ _user_message("Explain how workflow parameters and webhooks work."),+ _ai_message("Do you want me to explain parameters, or modify the workflow?"),+ ],+ 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 False+ assert RequiredContextKey.DOCS_CONTEXT in intent.required_context+ assert TurnIntentReasonCode.CONFIRMATION_CARRYOVER in intent.reason_codes+++def test_build_turn_intent_carries_mode_from_most_recent_classifiable_prior_turn() -> None:+ intent = build_turn_intent(+ user_message="yes",+ workflow_yaml="blocks: []",+ chat_history=[+ _user_message("Explain how I can call this workflow from an external tool."),+ _ai_message("Is your goal to modify the workflow, or do you want information?"),+ _user_message("I just want to know whether the parameters are fixed."),+ _ai_message("Do you confirm you want an explanation of parameters and webhooks?"),+ ],+ global_llm_context="",+ request_policy=RequestPolicy(),+ )++ assert intent.mode == TurnIntentMode.DOCS_ANSWER+ assert TurnIntentReasonCode.CONFIRMATION_CARRYOVER in intent.reason_codes+++def test_build_turn_intent_carries_build_mode_onto_confirmation() -> None:+ intent = build_turn_intent(+ user_message="go ahead",+ workflow_yaml="",+ chat_history=[_user_message("Build a workflow that downloads my invoices.")],+ global_llm_context="",+ request_policy=RequestPolicy(),+ )++ assert intent.mode == TurnIntentMode.BUILD+ assert TurnIntentReasonCode.CONFIRMATION_CARRYOVER in intent.reason_codes+++def test_build_turn_intent_does_not_carry_over_when_message_is_not_bare_affirmative() -> None:+ intent = build_turn_intent(+ user_message="yes, but change the target URL first",+ workflow_yaml="blocks: []",+ chat_history=[_user_message("Explain how parameters work.")],+ global_llm_context="",+ request_policy=RequestPolicy(),+ )++ assert intent.mode != TurnIntentMode.DOCS_ANSWER+ assert TurnIntentReasonCode.CONFIRMATION_CARRYOVER not in intent.reason_codes+++def test_build_turn_intent_confirmation_without_classifiable_prior_stays_unknown() -> None:+ intent = build_turn_intent(+ user_message="I confirm.",+ workflow_yaml="blocks: []",+ chat_history=[_user_message("I confirm.")],+ global_llm_context="",+ request_policy=RequestPolicy(),+ )++ assert intent.mode == TurnIntentMode.UNKNOWN+ assert TurnIntentReasonCode.CONFIRMATION_CARRYOVER not in intent.reason_codes+++def test_build_turn_intent_raw_secret_outranks_confirmation_carryover() -> 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,+ )+ intent = build_turn_intent(+ user_message="yes",+ workflow_yaml="blocks: []",+ chat_history=[_user_message("Build a workflow that downloads invoices.")],+ global_llm_context="",+ request_policy=policy,+ )++ assert intent.mode == TurnIntentMode.REFUSE+++def test_docs_answer_turn_directive_renders_only_for_docs_answer_mode() -> None:+ docs_directive = _docs_answer_turn_directive(TurnIntent(mode=TurnIntentMode.DOCS_ANSWER))+ assert "TURN INTENT: docs_answer" in docs_directive+ assert "Answer it inline in the user's language" in docs_directive+ assert "do not offer to build an example workflow" in docs_directive++ assert _docs_answer_turn_directive(TurnIntent(mode=TurnIntentMode.BUILD)) == ""+ assert _docs_answer_turn_directive(TurnIntent(mode=TurnIntentMode.EDIT)) == ""+ assert _docs_answer_turn_directive(None) == ""++def test_store_request_policy_attaches_turn_intent_to_context() -> None:ctx = CopilotContext(organization_id="org-1",