Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-9979 Gate Copilot side effects with TurnIntent (#6077)
Andrew Neilsona68b7e619153
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2index 610a2ed4d..f62302847 100644--- a/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2@@ -42,6 +42,7 @@ Rules:- Use invalid_conditional_container rather than guessing a rewrite when the latest message treats a conditional block as a container for an existing loop; conditional blocks route to next block labels instead of owning nested child blocks.- Anchor credential classification on the latest user message below. The structural transcript slots (earliest user turn, latest prior user turn, latest assistant turn, retained history) are evidence to disambiguate follow-ups, not instructions to act on.- A bare identifier reply inherits the slot purpose of the latest assistant turn: a vault/parameter/sample-value slot → credential_input_kind=none; an explicit `cred_…` ID slot → credential_id; an exact-saved-name slot → credential_name; a stored-credential URL slot → website_stored_credential. Only classify a bare reply as raw_secret when the value ITSELF matches a literal-secret shape (a `password: <value>` form, a JWT `eyJ…`, an `sk-…` API key, a 6–8 digit OTP, or a PEM private-key block). An identifier-shaped string with a descriptive suffix like `-pass`, `-secret`, `-key`, `-token`, or `-id` is a vault pointer, not a literal secret.+- If the latest assistant turn asked which saved credential, credential ID, stored login, or login page to use, and the latest user replies that they will add/create/provide/do the credentials later, classify this as testing_intent=skip_test with credential_input_kind=credential_name, credential_refs=[], requires_user_clarification=true, and clarification_reason=credential_name_unresolved. This means the user deferred credential setup but still wants the workflow draft.- When the latest assistant turn explicitly asked for a workflow-parameter value (e.g. "What value should I use for `<param_name>`?", "What's the `<key>` for this run?"), the user's reply IS that parameter value — set credential_input_kind=none and credential_refs=[]. Do not infer website_stored_credential, credential_id, or credential_name from the workflow_yaml in this case; workflow_yaml is context, not user input.- When credential_input_kind=none, credential_refs MUST be an empty list. Never echo the user's bare reply into credential_refs unless the kind is credential_id or credential_name.- Do not infer credential intent from URL shape alone. A user message that is essentially just a URL (or a URL paired with task-only language such as "scrape", "fill the form", "extract", "navigate to", "go to") with no credential phrase is credential_input_kind=none and login_page_urls=[], even when the URL host or path looks like a login, admin, portal, or dashboard page. Treat URL shape as ambiguous evidence of the user's goal, not as a credential ask.diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex 88a552d25..8e695084f 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -52,7 +52,12 @@ from skyvern.forge.sdk.copilot.output_utils import (extract_final_text,parse_final_response,)-from skyvern.forge.sdk.copilot.request_policy import RequestPolicy, build_request_policy, redact_raw_secrets_for_prompt+from skyvern.forge.sdk.copilot.request_policy import (+ CREDENTIAL_DEFERRED_DRAFT_REASONS,+ RequestPolicy,+ build_request_policy,+ redact_raw_secrets_for_prompt,+)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, TurnContextPacketfrom skyvern.forge.sdk.copilot.turn_intent import NO_MUTATION_TURN_INTENT_MODES, TurnIntent, build_turn_intent@@ -365,6 +370,10 @@ def _build_dynamic_system_prompt(tool_usage_guide: str, config: CopilotConfig) -+ "\n\nREQUEST POLICY:\n```yaml\n"+ policy_summary+ "\n```\nFollow this policy. If `allow_run_blocks` is false, do not call block-running tools. "+ + "Exception: when `clarification_reason` is `workflow_credential_inputs_unbound` or "+ + "`credential_name_unresolved` and "+ + "`allow_missing_credentials_in_draft` is true, call `update_and_run_blocks`; it will save the draft "+ + "workflow and skip the browser run with a credential setup message. "+ "If `resolved_credentials` are present, use those `credential_id` values.")@@ -501,9 +510,25 @@ def _turn_intent_disables_tools(turn_intent: TurnIntent | None) -> bool: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]:+def _request_policy_requires_update_and_run_skip_path(request_policy: RequestPolicy | None) -> bool:+ return (+ isinstance(request_policy, RequestPolicy)+ and request_policy.allow_update_workflow+ and not request_policy.allow_run_blocks+ and request_policy.allow_missing_credentials_in_draft+ and request_policy.clarification_reason in CREDENTIAL_DEFERRED_DRAFT_REASONS+ )+++def _native_tools_for_turn(+ native_tools: list[Any],+ turn_intent: TurnIntent | None,+ request_policy: RequestPolicy | None = None,+) -> list[Any]:if _turn_intent_disables_tools(turn_intent):return []+ if _request_policy_requires_update_and_run_skip_path(request_policy):+ return [tool for tool in native_tools if getattr(tool, "name", None) != "update_workflow"]return list(native_tools)@@ -1637,7 +1662,7 @@ async def _run_copilot_turn_impl(alias_map = {}overlays = {}- native_tools = _native_tools_for_turn(NATIVE_TOOLS, ctx.turn_intent)+ native_tools = _native_tools_for_turn(list(NATIVE_TOOLS), ctx.turn_intent, ctx.request_policy)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())diff --git a/skyvern/forge/sdk/copilot/output_utils.py b/skyvern/forge/sdk/copilot/output_utils.pyindex f1acf112d..0b98bd73b 100644--- a/skyvern/forge/sdk/copilot/output_utils.py+++ b/skyvern/forge/sdk/copilot/output_utils.py@@ -348,6 +348,8 @@ def summarize_tool_result(tool_name: str, result: dict[str, Any]) -> str:if tool_name == "update_workflow":return f"Workflow updated ({data.get('block_count', '?')} blocks)"+ if tool_name == "update_and_run_blocks" and data.get("skipped_run"):+ return f"Workflow updated ({data.get('block_count', '?')} blocks); browser run skipped"if tool_name == "list_credentials":return f"Found {data.get('count', 0)} credential(s)"if tool_name == "get_block_schema":diff --git a/skyvern/forge/sdk/copilot/request_policy.py b/skyvern/forge/sdk/copilot/request_policy.pyindex 95dc474f4..e96a2b029 100644--- a/skyvern/forge/sdk/copilot/request_policy.py+++ b/skyvern/forge/sdk/copilot/request_policy.py@@ -40,6 +40,9 @@ ClarificationReason = Literal["workflow_credential_inputs_unbound",]_VALID_CLARIFICATION_REASONS: frozenset[ClarificationReason] = frozenset(get_args(ClarificationReason))+CREDENTIAL_DEFERRED_DRAFT_REASONS: frozenset[ClarificationReason] = frozenset(+ {"workflow_credential_inputs_unbound", "credential_name_unresolved"}+)_PRE_RESOLUTION_CLARIFICATION_REASONS = {"credential_invention_requested","ambiguous_loop_edit",@@ -64,9 +67,10 @@ _RAW_SECRET_QUESTION = ()_SAVED_CREDENTIAL_NAME_QUESTION_STABLE_PREFIX = "Which saved credential should I use? Please provide the exact credential name or a credential ID beginning with cred_."_SAVED_CREDENTIAL_NAME_QUESTION = f"{_SAVED_CREDENTIAL_NAME_QUESTION_STABLE_PREFIX} {_CREDENTIALS_UI_DIRECTIONS}"-_STORED_CREDENTIAL_URL_QUESTION = (- f"Which website or login page should I use to look up the stored credential? {_CREDENTIALS_UI_DIRECTIONS}"+_STORED_CREDENTIAL_URL_QUESTION_STABLE_PREFIX = (+ "Which website or login page should I use to look up the stored credential?")+_STORED_CREDENTIAL_URL_QUESTION = f"{_STORED_CREDENTIAL_URL_QUESTION_STABLE_PREFIX} {_CREDENTIALS_UI_DIRECTIONS}"_CREDENTIAL_ID_RE = re.compile(r"\bcred_[A-Za-z0-9][A-Za-z0-9_-]*\b")_JINJA_TEMPLATE_VAR_RE = re.compile(r"\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}")_CREDENTIAL_PARAM_METADATA_FIELDS = frozenset(@@ -614,7 +618,10 @@ def _last_assistant_message_was_saved_credential_question() -> bool:for message in reversed(chat_history):if message.sender == WorkflowCopilotChatSender.AI:- return _SAVED_CREDENTIAL_NAME_QUESTION_STABLE_PREFIX in message.content+ return (+ _SAVED_CREDENTIAL_NAME_QUESTION_STABLE_PREFIX in message.content+ or _STORED_CREDENTIAL_URL_QUESTION_STABLE_PREFIX in message.content+ )return False@@ -637,11 +644,12 @@ def _should_defer_repeated_unresolved_credential_question(*,chat_history: list[WorkflowCopilotChatHistoryMessage],) -> bool:+ if not _last_assistant_message_was_saved_credential_question(chat_history):+ return Falsereturn (policy.credential_input_kind in ("none", "credential_name")and policy.clarification_reason == "credential_name_unresolved"and not _has_resolvable_credential_scope(policy)- and _last_assistant_message_was_saved_credential_question(chat_history))@@ -872,6 +880,7 @@ async def build_request_policy(chat_history=chat_history,):policy.requires_user_clarification = False+ policy.allow_update_workflow = Truepolicy.allow_run_blocks = Falsepolicy.allow_missing_credentials_in_draft = Truediff --git a/skyvern/forge/sdk/copilot/tools.py b/skyvern/forge/sdk/copilot/tools.pyindex d8db0ac70..0b9306cb1 100644--- a/skyvern/forge/sdk/copilot/tools.py+++ b/skyvern/forge/sdk/copilot/tools.py@@ -64,11 +64,16 @@ from skyvern.forge.sdk.copilot.output_utils import (sanitize_tool_result_for_llm,truncate_output,)-from skyvern.forge.sdk.copilot.request_policy import RequestPolicy+from skyvern.forge.sdk.copilot.request_policy import CREDENTIAL_DEFERRED_DRAFT_REASONS, 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, TurnIntent+from skyvern.forge.sdk.copilot.turn_intent import (+ NO_MUTATION_TURN_INTENT_MODES,+ UNRESOLVED_BLOCK_REF_TARGET_ENTITY,+ TurnIntent,+ TurnIntentMode,+)from skyvern.forge.sdk.routes.workflow_copilot import _process_workflow_yamlfrom skyvern.forge.sdk.settings_manager import SettingsManagerfrom skyvern.forge.sdk.workflow.exceptions import BaseWorkflowHTTPException@@ -822,58 +827,156 @@ def _request_policy_tool_error(ctx: AgentContext, tool_name: str) -> str | None:policy = getattr(ctx, "request_policy", None)if not isinstance(policy, RequestPolicy):return None+ error: str | None = Noneif tool_name == "update_workflow" and not policy.allow_update_workflow:- return (+ error = ("Request policy blocks workflow updates for the latest user message. ""Ask the user for safe stored credential metadata instead.")- if tool_name in BLOCK_RUNNING_TOOLS and not policy.allow_run_blocks:+ elif tool_name in BLOCK_RUNNING_TOOLS and not policy.allow_run_blocks:if policy.testing_intent == "skip_test":- return "Request policy says the latest user message asked for an untested draft. Use update_workflow only."- if policy.clarification_reason == "workflow_credential_inputs_unbound":- return (+ error = "Request policy says the latest user message asked for an untested draft. Use update_workflow only."+ elif policy.clarification_reason == "workflow_credential_inputs_unbound":+ error = ("Skipped test run: the existing workflow references credential parameters ""whose keys point to workflow inputs that are not configured. REPLY to the user ""with: 'I applied your requested change. I couldn't test the modified workflow ""because I couldn't find the required credentials — please add them via the ""Credentials UI, then I can try again.' Keep the unvalidated draft surfaced.")- return (- "Request policy blocks block-running tools for the latest user message. "- "Ask the user for the required safe credential or clarification before testing."+ else:+ error = (+ "Request policy blocks block-running tools for the latest user message. "+ "Ask the user for the required safe credential or clarification before testing."+ )+ if error is not None:+ LOG.info(+ "copilot authority gate blocked tool",+ authority_gate_layer="request_policy",+ blocked_tool=tool_name,+ request_policy_allow_update_workflow=policy.allow_update_workflow,+ request_policy_allow_run_blocks=policy.allow_run_blocks,+ request_policy_testing_intent=policy.testing_intent,+ request_policy_clarification_reason=policy.clarification_reason,)+ return errorreturn None+def _request_policy_allows_credential_deferred_draft(ctx: AgentContext) -> bool:+ policy = getattr(ctx, "request_policy", None)+ return (+ isinstance(policy, RequestPolicy)+ and policy.allow_update_workflow+ and not policy.allow_run_blocks+ and policy.allow_missing_credentials_in_draft+ and policy.clarification_reason in CREDENTIAL_DEFERRED_DRAFT_REASONS+ )+++def _request_policy_allows_update_and_skip_run(ctx: AgentContext, tool_name: str) -> bool:+ return tool_name == "update_and_run_blocks" and _request_policy_allows_credential_deferred_draft(ctx)+++def _turn_intent_has_edit_target(intent: TurnIntent) -> bool:+ # Keep this aligned with TurnIntent target kinds that make an edit specific enough to mutate safely.+ return any(+ intent.target_entities.get(entity_type)+ for entity_type in (+ "workflow",+ "block",+ "run",+ "proposed_workflow",+ "latest_assistant_proposal",+ )+ )++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:+ if not isinstance(intent, TurnIntent):return Noneauthority = intent.authority- if authority.may_update_workflow or authority.may_run_blocks:- return None+ unresolved_refs = intent.target_entities.get(UNRESOLVED_BLOCK_REF_TARGET_ENTITY, [])+ if intent.mode == TurnIntentMode.EDIT and tool_name in WORKFLOW_MUTATION_TOOLS and unresolved_refs:+ reason_code = "turn_intent_unresolved_edit_target"+ labels = sorted(_workflow_yaml_blocks_by_label(getattr(ctx, "workflow_yaml", None)))+ label_hint = ", ".join(labels[:8]) if labels else "no labeled blocks"+ LOG.info(+ "copilot authority gate blocked tool",+ authority_gate_layer="turn_intent",+ turn_intent_mode=intent.mode.value,+ turn_intent_target_entity_types=sorted(intent.target_entities),+ turn_intent_unresolved_refs=unresolved_refs,+ blocked_tool=tool_name,+ safe_reason_code=reason_code,+ )+ return (+ f"TurnIntent classified this turn as `edit`, but the latest user message references workflow/block "+ f"identifier(s) that are not present in the current workflow: {', '.join(unresolved_refs)}. "+ f"Current workflow labels include: {label_hint}. Ask the user which current block should change before "+ f"mutating or running blocks. safe_reason_code={reason_code}."+ )++ if (+ intent.mode == TurnIntentMode.EDIT+ and tool_name in WORKFLOW_MUTATION_TOOLS+ and not _turn_intent_has_edit_target(intent)+ ):+ reason_code = "turn_intent_missing_edit_target"+ LOG.info(+ "copilot authority gate blocked tool",+ authority_gate_layer="turn_intent",+ turn_intent_mode=intent.mode.value,+ turn_intent_target_entity_types=sorted(intent.target_entities),+ blocked_tool=tool_name,+ safe_reason_code=reason_code,+ )+ return (+ f"TurnIntent classified this turn as `edit`, but could not identify a specific workflow edit target, "+ f"so `{tool_name}` is not allowed. Ask the user which workflow/block should change before mutating. "+ f"safe_reason_code={reason_code}."+ )blocks_update = tool_name in WORKFLOW_MUTATION_TOOLS and not authority.may_update_workflowblocks_run = tool_name in BLOCK_RUNNING_TOOLS and not authority.may_run_blocksblocks_context_read = tool_name in ANSWER_ONLY_CONTEXT_TOOLS+ if blocks_run and not blocks_update and _request_policy_allows_update_and_skip_run(ctx, tool_name):+ return Noneif not blocks_update and not blocks_run and not blocks_context_read:return None- if blocks_run:+ if intent.mode in NO_MUTATION_TURN_INTENT_MODES and blocks_run:reason_code = "turn_intent_no_mutation_run_blocked"- elif blocks_update:+ elif intent.mode in NO_MUTATION_TURN_INTENT_MODES and blocks_update:reason_code = "turn_intent_no_mutation_update_blocked"- else:+ elif blocks_update and blocks_run:+ reason_code = "turn_intent_no_mutation_run_blocked"+ elif blocks_update:+ reason_code = "turn_intent_update_blocked"+ elif blocks_context_read:reason_code = "turn_intent_no_mutation_context_read_blocked"+ else:+ reason_code = "turn_intent_run_blocked"LOG.info(- "copilot turn intent no-mutation gate blocked tool",+ "copilot authority gate blocked tool",+ authority_gate_layer="turn_intent",turn_intent_mode=intent.mode.value,+ turn_intent_target_entity_types=sorted(intent.target_entities),+ turn_intent_may_update_workflow=authority.may_update_workflow,+ turn_intent_may_run_blocks=authority.may_run_blocks,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 ""+ if blocks_run and not blocks_update and authority.may_update_workflow:+ return (+ f"TurnIntent classified this turn as `{intent.mode.value}`, so `{tool_name}` is not allowed "+ f"to run browser blocks for the latest user message. Use `update_workflow` only and keep the draft "+ f"unvalidated. safe_reason_code={reason_code}.{detail}"+ )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 "@@ -882,6 +985,25 @@ def _turn_intent_tool_error(ctx: AgentContext, tool_name: str) -> str | None:)+def _authority_tool_error(+ ctx: AgentContext,+ tool_name: str,+ *,+ ignore_request_policy_error: bool = False,+) -> str | None:+ turn_intent_error = _turn_intent_tool_error(ctx, tool_name)+ request_policy_error = _request_policy_tool_error(ctx, tool_name)+ if turn_intent_error is not None and request_policy_error is not None:+ LOG.info(+ "copilot authority gate blocked tool",+ authority_gate_layer="both",+ blocked_tool=tool_name,+ )+ if request_policy_error is not None and not ignore_request_policy_error:+ return request_policy_error+ return turn_intent_error++_PARAMETER_TYPE_PLACEHOLDERS: dict[WorkflowParameterType, Any] = {WorkflowParameterType.STRING: "",WorkflowParameterType.INTEGER: 0,@@ -963,13 +1085,9 @@ 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}+ authority_error = _authority_tool_error(ctx, "update_workflow")+ if authority_error is not None:+ return {"ok": False, "error": authority_error}workflow_yaml = params["workflow_yaml"]if allow_missing_credentials is None:@@ -3824,6 +3942,16 @@ async def update_workflow_tool(loop_error = _tool_loop_error(copilot_ctx, "update_workflow", arguments)if loop_error:return json.dumps({"ok": False, "error": loop_error})+ if _request_policy_allows_credential_deferred_draft(copilot_ctx):+ result = {+ "ok": False,+ "error": (+ "Use update_and_run_blocks for this credential-deferred draft. It will save the workflow draft "+ "and skip the browser run with the required credential setup message."+ ),+ }+ record_tool_step_result_for_ctx(copilot_ctx, "update_workflow", arguments, result)+ return json.dumps(result)with copilot_span("update_workflow", data={"yaml_length": len(workflow_yaml)}):result = await _update_workflow(@@ -3928,13 +4056,9 @@ 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)+ authority_error = _authority_tool_error(copilot_ctx, "run_blocks_and_collect_debug")+ if authority_error:+ return _diagnosis_repair_tool_error(copilot_ctx, "run_blocks_and_collect_debug", authority_error)loop_error = _tool_loop_error(copilot_ctx, "run_blocks_and_collect_debug", arguments)if loop_error:@@ -4055,20 +4179,14 @@ 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)- and policy.allow_update_workflow- and not policy.allow_run_blocks- and policy.clarification_reason == "workflow_credential_inputs_unbound"+ skip_run_after_update = _request_policy_allows_update_and_skip_run(copilot_ctx, "update_and_run_blocks")+ authority_error = _authority_tool_error(+ copilot_ctx,+ "update_and_run_blocks",+ ignore_request_policy_error=skip_run_after_update,)- policy_error = _request_policy_tool_error(copilot_ctx, "update_and_run_blocks")- if not skip_run_after_update and policy_error:- return _diagnosis_repair_tool_error(copilot_ctx, "update_and_run_blocks", policy_error)+ if authority_error:+ return _diagnosis_repair_tool_error(copilot_ctx, "update_and_run_blocks", authority_error)loop_error = _tool_loop_error(copilot_ctx, "update_and_run_blocks", arguments)if loop_error:@@ -4092,7 +4210,7 @@ async def update_and_run_blocks_tool(update_result = await _update_workflow({"workflow_yaml": workflow_yaml},copilot_ctx,- allow_missing_credentials=False,+ allow_missing_credentials=skip_run_after_update,)_record_workflow_update_result(copilot_ctx, update_result)@@ -4127,10 +4245,10 @@ async def update_and_run_blocks_tool(return json.dumps(result)if skip_run_after_update:- skip_message = policy_error or "Skipped test run: required credentials are not configured."+ skip_message = "Skipped test run: required credentials are not configured."skip_result = {- "ok": False,- "error": skip_message,+ "ok": True,+ "message": skip_message,"data": {"block_count": copilot_ctx.last_update_block_count,"workflow_updated": True,diff --git a/skyvern/forge/sdk/copilot/turn_intent.py b/skyvern/forge/sdk/copilot/turn_intent.pyindex 739748885..f3b43d6cf 100644--- a/skyvern/forge/sdk/copilot/turn_intent.py+++ b/skyvern/forge/sdk/copilot/turn_intent.py@@ -1,8 +1,10 @@from __future__ import annotations+import refrom enum import StrEnumfrom typing import Any+import yamlfrom pydantic import BaseModel, ConfigDict, Field, field_validator, model_validatorfrom skyvern.forge.sdk.copilot.request_policy import RequestPolicy, redact_raw_secrets_for_prompt@@ -10,6 +12,9 @@ from skyvern.forge.sdk.schemas.workflow_copilot import (WorkflowCopilotChatHistoryMessage,WorkflowCopilotChatSender,)+from skyvern.utils.yaml_loader import safe_load_no_dates++UNRESOLVED_BLOCK_REF_TARGET_ENTITY = "unresolved_block_ref"class TurnIntentMode(StrEnum):@@ -158,6 +163,14 @@ _DOCS_TERMS = (" versus ","difference between",)+_IDENTIFIER_REF_RE = r"[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)+"+_CODE_IDENTIFIER_REF_RE = re.compile(rf"`(?P<ref>{_IDENTIFIER_REF_RE})`")+_BLOCK_IDENTIFIER_REF_RE = re.compile(+ rf"\b(?:(?:block|step)\s+(?P<after>{_IDENTIFIER_REF_RE})|(?P<before>{_IDENTIFIER_REF_RE})\s+(?:block|step))\b",+ re.I,+)+_WF_IDENTIFIER_REF_RE = re.compile(r"\bWF_[A-Za-z0-9_]+\b")+_ANY_IDENTIFIER_REF_RE = re.compile(rf"\b{_IDENTIFIER_REF_RE}\b")def _normalize_user_goal(user_message: str) -> str:@@ -178,6 +191,89 @@ def _contains_any(text: str, terms: tuple[str, ...]) -> bool:return any(term in normalized for term in terms)+def _workflow_block_labels(workflow_yaml: str | None) -> set[str]:+ if not workflow_yaml:+ return set()+ try:+ parsed = safe_load_no_dates(workflow_yaml)+ except yaml.YAMLError:+ return set()+ if not isinstance(parsed, dict):+ return set()+ workflow_definition = parsed.get("workflow_definition")+ if not isinstance(workflow_definition, dict):+ return set()+ blocks = workflow_definition.get("blocks")+ if not isinstance(blocks, list):+ return set()+ labels: set[str] = set()+ for block in blocks:+ if not isinstance(block, dict):+ continue+ label = block.get("label")+ if isinstance(label, str) and label:+ labels.add(label)+ return labels+++def _workflow_parameter_keys(workflow_yaml: str | None) -> set[str]:+ if not workflow_yaml:+ return set()+ try:+ parsed = safe_load_no_dates(workflow_yaml)+ except yaml.YAMLError:+ return set()+ if not isinstance(parsed, dict):+ return set()+ workflow_definition = parsed.get("workflow_definition")+ if not isinstance(workflow_definition, dict):+ return set()+ parameters = workflow_definition.get("parameters")+ if not isinstance(parameters, list):+ return set()+ keys: set[str] = set()+ for parameter in parameters:+ if not isinstance(parameter, dict):+ continue+ key = parameter.get("key")+ if isinstance(key, str) and key:+ keys.add(key)+ return keys+++def _explicit_identifier_refs(user_message: str) -> set[str]:+ refs = {match.group("ref") for match in _CODE_IDENTIFIER_REF_RE.finditer(user_message or "")}+ refs.update(+ match.group("after") or match.group("before")+ for match in _BLOCK_IDENTIFIER_REF_RE.finditer(user_message or "")+ if match.group("after") or match.group("before")+ )+ wf_refs = set(_WF_IDENTIFIER_REF_RE.findall(user_message or ""))+ refs.update(wf_refs)+ if wf_refs:+ # If the turn already contains a generated workflow-style ref, include the other+ # identifier-shaped tokens as companion refs. This catches "WF_x worked but y failed"+ # without treating every snake_case field name as a workflow block target.+ refs.update(_ANY_IDENTIFIER_REF_RE.findall(user_message or ""))+ return refs+++def _unresolved_explicit_block_refs(user_message: str, workflow_yaml: str | None) -> list[str]:+ explicit_refs = _explicit_identifier_refs(user_message)+ if not explicit_refs:+ return []+ known_labels = {label.lower() for label in _workflow_block_labels(workflow_yaml)}+ parameter_keys = {key.lower() for key in _workflow_parameter_keys(workflow_yaml)}+ known_non_block_refs = {"workflow_run_id", "browser_session_id"}+ unresolved: list[str] = []+ for ref in sorted(explicit_refs):+ normalized = ref.lower()+ if normalized in known_labels or normalized in parameter_keys or normalized in known_non_block_refs:+ continue+ unresolved.append(ref)+ return unresolved++def _mode_from_keywords(user_message: str, *, has_workflow: bool) -> tuple[TurnIntentMode, TurnIntentExpectedOutput] | None:@@ -213,7 +309,8 @@ def build_turn_intent(reason_codes: list[TurnIntentReasonCode] = [TurnIntentReasonCode.REQUEST_POLICY_DERIVED]if workflow_id or workflow_permanent_id or has_workflow:- target_entities["workflow"] = [value for value in (workflow_permanent_id, workflow_id) if value]+ workflow_targets = [value for value in (workflow_permanent_id, workflow_id) if value]+ target_entities["workflow"] = workflow_targets or ["current_workflow"]if workflow_run_id:target_entities["run"] = [workflow_run_id]if request_policy.credential_refs:@@ -268,6 +365,11 @@ def build_turn_intent(confidence = 0.35reason_codes.append(TurnIntentReasonCode.KEYWORD_HEURISTIC)+ if mode == TurnIntentMode.EDIT:+ unresolved_block_refs = _unresolved_explicit_block_refs(user_message, workflow_yaml)+ if unresolved_block_refs:+ target_entities[UNRESOLVED_BLOCK_REF_TARGET_ENTITY] = unresolved_block_refs+if mode == TurnIntentMode.DOCS_ANSWER:authority.may_update_workflow = Falseauthority.may_run_blocks = Falsediff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.pyindex 6348c9e6f..eb30e21dc 100644--- a/tests/unit/test_copilot_agent_helpers.py+++ b/tests/unit/test_copilot_agent_helpers.py@@ -1165,6 +1165,45 @@ class TestCredentialRefusalReachesAgent:assert cross_ref.search(desc), f"{tool.name} missing refusal cross-reference"+class TestNativeToolSurface:+ @pytest.mark.parametrize("reason", ["workflow_credential_inputs_unbound", "credential_name_unresolved"])+ def test_credential_deferred_draft_removes_update_workflow_tool(self, reason: str) -> None:+ from skyvern.forge.sdk.copilot.request_policy import RequestPolicy++ policy = RequestPolicy(+ testing_intent="skip_test",+ clarification_reason=reason,+ allow_update_workflow=True,+ allow_run_blocks=False,+ allow_missing_credentials_in_draft=True,+ )+ tools = [+ SimpleNamespace(name="update_workflow"),+ SimpleNamespace(name="list_credentials"),+ SimpleNamespace(name="update_and_run_blocks"),+ ]++ filtered = agent_module._native_tools_for_turn(tools, turn_intent=None, request_policy=policy)++ assert [tool.name for tool in filtered] == ["list_credentials", "update_and_run_blocks"]++ def test_non_deferred_policy_keeps_update_workflow_tool(self) -> None:+ from skyvern.forge.sdk.copilot.request_policy import RequestPolicy++ tools = [+ SimpleNamespace(name="update_workflow"),+ SimpleNamespace(name="update_and_run_blocks"),+ ]++ filtered = agent_module._native_tools_for_turn(+ tools,+ turn_intent=None,+ request_policy=RequestPolicy(allow_update_workflow=True, allow_run_blocks=True),+ )++ assert [tool.name for tool in filtered] == ["update_workflow", "update_and_run_blocks"]++class TestRequestPolicyCredentialResolution:@pytest.mark.asyncioasync def test_missing_user_supplied_credential_ids_ask_for_clarification(self, monkeypatch) -> None:@@ -1503,6 +1542,49 @@ class TestRequestPolicyCredentialResolution:assert prior_clarification_follow_up_policy.allow_missing_credentials_in_draftassert prior_clarification_follow_up_policy.clarification_question is None+ handler.response = {+ "testing_intent": "skip_test",+ "credential_input_kind": "credential_name",+ "requires_user_clarification": True,+ "clarification_reason": "credential_name_unresolved",+ }+ deferred_after_question_policy = await build_request_policy(+ user_message="i will do them later",+ workflow_yaml="",+ chat_history=_history(+ ("user", "login using the 'azure_credentials' and get the code from the 'mfa_email'"),+ ("ai", saved_credential_question),+ ),+ global_llm_context="",+ organization_id="org-1",+ handler=handler,+ )+ assert deferred_after_question_policy.user_response_policy == "proceed"+ assert deferred_after_question_policy.testing_intent == "skip_test"+ assert deferred_after_question_policy.clarification_reason == "credential_name_unresolved"+ assert deferred_after_question_policy.allow_update_workflow+ assert not deferred_after_question_policy.allow_run_blocks+ assert deferred_after_question_policy.allow_missing_credentials_in_draft++ stored_credential_site_question = "Which website or login page should I use to look up the stored credential?"+ deferred_after_site_question_policy = await build_request_policy(+ user_message="i will do them later",+ workflow_yaml="",+ chat_history=_history(+ ("user", "login using the 'azure_credentials' and get the code from the 'mfa_email'"),+ ("ai", stored_credential_site_question),+ ),+ global_llm_context="",+ organization_id="org-1",+ handler=handler,+ )+ assert deferred_after_site_question_policy.user_response_policy == "proceed"+ assert deferred_after_site_question_policy.testing_intent == "skip_test"+ assert deferred_after_site_question_policy.clarification_reason == "credential_name_unresolved"+ assert deferred_after_site_question_policy.allow_update_workflow+ assert not deferred_after_site_question_policy.allow_run_blocks+ assert deferred_after_site_question_policy.allow_missing_credentials_in_draft+handler.response = {"testing_intent": "require_test","credential_input_kind": "credential_name",diff --git a/tests/unit/test_copilot_turn_intent.py b/tests/unit/test_copilot_turn_intent.pyindex 6f3ddf9a6..ce4d0b08e 100644--- a/tests/unit/test_copilot_turn_intent.py+++ b/tests/unit/test_copilot_turn_intent.py@@ -15,6 +15,7 @@ from skyvern.forge.sdk.copilot.agent import (from skyvern.forge.sdk.copilot.context import CopilotContextfrom skyvern.forge.sdk.copilot.request_policy import RequestPolicyfrom skyvern.forge.sdk.copilot.turn_intent import (+ UNRESOLVED_BLOCK_REF_TARGET_ENTITY,RequiredContextKey,TurnIntent,TurnIntentAuthority,@@ -217,6 +218,50 @@ def test_build_turn_intent_keeps_explicit_fix_as_edit() -> None:assert intent.mode == TurnIntentMode.EDITassert intent.authority.may_update_workflow is True+ assert intent.target_entities["workflow"] == ["current_workflow"]+++def test_build_turn_intent_records_unresolved_explicit_block_refs() -> None:+ intent = build_turn_intent(+ user_message="WF_trigger_SSO_login worked but update_card is not receiving browser state.",+ workflow_yaml="""+title: Public SSO login cleanup+workflow_definition:+ blocks:+ - block_type: goto_url+ label: navigate_to_SSO+ - block_type: navigation+ label: block_placeholder+""",+ chat_history=[],+ global_llm_context="",+ request_policy=RequestPolicy(),+ )++ assert intent.mode == TurnIntentMode.EDIT+ assert intent.target_entities[UNRESOLVED_BLOCK_REF_TARGET_ENTITY] == [+ "WF_trigger_SSO_login",+ "update_card",+ ]+++def test_build_turn_intent_does_not_treat_snake_case_fields_as_unresolved_block_refs() -> None:+ intent = build_turn_intent(+ user_message="Update the workflow so the last_name field is required.",+ workflow_yaml="""+title: Existing+workflow_definition:+ blocks:+ - block_type: navigation+ label: update_form+""",+ chat_history=[],+ global_llm_context="",+ request_policy=RequestPolicy(),+ )++ assert intent.mode == TurnIntentMode.EDIT+ assert UNRESOLVED_BLOCK_REF_TARGET_ENTITY not in intent.target_entitiesdef test_store_request_policy_attaches_turn_intent_to_context() -> None:diff --git a/tests/unit/test_copilot_turn_intent_tool_gate.py b/tests/unit/test_copilot_turn_intent_tool_gate.pyindex 05bca780e..4700d51a7 100644--- a/tests/unit/test_copilot_turn_intent_tool_gate.py+++ b/tests/unit/test_copilot_turn_intent_tool_gate.py@@ -6,11 +6,17 @@ from unittest.mock import AsyncMock, patchimport pytestfrom skyvern.forge.sdk.copilot.context import CopilotContext+from skyvern.forge.sdk.copilot.request_policy import RequestPolicyfrom skyvern.forge.sdk.copilot.tools import _turn_intent_tool_error, _update_workflow-from skyvern.forge.sdk.copilot.turn_intent import TurnIntent, TurnIntentAuthority, TurnIntentMode+from skyvern.forge.sdk.copilot.turn_intent import (+ UNRESOLVED_BLOCK_REF_TARGET_ENTITY,+ TurnIntent,+ TurnIntentAuthority,+ TurnIntentMode,+)-def _ctx(turn_intent: TurnIntent) -> CopilotContext:+def _ctx(turn_intent: TurnIntent, request_policy: RequestPolicy | None = None) -> CopilotContext:return CopilotContext(organization_id="org-1",workflow_id="wf-1",@@ -19,6 +25,7 @@ def _ctx(turn_intent: TurnIntent) -> CopilotContext:browser_session_id=None,stream=SimpleNamespace(), # type: ignore[arg-type]turn_intent=turn_intent,+ request_policy=request_policy,)@@ -60,15 +67,136 @@ def test_turn_intent_gate_allows_draft_update_without_run_authority() -> None:assert _turn_intent_tool_error(_ctx(intent), "update_workflow") is None-def test_turn_intent_gate_defers_partial_authority_to_request_policy() -> None:+def test_turn_intent_gate_blocks_draft_only_run_tools() -> None:+ intent = TurnIntent(+ mode=TurnIntentMode.DRAFT_ONLY,+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=False),+ )++ error = _turn_intent_tool_error(_ctx(intent), "update_and_run_blocks")++ assert error is not None+ assert "Use `update_workflow` only" in error+ assert "safe_reason_code=turn_intent_run_blocked" in error+++def test_turn_intent_gate_allows_build_update_and_run_authority() -> None:+ intent = TurnIntent(+ mode=TurnIntentMode.BUILD,+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=True),+ )++ assert _turn_intent_tool_error(_ctx(intent), "update_and_run_blocks") is None+++def test_turn_intent_gate_blocks_edit_without_target_context() -> None:+ intent = TurnIntent(+ mode=TurnIntentMode.EDIT,+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=True),+ )++ error = _turn_intent_tool_error(_ctx(intent), "update_workflow")++ assert error is not None+ assert "could not identify a specific workflow edit target" in error+ assert "safe_reason_code=turn_intent_missing_edit_target" in error+++def test_turn_intent_gate_allows_edit_with_target_context() -> None:intent = TurnIntent(- mode=TurnIntentMode.CLARIFY,- authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=False, requires_user_input=True),+ mode=TurnIntentMode.EDIT,+ target_entities={"workflow": ["wfp-1"]},+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=True),)assert _turn_intent_tool_error(_ctx(intent), "update_and_run_blocks") is None+def test_turn_intent_gate_blocks_edit_with_unresolved_label_reference() -> None:+ intent = TurnIntent(+ mode=TurnIntentMode.EDIT,+ target_entities={+ "workflow": ["current_workflow"],+ UNRESOLVED_BLOCK_REF_TARGET_ENTITY: ["WF_trigger_SSO_login", "update_card"],+ },+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=True),+ )+ ctx = _ctx(intent)+ ctx.user_message = "WF_trigger_SSO_login worked but update_card is not receiving browser state."+ ctx.workflow_yaml = """+title: Public SSO login cleanup+workflow_definition:+ parameters:+ - parameter_type: workflow+ key: account_number+ blocks:+ - block_type: goto_url+ label: navigate_to_SSO+ url: https://the-internet.herokuapp.com/login+ - block_type: navigation+ label: block_placeholder+ navigation_goal: Confirm success.+"""++ error = _turn_intent_tool_error(ctx, "update_and_run_blocks")++ assert error is not None+ assert "WF_trigger_SSO_login" in error+ assert "update_card" in error+ assert "navigate_to_SSO" in error+ assert "safe_reason_code=turn_intent_unresolved_edit_target" in error+++def test_turn_intent_gate_does_not_scan_raw_user_message_for_snake_case_refs() -> None:+ intent = TurnIntent(+ mode=TurnIntentMode.EDIT,+ target_entities={"workflow": ["current_workflow"]},+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=True),+ )+ ctx = _ctx(intent)+ ctx.user_message = "Update the workflow so last_name is extracted as a required field."++ assert _turn_intent_tool_error(ctx, "update_and_run_blocks") is None+++def test_turn_intent_gate_allows_edit_with_parameter_reference() -> None:+ intent = TurnIntent(+ mode=TurnIntentMode.EDIT,+ target_entities={"workflow": ["current_workflow"]},+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=True),+ )+ ctx = _ctx(intent)+ ctx.user_message = "Update the current workflow so account_number is used in the search step."+ ctx.workflow_yaml = """+title: Existing+workflow_definition:+ parameters:+ - parameter_type: workflow+ key: account_number+ blocks:+ - block_type: navigation+ label: search_account+ navigation_goal: Search for the account.+"""++ assert _turn_intent_tool_error(ctx, "update_and_run_blocks") is None+++def test_turn_intent_gate_preserves_request_policy_update_skip_path() -> None:+ intent = TurnIntent(+ mode=TurnIntentMode.BUILD,+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=False),+ )+ policy = RequestPolicy(+ allow_update_workflow=True,+ allow_run_blocks=False,+ allow_missing_credentials_in_draft=True,+ clarification_reason="workflow_credential_inputs_unbound",+ )++ assert _turn_intent_tool_error(_ctx(intent, policy), "update_and_run_blocks") is None++@pytest.mark.asyncioasync def test_update_workflow_stops_before_persisting_for_answer_only_intent() -> None:intent = TurnIntent(@@ -86,7 +214,24 @@ async def test_update_workflow_stops_before_persisting_for_answer_only_intent()mock_app.WORKFLOW_SERVICE.update_workflow_definition.assert_not_called()-def test_update_and_run_blocks_reports_run_blocked_priority() -> None:+async def test_request_policy_refusal_wins_even_when_turn_intent_allows_update() -> None:+ intent = TurnIntent(+ mode=TurnIntentMode.BUILD,+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=True),+ )+ ctx = _ctx(intent, RequestPolicy(allow_update_workflow=False, allow_run_blocks=False))++ 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 result["error"].startswith("Request policy blocks workflow updates")+ mock_app.WORKFLOW_SERVICE.update_workflow_definition.assert_not_called()+++def test_update_and_run_blocks_reports_both_blocked_authorities() -> None:intent = TurnIntent(mode=TurnIntentMode.DIAGNOSE,authority=TurnIntentAuthority(may_update_workflow=False, may_run_blocks=False),