Skip to content

Automate browser based workflows with AI

SKY-10566: add LLM-backed TurnIntent classifier (#6388)

Andrew Neilson20691546eb8f
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-turn-intent.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-turn-intent.j2
new file mode 100644
index 000000000..c1c997516
--- /dev/null
+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-turn-intent.j2
@@ -0,0 +1,41 @@
+Classify the latest Workflow Copilot turn. Return only JSON:
+{mode, expected_output, required_context, confidence, target_entities, missing_context_question, reason_codes}.
+
+Allowed modes: {{ mode_values }}.
+Allowed expected_output values: {{ expected_output_values }}.
+Allowed required_context values: {{ required_context_values }}.
+Allowed reason_codes values: {{ reason_code_values }}.
+
+Classify task shape only. RequestPolicy owns credential/raw-secret/testing policy and deterministic code owns authority.
+
+Modes: build=new or blank workflow task; edit=change existing workflow/proposal; diagnose=inspect/debug/continue from run evidence; docs_answer=product/docs/concept answer without mutation; draft_only=workflow change but no validation run; clarify=ambiguous target/change; refuse=unsupported request; unknown=insufficient signal.
+
+Context keys: current_workflow for existing YAML; latest_assistant_proposal/workflow_change for prior draft/proposal edits; latest_run_result for diagnose/continuation; credential_metadata when safe credential metadata is relevant; docs_context for docs_answer; browser_state when current page/session is required.
+
+Target entities: use keys like workflow, run, credential, block, workflow_change, unresolved_block_ref, proposal. Put natural block names or labels in target_entities.block; deterministic code resolves labels. For clear whole-workflow or add-step edits, put a short action in workflow_change. Put unresolved edit targets in unresolved_block_ref and prefer clarify for broad/destructive ambiguous edits. Never include secret values.
+
+Confidence: 0.75-1.0 clear; 0.50-0.74 likely; below 0.50 ambiguous. Unknown is better than guessing.
+
+Rules:
+- Do not override request_policy_summary.
+- A draft/skip-test/no-run request is draft_only unless it only asks to read/debug run results.
+- Bare confirmations and short follow-ups classify from transcript anchors, not keyword matching.
+- Docs questions mentioning block/step names or run modes stay docs_answer unless the user asks to change the workflow.
+- Failure/run-result language is diagnose unless the user explicitly asks to implement a repair.
+
+Latest user message:
+```{{ user_message }}```
+Request policy summary:
+```{{ request_policy_summary }}```
+Earliest retained user turn:
+```{{ earliest_user_turn }}```
+Latest prior user turn:
+```{{ latest_prior_user_turn }}```
+Latest assistant turn:
+```{{ latest_assistant_turn }}```
+Retained recent history:
+```{{ retained_history }}```
+Current workflow YAML:
+```{{ workflow_yaml }}```
+Global context:
+```{{ global_llm_context }}```
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index 64e9a1970..8de94795a 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -100,8 +100,10 @@ from skyvern.forge.sdk.copilot.turn_intent import (
NO_MUTATION_TURN_INTENT_MODES,
RequiredContextKey,
TurnIntent,
+ TurnIntentClassification,
TurnIntentMode,
build_turn_intent,
+ classify_turn_intent,
)
from skyvern.forge.sdk.copilot.turn_outcome import (
apply_repeated_reply_guard,
@@ -328,6 +330,7 @@ def _store_request_policy_on_context(
ctx: CopilotContext,
policy: RequestPolicy,
policy_inputs: RequestPolicyGuardrailInputs,
+ turn_intent_classification: TurnIntentClassification | None = None,
) -> None:
agent_user_message, policy_chat_history_text = _request_policy_agent_inputs(
policy,
@@ -353,6 +356,7 @@ def _store_request_policy_on_context(
workflow_permanent_id=policy_inputs.workflow_permanent_id,
workflow_run_id=policy_inputs.workflow_run_id,
browser_session_id=policy_inputs.browser_session_id,
+ classification=turn_intent_classification,
)
@@ -2342,7 +2346,22 @@ def _build_copilot_input_guardrails(
handler=policy_inputs.handler,
)
if isinstance(ctx, CopilotContext):
- _store_request_policy_on_context(ctx, policy, policy_inputs)
+ turn_intent_classification = None
+ if policy.user_response_policy != "ask_clarification" or policy.raw_secret_handling == "redacted_draft":
+ turn_intent_classification = await classify_turn_intent(
+ user_message=policy_inputs.user_message,
+ workflow_yaml=policy_inputs.workflow_yaml,
+ chat_history=policy_inputs.chat_history_messages,
+ global_llm_context=policy_inputs.global_llm_context,
+ request_policy=policy,
+ handler=policy_inputs.handler,
+ )
+ _store_request_policy_on_context(
+ ctx,
+ policy,
+ policy_inputs,
+ turn_intent_classification=turn_intent_classification,
+ )
blocked = isinstance(policy, RequestPolicy) and policy.user_response_policy == "ask_clarification"
if isinstance(policy, RequestPolicy):
turn_intent = ctx.turn_intent if isinstance(ctx, CopilotContext) else None
diff --git a/skyvern/forge/sdk/copilot/tools.py b/skyvern/forge/sdk/copilot/tools.py
index a6af4b04f..47a208a99 100644
--- a/skyvern/forge/sdk/copilot/tools.py
+++ b/skyvern/forge/sdk/copilot/tools.py
@@ -1803,16 +1803,19 @@ def _request_policy_allows_update_and_skip_run(ctx: AgentContext, tool_name: str
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(
+ if any(
intent.target_entities.get(entity_type)
for entity_type in (
- "workflow",
"block",
"run",
"proposed_workflow",
"latest_assistant_proposal",
+ "proposal",
+ "workflow_change",
)
- )
+ ):
+ return True
+ return any(target != "current_workflow" for target in intent.target_entities.get("workflow", []))
def _turn_intent_tool_error(ctx: AgentContext, tool_name: str) -> CopilotToolBlockerSignal | None:
diff --git a/skyvern/forge/sdk/copilot/turn_intent.py b/skyvern/forge/sdk/copilot/turn_intent.py
index ca69ee976..4edb4e46e 100644
--- a/skyvern/forge/sdk/copilot/turn_intent.py
+++ b/skyvern/forge/sdk/copilot/turn_intent.py
@@ -1,23 +1,40 @@
from __future__ import annotations
-import functools
+import asyncio
import re
+from collections.abc import Mapping
from difflib import SequenceMatcher
from enum import StrEnum
-from typing import Any
+import structlog
import yaml
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
+from skyvern.config import settings
+from skyvern.forge.prompts import prompt_engine
+from skyvern.forge.sdk.api.llm.api_handler import LLMAPIHandler
from skyvern.forge.sdk.copilot.context import StructuredContext
-from skyvern.forge.sdk.copilot.request_policy import RequestPolicy, redact_raw_secrets_for_prompt
+from skyvern.forge.sdk.copilot.output_utils import parse_final_response
+from skyvern.forge.sdk.copilot.request_policy import (
+ RequestPolicy,
+ build_transcript_context,
+ redact_raw_secrets_for_prompt,
+)
+from skyvern.forge.sdk.copilot.tracing_setup import copilot_span
from skyvern.forge.sdk.schemas.workflow_copilot import (
WorkflowCopilotChatHistoryMessage,
WorkflowCopilotChatSender,
)
+from skyvern.utils.strings import escape_code_fences
from skyvern.utils.yaml_loader import safe_load_no_dates
+LOG = structlog.get_logger()
+PROMPT_NAME = "workflow-copilot-turn-intent"
UNRESOLVED_BLOCK_REF_TARGET_ENTITY = "unresolved_block_ref"
+_WORKFLOW_YAML_PROMPT_MAX_CHARS = 4096
+_GLOBAL_CONTEXT_PROMPT_MAX_CHARS = 2048
+_TARGET_ENTITY_MAX_VALUES = 12
+_TARGET_ENTITY_VALUE_MAX_CHARS = 160
class TurnIntentMode(StrEnum):
@@ -31,6 +48,13 @@ class TurnIntentMode(StrEnum):
UNKNOWN = "unknown"
+_LOW_CONFIDENCE_MUTATION_THRESHOLD = 0.5
+_MUTATING_CLASSIFIER_MODES = frozenset((TurnIntentMode.BUILD, TurnIntentMode.EDIT, TurnIntentMode.DRAFT_ONLY))
+_EDIT_SPECIFIC_TARGET_ENTITY_TYPES = frozenset(
+ ("block", "run", "proposed_workflow", "latest_assistant_proposal", "proposal", "workflow_change")
+)
+
+
NO_MUTATION_TURN_INTENT_MODES = frozenset(
{
TurnIntentMode.DOCS_ANSWER,
@@ -80,11 +104,26 @@ class TurnIntentReasonCode(StrEnum):
CHAT_HISTORY_PRESENT = "chat_history_present"
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"
USER_NON_PROGRESS = "user_non_progress"
RECOVERY_FROM_RUN_CONTEXT = "recovery_from_run_context"
+ LLM_CLASSIFIER = "llm_classifier"
+ LOW_CONFIDENCE_CLARIFICATION = "low_confidence_clarification"
+ TARGET_ENTITY_RESOLVED = "target_entity_resolved"
+ MISSING_EDIT_TARGET = "missing_edit_target"
+
+
+_DEFAULT_EXPECTED_OUTPUT_BY_MODE: dict[TurnIntentMode, TurnIntentExpectedOutput] = {
+ TurnIntentMode.BUILD: TurnIntentExpectedOutput.WORKFLOW_DRAFT,
+ TurnIntentMode.EDIT: TurnIntentExpectedOutput.WORKFLOW_UPDATE,
+ TurnIntentMode.DIAGNOSE: TurnIntentExpectedOutput.RUN_RESULT,
+ TurnIntentMode.DOCS_ANSWER: TurnIntentExpectedOutput.EXPLANATION,
+ TurnIntentMode.DRAFT_ONLY: TurnIntentExpectedOutput.WORKFLOW_DRAFT,
+ TurnIntentMode.CLARIFY: TurnIntentExpectedOutput.CLARIFICATION,
+ TurnIntentMode.REFUSE: TurnIntentExpectedOutput.REFUSAL,
+ TurnIntentMode.UNKNOWN: TurnIntentExpectedOutput.EXPLANATION,
+}
class TurnIntentAuthority(BaseModel):
@@ -134,19 +173,12 @@ class TurnIntent(BaseModel):
def _align_expected_output_with_mode(self) -> TurnIntent:
if self.expected_output != TurnIntentExpectedOutput.EXPLANATION:
return self
- expected_output_by_mode = {
- TurnIntentMode.BUILD: TurnIntentExpectedOutput.WORKFLOW_DRAFT,
- TurnIntentMode.EDIT: TurnIntentExpectedOutput.WORKFLOW_UPDATE,
- TurnIntentMode.DRAFT_ONLY: TurnIntentExpectedOutput.WORKFLOW_DRAFT,
- TurnIntentMode.CLARIFY: TurnIntentExpectedOutput.CLARIFICATION,
- TurnIntentMode.REFUSE: TurnIntentExpectedOutput.REFUSAL,
- }
- if mapped_expected_output := expected_output_by_mode.get(self.mode):
+ if mapped_expected_output := _DEFAULT_EXPECTED_OUTPUT_BY_MODE.get(self.mode):
self.expected_output = mapped_expected_output
return self
- def to_trace_data(self) -> dict[str, Any]:
- data: dict[str, Any] = {
+ def to_trace_data(self) -> dict[str, object]:
+ data: dict[str, object] = {
"mode": self.mode.value,
"expected_output": self.expected_output.value,
"required_context": [key.value for key in self.required_context],
@@ -165,58 +197,61 @@ class TurnIntent(BaseModel):
return data
+class TurnIntentClassification(BaseModel):
+ """Typed, model-produced task-shape classification.
+
+ Deterministic code consumes this as an input contract; it still decides
+ authority, context availability, and safety overrides.
+ """
+
+ model_config = ConfigDict(extra="forbid")
+
+ mode: TurnIntentMode = TurnIntentMode.UNKNOWN
+ expected_output: TurnIntentExpectedOutput | None = None
+ required_context: list[RequiredContextKey] = Field(default_factory=list)
+ confidence: float = Field(default=0.0, ge=0.0, le=1.0)
+ target_entities: dict[str, list[str]] = Field(default_factory=dict)
+ missing_context_question: str | None = None
+ reason_codes: list[TurnIntentReasonCode] = Field(default_factory=list)
+
+ @field_validator("required_context", mode="after")
+ @classmethod
+ def _dedupe_required_context(cls, value: list[RequiredContextKey]) -> list[RequiredContextKey]:
+ return list(dict.fromkeys(value))
+
+ @field_validator("reason_codes", mode="after")
+ @classmethod
+ def _dedupe_reason_codes(cls, value: list[TurnIntentReasonCode]) -> list[TurnIntentReasonCode]:
+ return list(dict.fromkeys(value))
+
+ @field_validator("target_entities", mode="after")
+ @classmethod
+ def _dedupe_target_entities(cls, value: dict[str, list[str]]) -> dict[str, list[str]]:
+ return {
+ str(entity_type): list(dict.fromkeys(str(entity).strip() for entity in entities if str(entity).strip()))
+ for entity_type, entities in value.items()
+ if str(entity_type).strip()
+ }
+
+ def expected_output_or_default(self) -> TurnIntentExpectedOutput:
+ return self.expected_output or _DEFAULT_EXPECTED_OUTPUT_BY_MODE[self.mode]
+
+ def to_trace_data(self) -> dict[str, object]:
+ data: dict[str, object] = {
+ "mode": self.mode.value,
+ "expected_output": self.expected_output_or_default().value,
+ "required_context": [key.value for key in self.required_context],
+ "confidence": self.confidence,
+ "reason_codes": [reason.value for reason in self.reason_codes],
+ }
+ if self.target_entities:
+ data["target_entity_types"] = sorted(self.target_entities)
+ if self.missing_context_question:
+ data["has_missing_context_question"] = True
+ return data
+
+
_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")
-# Verbs that also commonly appear as step/block names ("the delete step").
-_EDIT_NOUNY_TERMS = ("add", "insert", "remove", "delete")
-_DIAGNOSE_TERMS = ("debug", "diagnose", "failed", "failure", "error", "result")
-_RUN_CONTEXT_REQUEST_TERMS = ("get_run_results", "workflow_run_id", "run result", "run results")
-# Subset of _DIAGNOSE_TERMS that name unambiguous diagnose intent. "result" is in
-# _DIAGNOSE_TERMS but absent here: a browser task on a no-blocks workflow that
-# mentions "results" is a build request, not a run-result inspection.
-_CLEAR_DIAGNOSE_TERMS = ("debug", "diagnose", "failed", "failure", "error")
-_DOCS_TERMS = (
- "explain",
- "tell me what",
- "how do",
- "how does",
- "what is",
- "what are",
- "what does",
- "why",
- "docs",
- "documentation",
- "where should",
- " vs ",
- " versus ",
- "difference between",
-)
-_LEADING_NOUNY_FAILURE_RE = re.compile(
- rf"^\s*(?:the\s+)?(?:{'|'.join(_EDIT_NOUNY_TERMS)})\s+(?:steps?|blocks?)\s+"
- r"(?:failed|failure|errored?|errors?)\b",
- re.I,
-)
-# Anchored structure requests catch "I need a step..." without treating
-# reference/help questions like "where should a step go?" as mutation.
-_STRUCTURE_REQUEST_RE = re.compile(
- r"^\s*(?:(?:please|pls)\s+)?(?:"
- r"(?:i|we)\s+(?:need|want|would\s+like)\s+"
- r"(?:(?:(?:you\s+to|to)\s+(?:create|make|build|generate|add|insert)\s+)?)"
- r"|(?:can|could|would)\s+you\s+(?:(?:please)\s+)?(?:create|make|build|generate|add|insert)\s+"
- r"|(?:create|make|build|generate|add|insert)\s+"
- r")(?:(?:a|an|another|extra|new|some)\s+)?(?:steps?|blocks?)\b",
- re.I,
-)
-_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:
@@ -232,24 +267,6 @@ 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:
- return _word_boundary_pattern(terms).search(text.lower()) is not None
-
-
-def _is_explicit_run_context_request(user_message: str) -> bool:
- return _contains_any(user_message, _RUN_CONTEXT_REQUEST_TERMS)
-
-
def _workflow_definition_dict(workflow_yaml: str | None) -> dict | None:
if not workflow_yaml:
return None
@@ -263,16 +280,6 @@ def _workflow_definition_dict(workflow_yaml: str | None) -> dict | None:
return workflow_definition if isinstance(workflow_definition, dict) else None
-def _workflow_has_blocks(workflow_yaml: str | None) -> bool:
- workflow_definition = _workflow_definition_dict(workflow_yaml)
- if workflow_definition is None:
- return False
- blocks = workflow_definition.get("blocks")
- if not isinstance(blocks, list):
- return False
- return any(isinstance(block, dict) for block in blocks)
-
-
def _workflow_block_labels(workflow_yaml: str | None) -> set[str]:
workflow_definition = _workflow_definition_dict(workflow_yaml)
if workflow_definition is None:
@@ -290,97 +297,283 @@ def _workflow_block_labels(workflow_yaml: str | None) -> set[str]:
return labels
-def _workflow_parameter_keys(workflow_yaml: str | None) -> set[str]:
- workflow_definition = _workflow_definition_dict(workflow_yaml)
- if workflow_definition is None:
- 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):
+def _normalize_ref_text(value: str) -> str:
+ return re.sub(r"[^a-z0-9]+", " ", value.lower()).strip()
+
+
+def _add_block_label_lookup(
+ lookup: dict[tuple[str, str | None], list[str]],
+ key: tuple[str, str | None],
+ label: str,
+) -> None:
+ lookup.setdefault(key, [])
+ if label not in lookup[key]:
+ lookup[key].append(label)
+
+
+def _workflow_block_label_lookup(workflow_yaml: str | None) -> dict[tuple[str, str | None], list[str]]:
+ lookup: dict[tuple[str, str | None], list[str]] = {}
+ for label in sorted(_workflow_block_labels(workflow_yaml)):
+ normalized = _normalize_ref_text(label)
+ if not normalized:
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:
+ _add_block_label_lookup(lookup, (normalized, None), label)
+ for kind in ("block", "step"):
+ suffix = f" {kind}"
+ if normalized.endswith(suffix):
+ alias = normalized[: -len(suffix)].strip()
+ if alias:
+ _add_block_label_lookup(lookup, (alias, kind), label)
+ return lookup
+
+
+def _lookup_block_label(
+ lookup: dict[tuple[str, str | None], list[str]],
+ normalized_ref: str,
+ *,
+ kind: str | None = None,
+) -> str | None:
+ keys: list[tuple[str, str | None]] = []
+ if kind:
+ keys.append((normalized_ref, kind))
+ keys.append((normalized_ref, None))
+ for key in keys:
+ labels = lookup.get(key, [])
+ if len(labels) == 1:
+ return labels[0]
+ return None
+
+
+def _merge_target_entities(target_entities: dict[str, list[str]], additions: dict[str, list[str]]) -> None:
+ for entity_type, entities in additions.items():
+ target_entities[entity_type] = list(dict.fromkeys([*target_entities.get(entity_type, []), *entities]))
+
+
+def _clean_string_list(raw: object, *, max_values: int = _TARGET_ENTITY_MAX_VALUES) -> list[str]:
+ if not isinstance(raw, list):
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:
+ values: list[str] = []
+ for item in raw:
+ value = str(item).strip()[:_TARGET_ENTITY_VALUE_MAX_CHARS]
+ if value:
+ values.append(value)
+ if len(values) >= max_values:
+ break
+ return list(dict.fromkeys(values))
+
+
+def _coerce_confidence(value: object) -> float:
+ if isinstance(value, bool) or not isinstance(value, (float, int, str)):
+ return 0.0
+ try:
+ confidence = float(value)
+ except ValueError:
+ return 0.0
+ return min(1.0, max(0.0, confidence))
+
+
+def _coerce_mode(value: object) -> TurnIntentMode | None:
+ try:
+ return TurnIntentMode(str(value))
+ except ValueError:
+ return None
+
+
+def _coerce_expected_output(value: object) -> TurnIntentExpectedOutput | None:
+ if value is None:
+ return None
+ try:
+ return TurnIntentExpectedOutput(str(value))
+ except ValueError:
+ return None
+
+
+def _coerce_required_context(raw: object) -> list[RequiredContextKey]:
+ values = _clean_string_list(raw, max_values=len(RequiredContextKey))
+ required_context: list[RequiredContextKey] = []
+ for value in values:
+ try:
+ required_context.append(RequiredContextKey(value))
+ except ValueError:
continue
- unresolved.append(ref)
- return unresolved
+ return list(dict.fromkeys(required_context))
-def _mutation_mode(has_workflow: bool) -> tuple[TurnIntentMode, TurnIntentExpectedOutput]:
- if has_workflow:
- return TurnIntentMode.EDIT, TurnIntentExpectedOutput.WORKFLOW_UPDATE
- return TurnIntentMode.BUILD, TurnIntentExpectedOutput.WORKFLOW_DRAFT
+def _coerce_reason_codes(raw: object) -> list[TurnIntentReasonCode]:
+ values = _clean_string_list(raw, max_values=len(TurnIntentReasonCode))
+ reason_codes: list[TurnIntentReasonCode] = []
+ for value in values:
+ try:
+ reason_codes.append(TurnIntentReasonCode(value))
+ except ValueError:
+ continue
+ return list(dict.fromkeys(reason_codes))
-def _mode_from_keywords(
- user_message: str,
+def _coerce_target_entities(raw: object) -> dict[str, list[str]]:
+ if not isinstance(raw, Mapping):
+ return {}
+ entities: dict[str, list[str]] = {}
+ for entity_type, values in raw.items():
+ key = str(entity_type).strip()
+ if not key:
+ continue
+ cleaned_values = _clean_string_list(values)
+ if cleaned_values:
+ entities[key] = cleaned_values
+ return entities
+
+
+def _decode_classifier_response(raw: object) -> dict[str, object] | None:
+ if isinstance(raw, str):
+ raw = parse_final_response(raw)
+ if not isinstance(raw, Mapping):
+ return None
+ return {str(key): value for key, value in raw.items()}
+
+
+def _turn_intent_classification_from_raw(raw: object) -> TurnIntentClassification | None:
+ payload = _decode_classifier_response(raw)
+ if payload is None:
+ return None
+ mode = _coerce_mode(payload.get("mode"))
+ if mode is None:
+ return None
+ missing_context_question = payload.get("missing_context_question")
+ return TurnIntentClassification(
+ mode=mode,
+ expected_output=_coerce_expected_output(payload.get("expected_output")),
+ required_context=_coerce_required_context(payload.get("required_context")),
+ confidence=_coerce_confidence(payload.get("confidence")),
+ target_entities=_coerce_target_entities(payload.get("target_entities")),
+ missing_context_question=missing_context_question.strip()
+ if isinstance(missing_context_question, str) and missing_context_question.strip()
+ else None,
+ reason_codes=_coerce_reason_codes(payload.get("reason_codes")),
+ )
+
+
+def _block_ref_candidates(value: str) -> list[tuple[str, str | None]]:
+ normalized = _normalize_ref_text(value)
+ if not normalized:
+ return []
+ candidates: list[tuple[str, str | None]] = []
+ for article in ("the ", "a ", "an "):
+ if normalized.startswith(article):
+ normalized = normalized[len(article) :].strip()
+ break
+ for kind in ("block", "step"):
+ suffix = f" {kind}"
+ if normalized.endswith(suffix):
+ alias = normalized[: -len(suffix)].strip()
+ if alias:
+ candidates.append((alias, kind))
+ candidates.append((normalized, None))
+ return list(dict.fromkeys(candidates))
+
+
+def _resolve_classified_block_targets(values: list[str], workflow_yaml: str | None) -> tuple[list[str], list[str]]:
+ lookup = _workflow_block_label_lookup(workflow_yaml)
+ resolved: list[str] = []
+ unresolved: list[str] = []
+ for value in values:
+ label = None
+ for normalized_ref, kind in _block_ref_candidates(value):
+ label = _lookup_block_label(lookup, normalized_ref, kind=kind)
+ if label:
+ break
+ if label:
+ resolved.append(label)
+ else:
+ unresolved.append(value)
+ return list(dict.fromkeys(resolved)), list(dict.fromkeys(unresolved))
+
+
+def _normalize_classified_target_entities(
+ target_entities: dict[str, list[str]],
+ workflow_yaml: str | None,
+) -> dict[str, list[str]]:
+ normalized_entities = {key: list(values) for key, values in target_entities.items() if values}
+ block_values = normalized_entities.pop("block", [])
+ if block_values:
+ resolved, unresolved = _resolve_classified_block_targets(block_values, workflow_yaml)
+ if resolved:
+ _merge_target_entities(normalized_entities, {"block": resolved})
+ if unresolved:
+ _merge_target_entities(normalized_entities, {UNRESOLVED_BLOCK_REF_TARGET_ENTITY: unresolved})
+ return normalized_entities
+
+
+def _has_specific_edit_target(target_entities: dict[str, list[str]]) -> bool:
+ if any(target_entities.get(entity_type) for entity_type in _EDIT_SPECIFIC_TARGET_ENTITY_TYPES):
+ return True
+ return any(target != "current_workflow" for target in target_entities.get("workflow", []))
+
+
+async def classify_turn_intent(
*,
- has_workflow: bool,
- has_workflow_blocks: bool,
- has_prior_run_signal: bool,
-) -> tuple[TurnIntentMode, TurnIntentExpectedOutput] | None:
- if _LEADING_NOUNY_FAILURE_RE.search(user_message or ""):
- return TurnIntentMode.DIAGNOSE, TurnIntentExpectedOutput.RUN_RESULT
- if has_workflow and _contains_any(user_message, _EDIT_TERMS):
- return TurnIntentMode.EDIT, TurnIntentExpectedOutput.WORKFLOW_UPDATE
- # A browser-task verb on a saved workflow with no buildable blocks is a new
- # build request even when the message mentions "results"; suppress only when
- # the user names diagnosis or docs intent, or a prior run is attached. The
- # no-yaml case still falls through to the trailing browser-task fallback.
- if (
- has_workflow
- and not has_workflow_blocks
- and not has_prior_run_signal
- and _contains_any(user_message, _NEW_BROWSER_TASK_TERMS)
- and not _contains_any(user_message, _CLEAR_DIAGNOSE_TERMS)
- and not _contains_any(user_message, _DOCS_TERMS)
- ):
- return TurnIntentMode.BUILD, TurnIntentExpectedOutput.WORKFLOW_DRAFT
- if _contains_any(user_message, _DIAGNOSE_TERMS):
- return TurnIntentMode.DIAGNOSE, TurnIntentExpectedOutput.RUN_RESULT
- if _contains_any(user_message, _DOCS_TERMS):
- return TurnIntentMode.DOCS_ANSWER, TurnIntentExpectedOutput.EXPLANATION
- if _STRUCTURE_REQUEST_RE.search(user_message or ""):
- return _mutation_mode(has_workflow)
- if _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_DRAFT
- return None
+ user_message: str,
+ workflow_yaml: str,
+ chat_history: list[WorkflowCopilotChatHistoryMessage],
+ global_llm_context: str,
+ request_policy: RequestPolicy,
+ handler: LLMAPIHandler | None,
+) -> TurnIntentClassification | None:
+ if not isinstance(user_message, str) or not user_message.strip():
+ return None
+ if handler is None:
+ LOG.info("turn-intent classifier has no LLM handler available")
+ return None
+
+ safe_user_message = redact_raw_secrets_for_prompt(user_message)
+ transcript = build_transcript_context(chat_history, safe_user_message)
+ try:
+ prompt = prompt_engine.load_prompt(
+ template=PROMPT_NAME,
+ mode_values=", ".join(mode.value for mode in TurnIntentMode),
+ expected_output_values=", ".join(output.value for output in TurnIntentExpectedOutput),
+ required_context_values=", ".join(key.value for key in RequiredContextKey),
+ reason_code_values=", ".join(reason.value for reason in TurnIntentReasonCode),
+ user_message=escape_code_fences(safe_user_message),
+ request_policy_summary=escape_code_fences(request_policy.prompt_summary()),
+ workflow_yaml=escape_code_fences(
+ redact_raw_secrets_for_prompt(workflow_yaml)[:_WORKFLOW_YAML_PROMPT_MAX_CHARS]
+ ),
+ earliest_user_turn=transcript.earliest_user_turn,
+ latest_prior_user_turn=transcript.latest_prior_user_turn,
+ latest_assistant_turn=transcript.latest_assistant_turn,
+ retained_history=transcript.retained_history,
+ global_llm_context=escape_code_fences(
+ redact_raw_secrets_for_prompt(global_llm_context)[:_GLOBAL_CONTEXT_PROMPT_MAX_CHARS]
+ ),
+ )
+ except Exception as exc:
+ LOG.warning("turn-intent classifier prompt render failed", error=str(exc))
+ return None
+
+ try:
+ raw = await asyncio.wait_for(
+ handler(prompt=prompt, prompt_name=PROMPT_NAME),
+ timeout=settings.COPILOT_FEASIBILITY_GATE_TIMEOUT_SECONDS,
+ )
+ except asyncio.TimeoutError:
+ LOG.warning(
+ "turn-intent classifier timed out",
+ timeout=settings.COPILOT_FEASIBILITY_GATE_TIMEOUT_SECONDS,
+ )
+ return None
+ except Exception as exc:
+ LOG.warning("turn-intent classifier failed", error=str(exc))
+ return None
+
+ classification = _turn_intent_classification_from_raw(raw)
+ if classification is None:
+ LOG.warning("turn-intent classifier returned malformed output")
+ return None
+
+ with copilot_span("turn_intent_classifier", data=classification.to_trace_data()):
+ LOG.info("turn-intent classifier decision", **classification.to_trace_data())
+ return classification
_PRIOR_RUN_OUTPUT_PREFIX = " output:"
@@ -414,38 +607,6 @@ def _has_structured_prior_run_signal(global_llm_context: str) -> bool:
return any(isinstance(entry, str) and _decision_records_prior_run(entry) for entry in structured.decisions_made)
-_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
-
-
_NON_PROGRESS_MARKER_RE = re.compile(
r"\b(?:"
r"i\s+can'?t\s+see\s+(?:it|that|them|those|the)"
@@ -505,33 +666,6 @@ def _user_signals_non_progress(user_message: str, chat_history: list[WorkflowCop
return SequenceMatcher(None, current_norm, prior_norm).ratio() >= _NON_PROGRESS_RESTATE_THRESHOLD
-def _carryover_mode_from_prior_turn(
- chat_history: list[WorkflowCopilotChatHistoryMessage],
- *,
- has_workflow: bool,
- has_workflow_blocks: bool,
- has_prior_run_signal: 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,
- has_workflow_blocks=has_workflow_blocks,
- has_prior_run_signal=has_prior_run_signal,
- ):
- return carried
- return None
-
-
def build_turn_intent(
*,
user_message: str,
@@ -543,9 +677,9 @@ def build_turn_intent(
workflow_permanent_id: str | None = None,
workflow_run_id: str | None = None,
browser_session_id: str | None = None,
+ classification: TurnIntentClassification | None = None,
) -> TurnIntent:
has_workflow = bool((workflow_yaml or "").strip())
- has_workflow_blocks = _workflow_has_blocks(workflow_yaml)
has_prior_context = bool((global_llm_context or "").strip())
target_entities: dict[str, list[str]] = {}
required_context: list[RequiredContextKey] = []
@@ -600,45 +734,53 @@ def build_turn_intent(
confidence = 0.8
missing_context_question = request_policy.clarification_question
reason_codes.append(TurnIntentReasonCode.REQUEST_POLICY_CLARIFICATION)
- elif has_prior_run_signal and _is_explicit_run_context_request(user_message):
- mode = TurnIntentMode.DIAGNOSE
- expected_output = TurnIntentExpectedOutput.RUN_RESULT
- confidence = 0.45
- reason_codes.append(TurnIntentReasonCode.KEYWORD_HEURISTIC)
+ elif classification is not None and classification.mode != TurnIntentMode.UNKNOWN:
+ mode = classification.mode
+ expected_output = classification.expected_output_or_default()
+ confidence = classification.confidence
+ missing_context_question = classification.missing_context_question
+ required_context.extend(classification.required_context)
+ _merge_target_entities(
+ target_entities,
+ _normalize_classified_target_entities(classification.target_entities, workflow_yaml),
+ )
+ reason_codes.append(TurnIntentReasonCode.LLM_CLASSIFIER)
+ reason_codes.extend(classification.reason_codes)
elif request_policy.testing_intent == "skip_test":
mode = TurnIntentMode.DRAFT_ONLY
expected_output = TurnIntentExpectedOutput.WORKFLOW_DRAFT
confidence = 0.6
reason_codes.append(TurnIntentReasonCode.TESTING_INTENT_SKIP_TEST)
- elif keyword_mode := _mode_from_keywords(
- user_message,
- has_workflow=has_workflow,
- has_workflow_blocks=has_workflow_blocks,
- has_prior_run_signal=has_prior_run_signal,
- ):
- mode, expected_output = keyword_mode
- confidence = 0.35
- reason_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,
- has_workflow_blocks=has_workflow_blocks,
- has_prior_run_signal=has_prior_run_signal,
+ elif classification is not None:
+ confidence = classification.confidence
+ required_context.extend(classification.required_context)
+ _merge_target_entities(
+ target_entities,
+ _normalize_classified_target_entities(classification.target_entities, workflow_yaml),
)
+ reason_codes.append(TurnIntentReasonCode.LLM_CLASSIFIER)
+ reason_codes.extend(classification.reason_codes)
+
+ if (
+ classification is not None
+ and mode in _MUTATING_CLASSIFIER_MODES
+ and confidence < _LOW_CONFIDENCE_MUTATION_THRESHOLD
):
- mode, expected_output = carried_mode
- confidence = 0.3
- reason_codes.append(TurnIntentReasonCode.CONFIRMATION_CARRYOVER)
+ mode = TurnIntentMode.CLARIFY
+ expected_output = TurnIntentExpectedOutput.CLARIFICATION
+ missing_context_question = missing_context_question or "What workflow should I build or change?"
+ reason_codes.append(TurnIntentReasonCode.LOW_CONFIDENCE_CLARIFICATION)
+
+ if mode == TurnIntentMode.EDIT and not _has_specific_edit_target(target_entities):
+ mode = TurnIntentMode.CLARIFY
+ expected_output = TurnIntentExpectedOutput.CLARIFICATION
+ confidence = min(confidence, _LOW_CONFIDENCE_MUTATION_THRESHOLD - 0.01)
+ missing_context_question = missing_context_question or "What change should I make to this workflow?"
+ reason_codes.append(TurnIntentReasonCode.MISSING_EDIT_TARGET)
if _user_signals_non_progress(user_message, chat_history):
reason_codes.append(TurnIntentReasonCode.USER_NON_PROGRESS)
- 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.UNKNOWN and has_prior_run_signal:
mode = TurnIntentMode.DIAGNOSE
expected_output = TurnIntentExpectedOutput.RUN_RESULT
@@ -648,6 +790,16 @@ def build_turn_intent(
authority.may_update_workflow = False
authority.may_run_blocks = False
required_context.append(RequiredContextKey.DOCS_CONTEXT)
+ elif mode == TurnIntentMode.DRAFT_ONLY:
+ authority.may_run_blocks = False
+ elif mode == TurnIntentMode.CLARIFY:
+ authority.may_update_workflow = False
+ authority.may_run_blocks = False
+ authority.requires_user_input = True
+ elif mode == TurnIntentMode.REFUSE:
+ authority.may_update_workflow = False
+ authority.may_run_blocks = False
+ authority.requires_user_input = True
elif mode == TurnIntentMode.DIAGNOSE and RequiredContextKey.LATEST_RUN_RESULT not in required_context:
authority.may_update_workflow = False
authority.may_run_blocks = False
diff --git a/tests/unit/test_copilot_turn_intent.py b/tests/unit/test_copilot_turn_intent.py
index a018cd6f1..7d9b96090 100644
--- a/tests/unit/test_copilot_turn_intent.py
+++ b/tests/unit/test_copilot_turn_intent.py
@@ -16,14 +16,19 @@ from skyvern.forge.sdk.copilot.agent import (
from skyvern.forge.sdk.copilot.context import CopilotContext, StructuredContext
from skyvern.forge.sdk.copilot.request_policy import RequestPolicy
from skyvern.forge.sdk.copilot.turn_intent import (
+ PROMPT_NAME,
UNRESOLVED_BLOCK_REF_TARGET_ENTITY,
RequiredContextKey,
TurnIntent,
TurnIntentAuthority,
+ TurnIntentClassification,
+ TurnIntentExpectedOutput,
TurnIntentMode,
TurnIntentReasonCode,
_has_structured_prior_run_signal,
+ _turn_intent_classification_from_raw,
build_turn_intent,
+ classify_turn_intent,
)
from skyvern.forge.sdk.schemas.workflow_copilot import (
WorkflowCopilotChatHistoryMessage,
@@ -47,6 +52,27 @@ def _ai_message(content: str) -> WorkflowCopilotChatHistoryMessage:
)
+def _classification(
+ mode: TurnIntentMode,
+ *,
+ expected_output: TurnIntentExpectedOutput | None = None,
+ required_context: list[RequiredContextKey] | None = None,
+ confidence: float = 0.8,
+ target_entities: dict[str, list[str]] | None = None,
+ missing_context_question: str | None = None,
+ reason_codes: list[TurnIntentReasonCode] | None = None,
+) -> TurnIntentClassification:
+ return TurnIntentClassification(
+ mode=mode,
+ expected_output=expected_output,
+ required_context=required_context or [],
+ confidence=confidence,
+ target_entities=target_entities or {},
+ missing_context_question=missing_context_question,
+ reason_codes=reason_codes or [],
+ )
+
+
def test_turn_intent_defaults_to_unknown_shadow_contract() -> None:
intent = TurnIntent()
@@ -94,397 +120,379 @@ def test_turn_intent_trace_data_omits_raw_goal_and_target_values() -> None:
assert "cred_sensitive" not in repr(trace_data)
-def test_build_turn_intent_uses_request_policy_clarification_without_changing_policy() -> None:
- policy = RequestPolicy(
- user_response_policy="ask_clarification",
- allow_update_workflow=False,
- allow_run_blocks=False,
- clarification_question="Which page should I target?",
- clarification_reason="missing_target_context",
- )
-
- intent = build_turn_intent(
- user_message="Update this workflow",
- workflow_yaml="blocks: []",
- chat_history=[_user_message("Build a workflow")],
- global_llm_context="",
- request_policy=policy,
- )
-
- assert intent.mode == TurnIntentMode.CLARIFY
- assert intent.authority.requires_user_input is True
- assert intent.authority.may_update_workflow is False
- assert intent.authority.may_run_blocks is False
- assert intent.missing_context_question == "Which page should I target?"
- assert RequiredContextKey.CURRENT_WORKFLOW in intent.required_context
- assert 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.",
- )
-
+def test_build_turn_intent_does_not_keyword_classify_without_llm_result() -> None:
intent = build_turn_intent(
- user_message="Use this password: hunter2 to sign in.",
+ user_message="Build a workflow that opens https://example.test and downloads invoices.",
workflow_yaml="",
chat_history=[],
global_llm_context="",
- request_policy=policy,
+ request_policy=RequestPolicy(),
)
- 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
+ assert intent.mode == TurnIntentMode.UNKNOWN
+ assert TurnIntentReasonCode.LLM_CLASSIFIER not in intent.reason_codes
-def test_build_turn_intent_redacts_user_goal() -> None:
+def test_build_turn_intent_applies_llm_build_classification() -> None:
intent = build_turn_intent(
- user_message="Use password: hunter2 and build the workflow",
+ user_message="Create a workflow from the page I have open.",
workflow_yaml="",
chat_history=[],
global_llm_context="",
request_policy=RequestPolicy(),
+ browser_session_id="pbs_123",
+ classification=_classification(
+ TurnIntentMode.BUILD,
+ required_context=[RequiredContextKey.BROWSER_STATE],
+ confidence=0.84,
+ ),
)
- assert "hunter2" not in intent.user_goal
- assert "[REDACTED_SECRET]" in intent.user_goal
+ assert intent.mode == TurnIntentMode.BUILD
+ assert intent.expected_output == TurnIntentExpectedOutput.WORKFLOW_DRAFT
+ assert intent.authority.may_update_workflow is True
+ assert intent.authority.may_run_blocks is True
+ assert RequiredContextKey.BROWSER_STATE in intent.required_context
+ assert TurnIntentReasonCode.BROWSER_CONTEXT_PRESENT in intent.reason_codes
+ assert TurnIntentReasonCode.LLM_CLASSIFIER in intent.reason_codes
-def test_build_turn_intent_marks_docs_context_for_docs_answer() -> None:
+def test_build_turn_intent_applies_docs_classification_without_mutation() -> None:
intent = build_turn_intent(
- user_message="Why does a loop need a condition?",
- workflow_yaml="",
+ user_message="What does run with code mean?",
+ workflow_yaml="title: Existing\nworkflow_definition:\n blocks: []\n",
chat_history=[],
global_llm_context="",
request_policy=RequestPolicy(),
+ classification=_classification(TurnIntentMode.DOCS_ANSWER),
)
assert intent.mode == TurnIntentMode.DOCS_ANSWER
assert intent.authority.may_update_workflow is False
assert intent.authority.may_run_blocks is False
+ assert RequiredContextKey.CURRENT_WORKFLOW in intent.required_context
assert RequiredContextKey.DOCS_CONTEXT in intent.required_context
-def test_build_turn_intent_marks_platform_comparison_as_docs_answer() -> None:
+def test_build_turn_intent_applies_diagnose_classification_and_read_authority() -> None:
intent = build_turn_intent(
- user_message="I meant run with code vs run with agent",
- workflow_yaml="blocks: []",
+ user_message="Tell me why the run failed.",
+ workflow_yaml="title: Existing\nworkflow_definition:\n blocks: []\n",
chat_history=[],
global_llm_context="",
- request_policy=RequestPolicy(),
+ request_policy=RequestPolicy(allow_update_workflow=True, allow_run_blocks=True),
+ workflow_run_id="wr_123",
+ classification=_classification(TurnIntentMode.DIAGNOSE),
)
- assert intent.mode == TurnIntentMode.DOCS_ANSWER
+ assert intent.mode == TurnIntentMode.DIAGNOSE
+ assert intent.expected_output == TurnIntentExpectedOutput.RUN_RESULT
+ assert intent.authority.may_read_run_context is True
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 RequiredContextKey.LATEST_RUN_RESULT in intent.required_context
+ assert intent.target_entities["run"] == ["wr_123"]
-def test_build_turn_intent_marks_blank_workflow_browser_task_as_build() -> None:
+def test_build_turn_intent_applies_draft_only_classification_without_run_authority() -> None:
intent = build_turn_intent(
- user_message="Go to https://en.wikipedia.org and search for Bauhaus.",
+ user_message="Draft only; no validation run.",
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
-
-
-_BLANK_SAVED_WORKFLOW_YAML = "title: Saved blank workflow\nworkflow_definition:\n blocks: []\n parameters: []\n"
-
-
-def test_build_turn_intent_marks_blank_saved_workflow_browser_task_with_results_word_as_build() -> None:
- intent = build_turn_intent(
- user_message=(
- "Go to https://example.test/registry, search for ABC-1234, expand the entry, "
- "and report the credential type and expiration date from the results."
- ),
- workflow_yaml=_BLANK_SAVED_WORKFLOW_YAML,
- chat_history=[],
- global_llm_context="",
- request_policy=RequestPolicy(),
+ request_policy=RequestPolicy(allow_update_workflow=True, allow_run_blocks=True),
+ classification=_classification(TurnIntentMode.DRAFT_ONLY),
)
- assert intent.mode == TurnIntentMode.BUILD
+ assert intent.mode == TurnIntentMode.DRAFT_ONLY
assert intent.authority.may_update_workflow is True
- assert intent.authority.may_run_blocks is True
- assert RequiredContextKey.LATEST_RUN_RESULT not in intent.required_context
+ assert intent.authority.may_run_blocks is False
-def test_build_turn_intent_marks_create_workflow_with_browser_task_and_results_as_build() -> None:
+def test_build_turn_intent_skip_test_policy_is_fallback_when_classifier_missing() -> None:
intent = build_turn_intent(
- user_message=("Create a workflow that opens https://example.test and reports the results."),
- workflow_yaml=_BLANK_SAVED_WORKFLOW_YAML,
+ user_message="Draft only; no validation run.",
+ workflow_yaml="",
chat_history=[],
global_llm_context="",
- request_policy=RequestPolicy(),
+ request_policy=RequestPolicy(testing_intent="skip_test", allow_update_workflow=True, allow_run_blocks=False),
)
- assert intent.mode == TurnIntentMode.BUILD
- assert intent.authority.may_update_workflow is True
- assert intent.authority.may_run_blocks is True
- assert RequiredContextKey.LATEST_RUN_RESULT not in intent.required_context
+ assert intent.mode == TurnIntentMode.DRAFT_ONLY
+ assert intent.authority.may_run_blocks is False
+ assert TurnIntentReasonCode.TESTING_INTENT_SKIP_TEST in intent.reason_codes
-def test_build_turn_intent_keeps_clear_diagnose_on_blank_saved_workflow_with_browser_task_verb() -> None:
+def test_build_turn_intent_llm_diagnose_outranks_skip_test_policy() -> None:
intent = build_turn_intent(
- user_message="Open the failed page and tell me what went wrong.",
- workflow_yaml=_BLANK_SAVED_WORKFLOW_YAML,
+ user_message="Call get_run_results with workflow_run_id wr_123. Do not run blocks.",
+ workflow_yaml="title: Existing\nworkflow_definition:\n blocks: []\n",
chat_history=[],
global_llm_context="",
- request_policy=RequestPolicy(),
+ request_policy=RequestPolicy(testing_intent="skip_test", allow_update_workflow=True, allow_run_blocks=False),
+ workflow_run_id="wr_123",
+ classification=_classification(TurnIntentMode.DIAGNOSE),
)
assert intent.mode == TurnIntentMode.DIAGNOSE
+ assert intent.authority.may_read_run_context is True
+ assert intent.authority.may_update_workflow is False
+ assert TurnIntentReasonCode.TESTING_INTENT_SKIP_TEST not in intent.reason_codes
-def test_build_turn_intent_keeps_run_result_diagnose_with_build_keyword_on_existing_workflow() -> None:
- existing_workflow_yaml = (
- "title: Existing\nworkflow_definition:\n blocks:\n - block_type: navigation\n label: nav_to_site\n"
+def test_build_turn_intent_uses_request_policy_clarification_over_llm_classification() -> None:
+ policy = RequestPolicy(
+ user_response_policy="ask_clarification",
+ allow_update_workflow=False,
+ allow_run_blocks=False,
+ clarification_question="Which page should I target?",
+ clarification_reason="missing_target_context",
)
+
intent = build_turn_intent(
- user_message="Generate a report from the last result.",
- workflow_yaml=existing_workflow_yaml,
- chat_history=[],
+ user_message="Update this workflow",
+ workflow_yaml="blocks: []",
+ chat_history=[_user_message("Build a workflow")],
global_llm_context="",
- request_policy=RequestPolicy(),
+ request_policy=policy,
+ classification=_classification(TurnIntentMode.EDIT),
)
- assert intent.mode == TurnIntentMode.DIAGNOSE
+ assert intent.mode == TurnIntentMode.CLARIFY
+ assert intent.authority.requires_user_input is True
+ assert intent.authority.may_update_workflow is False
+ assert intent.authority.may_run_blocks is False
+ assert intent.missing_context_question == "Which page should I target?"
+ assert RequiredContextKey.CURRENT_WORKFLOW in intent.required_context
+ assert TurnIntentReasonCode.REQUEST_POLICY_CLARIFICATION in intent.reason_codes
+ assert TurnIntentReasonCode.LLM_CLASSIFIER not in intent.reason_codes
-def test_build_turn_intent_keeps_run_result_diagnose_when_no_browser_task_verb() -> None:
- intent = build_turn_intent(
- user_message="What is the result of the last run?",
- workflow_yaml=_BLANK_SAVED_WORKFLOW_YAML,
- chat_history=[],
- global_llm_context="",
- request_policy=RequestPolicy(),
+def test_build_turn_intent_routes_raw_secret_to_refuse_over_llm_classification() -> 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.",
)
- assert intent.mode == TurnIntentMode.DIAGNOSE
-
-
-def test_build_turn_intent_keeps_diagnose_when_run_id_attached_on_blank_saved_workflow() -> None:
intent = build_turn_intent(
- user_message="Open the result.",
- workflow_yaml=_BLANK_SAVED_WORKFLOW_YAML,
+ user_message="Use this password: hunter2 to sign in.",
+ workflow_yaml="",
chat_history=[],
global_llm_context="",
- request_policy=RequestPolicy(),
- workflow_run_id="wr_abc123",
+ request_policy=policy,
+ classification=_classification(TurnIntentMode.BUILD),
)
- assert intent.mode == TurnIntentMode.DIAGNOSE
- assert RequiredContextKey.LATEST_RUN_RESULT in intent.required_context
+ 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
+ assert TurnIntentReasonCode.LLM_CLASSIFIER not in intent.reason_codes
-def test_build_turn_intent_routes_docs_question_with_browser_task_verb_on_blank_saved_workflow() -> None:
+def test_build_turn_intent_redacts_user_goal() -> None:
intent = build_turn_intent(
- user_message="How do I navigate to my workflow?",
- workflow_yaml=_BLANK_SAVED_WORKFLOW_YAML,
+ user_message="Use password: hunter2 and build the workflow",
+ workflow_yaml="",
chat_history=[],
global_llm_context="",
request_policy=RequestPolicy(),
+ classification=_classification(TurnIntentMode.BUILD),
)
- assert intent.mode == TurnIntentMode.DOCS_ANSWER
- assert intent.authority.may_update_workflow is False
- assert intent.authority.may_run_blocks is False
+ assert "hunter2" not in intent.user_goal
+ assert "[REDACTED_SECRET]" in intent.user_goal
-def test_build_turn_intent_marks_run_context_for_diagnose() -> None:
[email protected]("mode", [TurnIntentMode.BUILD, TurnIntentMode.EDIT, TurnIntentMode.DRAFT_ONLY])
+def test_build_turn_intent_low_confidence_mutating_classification_clarifies(mode: TurnIntentMode) -> None:
intent = build_turn_intent(
- user_message="Diagnose the failed run",
- workflow_yaml="blocks: []",
+ user_message="Update it.",
+ workflow_yaml="title: Existing\nworkflow_definition:\n blocks: []\n",
chat_history=[],
global_llm_context="",
request_policy=RequestPolicy(),
+ classification=_classification(mode, confidence=0.35, target_entities={"workflow_change": ["update_it"]}),
)
- assert intent.mode == TurnIntentMode.DIAGNOSE
+ assert intent.mode == TurnIntentMode.CLARIFY
assert intent.authority.may_update_workflow is False
assert intent.authority.may_run_blocks is False
- assert RequiredContextKey.LATEST_RUN_RESULT in intent.required_context
+ assert TurnIntentReasonCode.LOW_CONFIDENCE_CLARIFICATION in intent.reason_codes
-def test_build_turn_intent_does_not_require_unassembled_browser_state() -> None:
+def test_build_turn_intent_targetless_edit_classification_clarifies() -> None:
intent = build_turn_intent(
- user_message="Continue in the open browser",
- workflow_yaml="workflow_definition:\n blocks: []",
+ user_message="Update it.",
+ workflow_yaml="title: Existing\nworkflow_definition:\n blocks: []\n",
chat_history=[],
global_llm_context="",
request_policy=RequestPolicy(),
- browser_session_id="pbs_123",
+ classification=_classification(TurnIntentMode.EDIT, confidence=0.82),
)
- assert RequiredContextKey.BROWSER_STATE not in intent.required_context
- assert TurnIntentReasonCode.BROWSER_CONTEXT_PRESENT in intent.reason_codes
+ assert intent.mode == TurnIntentMode.CLARIFY
+ assert intent.authority.may_update_workflow is False
+ assert intent.authority.may_run_blocks is False
+ assert intent.missing_context_question == "What change should I make to this workflow?"
+ assert TurnIntentReasonCode.MISSING_EDIT_TARGET in intent.reason_codes
-def test_build_turn_intent_keeps_explicit_fix_as_edit() -> None:
+def test_build_turn_intent_allows_clear_workflow_change_edit_classification() -> None:
intent = build_turn_intent(
- user_message="Fix the error after login.",
- workflow_yaml="blocks: []",
+ user_message="Add a step that downloads the invoice PDF.",
+ workflow_yaml="title: Existing\nworkflow_definition:\n blocks: []\n",
chat_history=[],
global_llm_context="",
- request_policy=RequestPolicy(),
+ request_policy=RequestPolicy(allow_run_blocks=False),
+ classification=_classification(
+ TurnIntentMode.EDIT,
+ confidence=0.82,
+ target_entities={"workflow_change": ["add_invoice_download_step"]},
+ ),
)
assert intent.mode == TurnIntentMode.EDIT
assert intent.authority.may_update_workflow is True
- assert intent.target_entities["workflow"] == ["current_workflow"]
+ assert intent.target_entities["workflow_change"] == ["add_invoice_download_step"]
-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
-""",
+ ("block_ref", "expected_label"),
+ [
+ ("login block", "login_block"),
+ ("login_block", "login_block"),
+ ("login step", "login_step"),
+ ],
+)
+def test_build_turn_intent_resolves_classifier_block_targets(block_ref: str, expected_label: str) -> None:
+ intent = build_turn_intent(
+ user_message=f"Update the {block_ref}.",
+ workflow_yaml=(
+ "title: Existing\n"
+ "workflow_definition:\n"
+ " blocks:\n"
+ " - block_type: navigation\n"
+ " label: login_block\n"
+ " - block_type: action\n"
+ " label: login_step\n"
+ ),
chat_history=[],
global_llm_context="",
- request_policy=RequestPolicy(),
+ request_policy=RequestPolicy(allow_run_blocks=False),
+ classification=_classification(
+ TurnIntentMode.EDIT,
+ confidence=0.65,
+ target_entities={"block": [block_ref]},
+ reason_codes=[TurnIntentReasonCode.TARGET_ENTITY_RESOLVED],
+ ),
)
assert intent.mode == TurnIntentMode.EDIT
- assert intent.target_entities[UNRESOLVED_BLOCK_REF_TARGET_ENTITY] == [
- "WF_trigger_SSO_login",
- "update_card",
- ]
+ assert intent.target_entities["block"] == [expected_label]
+ assert intent.authority.may_update_workflow is True
-def test_build_turn_intent_does_not_treat_snake_case_fields_as_unresolved_block_refs() -> None:
+def test_build_turn_intent_preserves_classifier_unresolved_block_targets() -> 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
-""",
+ user_message="Remove the login block.",
+ workflow_yaml=(
+ "title: Existing\n"
+ "workflow_definition:\n"
+ " blocks:\n"
+ " - block_type: navigation\n"
+ " label: download_invoice\n"
+ ),
chat_history=[],
global_llm_context="",
- request_policy=RequestPolicy(),
+ request_policy=RequestPolicy(allow_run_blocks=False),
+ classification=_classification(
+ TurnIntentMode.CLARIFY,
+ confidence=0.35,
+ target_entities={"block": ["login block"]},
+ missing_context_question="Which existing block should I change?",
+ reason_codes=[TurnIntentReasonCode.LOW_CONFIDENCE_CLARIFICATION],
+ ),
)
- assert intent.mode == TurnIntentMode.EDIT
- assert UNRESOLVED_BLOCK_REF_TARGET_ENTITY not in intent.target_entities
+ assert intent.mode == TurnIntentMode.CLARIFY
+ assert intent.authority.requires_user_input is True
+ assert intent.target_entities[UNRESOLVED_BLOCK_REF_TARGET_ENTITY] == ["login block"]
-def test_build_turn_intent_carries_docs_mode_onto_bare_confirmation() -> None:
+def test_build_turn_intent_unknown_with_workflow_run_id_upgrades_to_diagnose() -> 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?"),
- ],
+ user_message="please continue",
+ workflow_yaml="",
+ chat_history=[],
global_llm_context="",
request_policy=RequestPolicy(),
+ workflow_run_id="wr_test_123",
)
- assert intent.mode == TurnIntentMode.DOCS_ANSWER
+ assert intent.mode == TurnIntentMode.DIAGNOSE
+ assert TurnIntentReasonCode.RECOVERY_FROM_RUN_CONTEXT in intent.reason_codes
+ assert intent.authority.may_read_run_context is True
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?"),
+def _structured_context_with_run_decision() -> str:
+ return StructuredContext(
+ decisions_made=[
+ "run_blocks_and_collect_debug: ran 3 blocks, hit per-tool-call budget",
+ " output: block_extract: {'rbt_certified': true}",
],
- global_llm_context="",
- request_policy=RequestPolicy(),
- )
-
- assert intent.mode == TurnIntentMode.DOCS_ANSWER
- assert TurnIntentReasonCode.CONFIRMATION_CARRYOVER in intent.reason_codes
+ ).to_json_str()
-def test_build_turn_intent_carries_build_mode_onto_confirmation() -> None:
+def test_build_turn_intent_unknown_with_persisted_prior_run_signal_upgrades_to_diagnose() -> None:
intent = build_turn_intent(
- user_message="go ahead",
+ user_message="please continue",
workflow_yaml="",
- chat_history=[_user_message("Build a workflow that downloads my invoices.")],
- global_llm_context="",
+ chat_history=[],
+ global_llm_context=_structured_context_with_run_decision(),
request_policy=RequestPolicy(),
)
- assert intent.mode == TurnIntentMode.BUILD
- assert TurnIntentReasonCode.CONFIRMATION_CARRYOVER in intent.reason_codes
-
+ assert intent.mode == TurnIntentMode.DIAGNOSE
+ assert TurnIntentReasonCode.RECOVERY_FROM_RUN_CONTEXT in intent.reason_codes
+ assert intent.authority.may_read_run_context is True
-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_has_structured_prior_run_signal_ignores_workflow_state_only() -> None:
+ payload = StructuredContext(workflow_state="updated workflow yaml diff summary").to_json_str()
+ assert _has_structured_prior_run_signal(payload) is False
-def test_build_turn_intent_confirmation_without_classifiable_prior_stays_unknown() -> None:
+def test_user_non_progress_fires_on_stuck_marker() -> None:
intent = build_turn_intent(
- user_message="I confirm.",
- workflow_yaml="blocks: []",
- chat_history=[_user_message("I confirm.")],
+ user_message="i can't see it",
+ workflow_yaml="",
+ chat_history=[_user_message("where is my downloaded file"), _ai_message("Check the Artifacts panel.")],
global_llm_context="",
request_policy=RequestPolicy(),
)
- assert intent.mode == TurnIntentMode.UNKNOWN
- assert TurnIntentReasonCode.CONFIRMATION_CARRYOVER not in intent.reason_codes
+ assert TurnIntentReasonCode.USER_NON_PROGRESS 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,
- )
+def test_user_non_progress_does_not_fire_on_first_turn_even_when_marker_matches() -> None:
intent = build_turn_intent(
- user_message="yes",
- workflow_yaml="blocks: []",
- chat_history=[_user_message("Build a workflow that downloads invoices.")],
+ user_message="where is my API key stored?",
+ workflow_yaml="",
+ chat_history=[],
global_llm_context="",
- request_policy=policy,
+ request_policy=RequestPolicy(),
)
- assert intent.mode == TurnIntentMode.REFUSE
+ assert TurnIntentReasonCode.USER_NON_PROGRESS not in intent.reason_codes
def test_docs_answer_turn_directive_renders_only_for_docs_answer_mode() -> None:
@@ -498,119 +506,14 @@ def test_docs_answer_turn_directive_renders_only_for_docs_answer_mode() -> None:
assert _docs_answer_turn_directive(None) == ""
-def test_build_turn_intent_requests_workflow_change_when_prior_assistant_turn_exists() -> None:
- ai_turn = WorkflowCopilotChatHistoryMessage(
- sender=WorkflowCopilotChatSender.AI,
- content="Drafted v1",
- created_at=datetime.now(timezone.utc),
- )
- intent = build_turn_intent(
- user_message="I did it myself, does this look right?",
- workflow_yaml="blocks: []",
- chat_history=[_user_message("Build a workflow"), ai_turn],
- global_llm_context="",
- request_policy=RequestPolicy(),
- )
-
- assert RequiredContextKey.WORKFLOW_CHANGE in intent.required_context
-
-
-def test_build_turn_intent_omits_workflow_change_on_first_turn() -> None:
- intent = build_turn_intent(
- user_message="Build a workflow",
- workflow_yaml="",
- chat_history=[],
- global_llm_context="",
- request_policy=RequestPolicy(),
- )
-
- assert RequiredContextKey.WORKFLOW_CHANGE not in intent.required_context
-
-
-def _ai_message(text: str) -> WorkflowCopilotChatHistoryMessage:
- return WorkflowCopilotChatHistoryMessage(
- sender=WorkflowCopilotChatSender.AI,
- content=text,
- created_at=datetime.now(timezone.utc),
- )
-
-
-def test_user_non_progress_fires_on_stuck_marker() -> None:
- intent = build_turn_intent(
- user_message="i can't see it",
- workflow_yaml="",
- chat_history=[_user_message("where is my downloaded file"), _ai_message("Check the Artifacts panel.")],
- global_llm_context="",
- request_policy=RequestPolicy(),
- )
- assert TurnIntentReasonCode.USER_NON_PROGRESS in intent.reason_codes
-
-
-def test_user_non_progress_fires_on_short_restatement() -> None:
- intent = build_turn_intent(
- user_message="where's my downloaded file?",
- workflow_yaml="",
- chat_history=[_user_message("where is my downloaded file"), _ai_message("Check the Artifacts panel.")],
- global_llm_context="",
- request_policy=RequestPolicy(),
- )
- assert TurnIntentReasonCode.USER_NON_PROGRESS in intent.reason_codes
-
-
-def test_user_non_progress_does_not_fire_on_topic_switch_after_ai_reply() -> None:
- """Regression: 'where is my X' is a topic switch, not non-progress, even with prior AI."""
- intent = build_turn_intent(
- user_message="where is my API key stored?",
- workflow_yaml="",
- chat_history=[_user_message("build me a workflow"), _ai_message("Drafted v1.")],
- global_llm_context="",
- request_policy=RequestPolicy(),
- )
- assert TurnIntentReasonCode.USER_NON_PROGRESS not in intent.reason_codes
-
-
-def test_user_non_progress_does_not_fire_on_first_turn_even_when_marker_matches() -> None:
- """Regression: a first-turn 'where is my X' is a real question, not non-progress."""
- intent = build_turn_intent(
- user_message="where is my API key stored?",
- workflow_yaml="",
- chat_history=[],
- global_llm_context="",
- request_policy=RequestPolicy(),
- )
- assert TurnIntentReasonCode.USER_NON_PROGRESS not in intent.reason_codes
-
-
-def test_user_non_progress_does_not_fire_on_topic_switch() -> None:
- intent = build_turn_intent(
- user_message="now build me a workflow for invoicing",
- workflow_yaml="",
- chat_history=[_user_message("where is my downloaded file"), _ai_message("Check the Artifacts panel.")],
- global_llm_context="",
- request_policy=RequestPolicy(),
- )
- assert TurnIntentReasonCode.USER_NON_PROGRESS not in intent.reason_codes
-
-
-def test_user_non_progress_does_not_fire_on_legitimate_followup() -> None:
- intent = build_turn_intent(
- user_message="where is the documentation for loop blocks?",
- workflow_yaml="",
- chat_history=[_user_message("build me a workflow"), _ai_message("Drafted v1.")],
- global_llm_context="",
- request_policy=RequestPolicy(),
- )
- assert TurnIntentReasonCode.USER_NON_PROGRESS not in intent.reason_codes
-
-
-def test_store_request_policy_attaches_turn_intent_to_context() -> None:
- ctx = CopilotContext(
- organization_id="org-1",
- workflow_id="wf-1",
- workflow_permanent_id="wfp-1",
- workflow_yaml="",
- browser_session_id=None,
- stream=MagicMock(),
+def test_store_request_policy_attaches_classified_turn_intent_to_context() -> None:
+ ctx = CopilotContext(
+ organization_id="org-1",
+ workflow_id="wf-1",
+ workflow_permanent_id="wfp-1",
+ workflow_yaml="",
+ browser_session_id=None,
+ stream=MagicMock(),
)
policy = RequestPolicy(allow_update_workflow=True, allow_run_blocks=False)
inputs = RequestPolicyGuardrailInputs(
@@ -624,9 +527,15 @@ def test_store_request_policy_attaches_turn_intent_to_context() -> None:
previous_user_message=None,
)
- _store_request_policy_on_context(ctx, policy, inputs)
+ _store_request_policy_on_context(
+ ctx,
+ policy,
+ inputs,
+ turn_intent_classification=_classification(TurnIntentMode.DIAGNOSE),
+ )
assert ctx.turn_intent is not None
+ assert ctx.turn_intent.mode == TurnIntentMode.DIAGNOSE
assert ctx.turn_intent.authority.may_update_workflow is False
assert ctx.turn_intent.authority.may_run_blocks is False
@@ -647,369 +556,68 @@ def test_answer_only_turn_intent_keeps_native_tools_registered() -> None:
assert filtered == tools
-def test_build_turn_intent_marks_declarative_step_request_as_edit() -> None:
- intent = build_turn_intent(
- user_message="I need a step where the page scrolls to the right.",
- workflow_yaml="blocks: []",
- chat_history=[],
- global_llm_context="",
- request_policy=RequestPolicy(allow_run_blocks=False),
- )
-
- assert intent.mode == TurnIntentMode.EDIT
-
-
-def test_build_turn_intent_marks_create_step_request_as_edit() -> None:
- intent = build_turn_intent(
- user_message="create a step in my workflow where the page scrolls to the right",
- workflow_yaml="blocks: []",
- chat_history=[],
- global_llm_context="",
- request_policy=RequestPolicy(allow_run_blocks=False),
- )
-
- assert intent.mode == TurnIntentMode.EDIT
-
-
-def test_build_turn_intent_marks_declarative_plural_step_request_as_edit() -> None:
- intent = build_turn_intent(
- user_message="I need steps that log in and download the report.",
- workflow_yaml="blocks: []",
- chat_history=[],
- global_llm_context="",
- request_policy=RequestPolicy(allow_run_blocks=False),
- )
-
- assert intent.mode == TurnIntentMode.EDIT
-
-
-def test_build_turn_intent_marks_another_step_request_as_edit() -> None:
- intent = build_turn_intent(
- user_message="I need another step after the login block.",
- workflow_yaml="blocks: []",
- chat_history=[],
- global_llm_context="",
- request_policy=RequestPolicy(allow_run_blocks=False),
- )
-
- assert intent.mode == TurnIntentMode.EDIT
-
-
-def test_build_turn_intent_marks_declarative_step_request_as_build_without_workflow() -> None:
- intent = build_turn_intent(
- user_message="I want a step that clicks the login button.",
- workflow_yaml="",
- chat_history=[],
- global_llm_context="",
- request_policy=RequestPolicy(),
- )
-
- assert intent.mode == TurnIntentMode.BUILD
-
-
-def test_build_turn_intent_marks_leading_add_step_as_edit() -> None:
- intent = build_turn_intent(
- user_message="add a step that downloads the invoice PDF",
- workflow_yaml="blocks: []",
- chat_history=[],
- global_llm_context="",
- request_policy=RequestPolicy(allow_run_blocks=False),
- )
-
- assert intent.mode == TurnIntentMode.EDIT
-
-
-def test_build_turn_intent_does_not_classify_leading_remove_named_block_as_edit() -> None:
- intent = build_turn_intent(
- user_message="remove the login block",
- workflow_yaml="blocks: []",
- chat_history=[],
- global_llm_context="",
- request_policy=RequestPolicy(allow_run_blocks=False),
- )
-
- assert intent.mode == TurnIntentMode.UNKNOWN
-
-
-def test_build_turn_intent_leading_add_with_failure_clause_is_edit() -> None:
- intent = build_turn_intent(
- user_message="Add a step that fails if the invoice total is missing.",
- workflow_yaml="blocks: []",
- chat_history=[],
- global_llm_context="",
- request_policy=RequestPolicy(allow_run_blocks=False),
- )
-
- assert intent.mode == TurnIntentMode.EDIT
-
-
-def test_build_turn_intent_leading_nouny_docs_question_stays_docs_answer() -> None:
- intent = build_turn_intent(
- user_message="delete is a step type, what does it do?",
- 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
-
-
-def test_build_turn_intent_leading_delete_step_docs_question_stays_docs_answer() -> None:
- intent = build_turn_intent(
- user_message="delete step - what does it do?",
- 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
-
-
-def test_build_turn_intent_docs_question_with_nouny_edit_word_stays_docs_answer() -> None:
- intent = build_turn_intent(
- user_message="What does the delete step do?",
- 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
-
-
-def test_build_turn_intent_failure_report_with_nouny_step_name_is_diagnose() -> None:
- intent = build_turn_intent(
- user_message="The delete step failed.",
- workflow_yaml="blocks: []",
- chat_history=[],
- global_llm_context="",
- request_policy=RequestPolicy(allow_update_workflow=False, allow_run_blocks=False),
- )
-
- assert intent.mode == TurnIntentMode.DIAGNOSE
-
-
-def test_build_turn_intent_leading_nouny_failure_report_is_diagnose() -> None:
- intent = build_turn_intent(
- user_message="delete step failed.",
- workflow_yaml="blocks: []",
- chat_history=[],
- global_llm_context="",
- request_policy=RequestPolicy(allow_update_workflow=False, allow_run_blocks=False),
- )
-
- assert intent.mode == TurnIntentMode.DIAGNOSE
-
-
-def test_build_turn_intent_leading_nouny_block_failure_report_is_diagnose() -> None:
- intent = build_turn_intent(
- user_message="Remove block failed after login.",
- workflow_yaml="blocks: []",
- chat_history=[],
- global_llm_context="",
- request_policy=RequestPolicy(allow_update_workflow=False, allow_run_blocks=False),
- )
-
- assert intent.mode == TurnIntentMode.DIAGNOSE
-
-
-def test_build_turn_intent_does_not_mutate_on_existing_block_reference() -> None:
- intent = build_turn_intent(
- user_message="thanks, that step looks great",
- workflow_yaml="blocks: []",
- chat_history=[],
- global_llm_context="",
- request_policy=RequestPolicy(),
- )
-
- assert intent.mode not in (TurnIntentMode.EDIT, TurnIntentMode.BUILD)
-
-
-def test_build_turn_intent_docs_question_with_structure_noun_stays_docs_answer() -> None:
- intent = build_turn_intent(
- user_message="Can you tell me what a block is supposed to do?",
- 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
-
-
-def test_build_turn_intent_structure_reference_question_does_not_mutate() -> None:
- intent = build_turn_intent(
- user_message="Where should a step go in the workflow?",
- workflow_yaml="blocks: []",
- chat_history=[],
- global_llm_context="",
- request_policy=RequestPolicy(),
- )
-
- assert intent.mode not in (TurnIntentMode.EDIT, TurnIntentMode.BUILD)
-
-
-def _structured_context_with_run_decision() -> str:
- return StructuredContext(
- decisions_made=[
- "run_blocks_and_collect_debug: ran 3 blocks, hit per-tool-call budget",
- " output: block_extract: {'rbt_certified': true}",
- ],
- ).to_json_str()
-
-
-def test_build_turn_intent_unknown_with_workflow_run_id_upgrades_to_diagnose() -> None:
- intent = build_turn_intent(
- user_message="please continue",
- workflow_yaml="",
- chat_history=[],
- global_llm_context="",
- request_policy=RequestPolicy(),
- workflow_run_id="wr_test_123",
- )
-
- assert intent.mode == TurnIntentMode.DIAGNOSE
- assert TurnIntentReasonCode.RECOVERY_FROM_RUN_CONTEXT in intent.reason_codes
- assert intent.authority.may_read_run_context is True
- assert intent.authority.may_update_workflow is False
- assert intent.authority.may_run_blocks is False
-
-
-def test_build_turn_intent_unknown_with_persisted_prior_run_signal_upgrades_to_diagnose() -> None:
- intent = build_turn_intent(
- user_message="please continue",
- workflow_yaml="",
- chat_history=[],
- global_llm_context=_structured_context_with_run_decision(),
- request_policy=RequestPolicy(),
- )
-
- assert intent.mode == TurnIntentMode.DIAGNOSE
- assert TurnIntentReasonCode.RECOVERY_FROM_RUN_CONTEXT in intent.reason_codes
- assert intent.authority.may_read_run_context is True
-
-
-def test_build_turn_intent_unknown_with_persisted_prior_failed_run_upgrades_to_diagnose() -> None:
- structured_context = StructuredContext()
- structured_context.merge_turn_summary(
- [
- {
- "tool": "update_and_run_blocks",
- "summary": "Failed: The run exceeded the 240s per-tool-call budget. Run ID: wr_budget_123.",
- }
- ]
- )
- global_llm_context = structured_context.to_json_str()
- assert _has_structured_prior_run_signal(global_llm_context) is True
-
- intent = build_turn_intent(
- user_message="please continue",
- workflow_yaml="",
- chat_history=[],
- global_llm_context=global_llm_context,
- request_policy=RequestPolicy(),
- )
-
- assert intent.mode == TurnIntentMode.DIAGNOSE
- assert TurnIntentReasonCode.RECOVERY_FROM_RUN_CONTEXT in intent.reason_codes
- assert intent.authority.may_read_run_context is True
-
-
-def test_build_turn_intent_unknown_without_run_signals_stays_unknown() -> None:
- intent = build_turn_intent(
- user_message="please continue",
- workflow_yaml="",
- chat_history=[],
- global_llm_context="",
- request_policy=RequestPolicy(),
- )
-
- assert intent.mode == TurnIntentMode.UNKNOWN
- assert TurnIntentReasonCode.RECOVERY_FROM_RUN_CONTEXT not in intent.reason_codes
- assert intent.authority.may_read_run_context is False
-
-
-def test_build_turn_intent_docs_answer_keeps_read_context_false_even_with_run_id() -> None:
- intent = build_turn_intent(
- user_message="How do parameters work?",
- workflow_yaml="",
- chat_history=[],
- global_llm_context="",
- request_policy=RequestPolicy(),
- workflow_run_id="wr_test_123",
- )
-
- assert intent.mode == TurnIntentMode.DOCS_ANSWER
- assert intent.authority.may_read_run_context is False
-
-
-def test_build_turn_intent_explicit_run_results_outranks_skip_test_policy() -> None:
- intent = build_turn_intent(
- user_message="Call get_run_results with workflow_run_id wr_test_123. Do not run blocks.",
- workflow_yaml="title: Existing workflow\nworkflow_definition:\n blocks: []\n",
- chat_history=[],
- global_llm_context="",
- request_policy=RequestPolicy(testing_intent="skip_test", allow_update_workflow=True, allow_run_blocks=False),
- workflow_run_id="wr_test_123",
- )
-
- assert intent.mode == TurnIntentMode.DIAGNOSE
- assert intent.authority.may_read_run_context is True
- assert intent.authority.may_update_workflow is False
- assert intent.authority.may_run_blocks is False
-
+def test_turn_intent_classification_parser_normalizes_supported_llm_payloads() -> None:
+ payload = {
+ "mode": "edit",
+ "expected_output": "workflow_update",
+ "required_context": ["current_workflow"],
+ "confidence": 1.2,
+ "target_entities": {"block": ["login block"]},
+ "reason_codes": ["target_entity_resolved", "not_a_reason"],
+ }
-def test_build_turn_intent_diagnose_grants_may_read_run_context_without_run_id() -> None:
- intent = build_turn_intent(
- user_message="Diagnose the failure.",
+ for raw_payload in (
+ payload,
+ (
+ '{"mode":"edit","expected_output":"workflow_update","required_context":["current_workflow"],'
+ '"confidence":1.2,"target_entities":{"block":["login block"]},'
+ '"reason_codes":["target_entity_resolved","not_a_reason"]}'
+ ),
+ ):
+ classification = _turn_intent_classification_from_raw(raw_payload)
+
+ assert classification is not None
+ assert classification.mode == TurnIntentMode.EDIT
+ assert classification.expected_output == TurnIntentExpectedOutput.WORKFLOW_UPDATE
+ assert classification.required_context == [RequiredContextKey.CURRENT_WORKFLOW]
+ assert classification.confidence == 1.0
+ assert classification.target_entities == {"block": ["login block"]}
+ assert classification.reason_codes == [TurnIntentReasonCode.TARGET_ENTITY_RESOLVED]
+
+
+def test_turn_intent_classification_parser_rejects_malformed_payload() -> None:
+ assert _turn_intent_classification_from_raw({"mode": "not_a_mode"}) is None
+ assert _turn_intent_classification_from_raw("not json") is None
+
+
+async def test_classify_turn_intent_calls_llm_handler_with_prompt_contract() -> None:
+ calls: list[dict[str, str]] = []
+
+ async def handler(prompt: str, prompt_name: str, **_: object) -> dict[str, object]:
+ calls.append({"prompt": prompt, "prompt_name": prompt_name})
+ return {
+ "mode": "build",
+ "expected_output": "workflow_draft",
+ "required_context": ["browser_state"],
+ "confidence": 0.82,
+ "target_entities": {"workflow": ["current_workflow"]},
+ "missing_context_question": None,
+ "reason_codes": [],
+ }
+
+ classification = await classify_turn_intent(
+ user_message="Create a workflow from the page I have open.",
workflow_yaml="",
chat_history=[],
global_llm_context="",
request_policy=RequestPolicy(),
+ handler=handler,
)
- assert intent.mode == TurnIntentMode.DIAGNOSE
- assert intent.authority.may_read_run_context is True
-
-
-def test_has_structured_prior_run_signal_ignores_workflow_state_only() -> None:
- payload = StructuredContext(workflow_state="updated workflow yaml diff summary").to_json_str()
- assert _has_structured_prior_run_signal(payload) is False
-
-
-def test_has_structured_prior_run_signal_ignores_unrelated_decisions() -> None:
- payload = StructuredContext(
- decisions_made=["click: clicked submit", "evaluate: returned true"],
- ).to_json_str()
- assert _has_structured_prior_run_signal(payload) is False
-
-
-def test_has_structured_prior_run_signal_handles_malformed_json() -> None:
- assert _has_structured_prior_run_signal("{not valid json") is False
- assert _has_structured_prior_run_signal("") is False
-
-
-def test_has_structured_prior_run_signal_ignores_failed_tool_attempt_without_output() -> None:
- # The merger appends a `<tool>: Failed: ...` entry for blocked/loop-rejected
- # calls, but no ` output:` line (hooks.py only sets output_preview on
- # ok=True). Failed attempts must not trigger recovery.
- payload = StructuredContext(
- decisions_made=["run_blocks_and_collect_debug: Failed: blocked by policy"],
- ).to_json_str()
- assert _has_structured_prior_run_signal(payload) is False
-
-
-def test_has_structured_prior_run_signal_matches_output_preview_line() -> None:
- payload = StructuredContext(
- decisions_made=[
- "get_run_results: workflow completed",
- " output: block_extract: {'result': 'ok'}",
- ],
- ).to_json_str()
- assert _has_structured_prior_run_signal(payload) is True
+ assert classification is not None
+ assert classification.mode == TurnIntentMode.BUILD
+ assert classification.required_context == [RequiredContextKey.BROWSER_STATE]
+ assert calls[0]["prompt_name"] == PROMPT_NAME
+ assert "Create a workflow from the page I have open." in calls[0]["prompt"]
+ assert "Allowed modes" in calls[0]["prompt"]
diff --git a/tests/unit/test_copilot_turn_intent_tool_gate.py b/tests/unit/test_copilot_turn_intent_tool_gate.py
index e74efa0b8..f1c2a8159 100644
--- a/tests/unit/test_copilot_turn_intent_tool_gate.py
+++ b/tests/unit/test_copilot_turn_intent_tool_gate.py
@@ -181,13 +181,30 @@ def test_turn_intent_gate_blocks_edit_without_target_context() -> None:
def test_turn_intent_gate_allows_edit_with_target_context() -> None:
intent = TurnIntent(
mode=TurnIntentMode.EDIT,
- target_entities={"workflow": ["wfp-1"]},
+ target_entities={"workflow_change": ["add_invoice_download_step"]},
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_default_current_workflow_only() -> None:
+ intent = TurnIntent(
+ mode=TurnIntentMode.EDIT,
+ target_entities={"workflow": ["current_workflow"]},
+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=True),
+ )
+
+ signal = _turn_intent_tool_error(_ctx(intent), "update_and_run_blocks")
+
+ _assert_signal(
+ signal,
+ internal_reason_code="turn_intent_missing_edit_target",
+ classifier_mode="edit",
+ blocked_tool="update_and_run_blocks",
+ )
+
+
def test_turn_intent_gate_blocks_edit_with_unresolved_label_reference() -> None:
intent = TurnIntent(
mode=TurnIntentMode.EDIT,
@@ -233,7 +250,7 @@ workflow_definition:
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"]},
+ target_entities={"workflow_change": ["extract_last_name"]},
authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=True),
)
ctx = _ctx(intent)
@@ -245,7 +262,7 @@ def test_turn_intent_gate_does_not_scan_raw_user_message_for_snake_case_refs() -
def test_turn_intent_gate_allows_edit_with_parameter_reference() -> None:
intent = TurnIntent(
mode=TurnIntentMode.EDIT,
- target_entities={"workflow": ["current_workflow"]},
+ target_entities={"workflow_change": ["use_account_number_in_search"]},
authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=True),
)
ctx = _ctx(intent)