Skip to content

Automate browser based workflows with AI

SKY-10307: Surface Copilot missing-context fallback (#6144)

Andrew Neilsona9b646f0ec44
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index cec0d365f..b5ba8d845 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -70,6 +70,7 @@ from skyvern.forge.sdk.copilot.tracing_setup import _copilot_model_name, ensure_
from skyvern.forge.sdk.copilot.turn_context import TurnContextAssembler, TurnContextInputs, TurnContextPacket
from skyvern.forge.sdk.copilot.turn_intent import (
NO_MUTATION_TURN_INTENT_MODES,
+ RequiredContextKey,
TurnIntent,
TurnIntentMode,
build_turn_intent,
@@ -707,9 +708,29 @@ _CANCEL_REPLY_UNVALIDATED = (
)
_CANCEL_REPLY_TESTED = "Cancelled. I have a tested draft for you. Accept it to save, or discard."
_UNBACKED_WORKFLOW_DELIVERY_REPLY = (
- "I wasn't able to produce a workflow proposal in this turn. Please try again, or provide the missing details "
- "so I can build and test it."
+ "I wasn't able to produce a workflow proposal in this turn, and I couldn't identify which details were missing "
+ "from this turn. Please retry with the target site, page, or workflow requirement."
)
+_UNBACKED_WORKFLOW_DELIVERY_PREFIX = "I wasn't able to produce a workflow proposal in this turn."
+_GENERIC_MISSING_CONTEXT_PHRASES = (
+ "missing details",
+ "one more detail",
+)
+_REQUIRED_CONTEXT_LABELS = {
+ RequiredContextKey.CURRENT_WORKFLOW: "the current workflow",
+ RequiredContextKey.PROPOSED_WORKFLOW: "the proposed workflow",
+ RequiredContextKey.LATEST_ASSISTANT_PROPOSAL: "the latest workflow proposal",
+ RequiredContextKey.WORKFLOW_CHANGE: "the workflow change to apply",
+ RequiredContextKey.LATEST_RUN_RESULT: "the latest run result",
+ RequiredContextKey.CREDENTIAL_METADATA: "the saved credential metadata",
+ RequiredContextKey.DOCS_CONTEXT: "the relevant documentation context",
+ RequiredContextKey.BROWSER_STATE: "the current browser tab or page state",
+}
+_DIAGNOSIS_MISSING_CONTEXT_LABELS = {
+ "workflow_run_id": "the workflow run ID",
+ "block_results": "the block run results",
+ "failure_reason": "the failure reason",
+}
_INTERNAL_BLOCK_TAXONOMY_REPLY = (
"Internal workflow names are not the right interface to use when building with Copilot. "
"Describe the page action, data to collect, sign-in step, or check you want, and I'll translate that into "
@@ -755,6 +776,87 @@ def _recorded_failure_summary(ctx: CopilotContext) -> tuple[str, str]:
return reason, status_sentence
+def _specific_missing_context_question(value: Any) -> str:
+ question = _clean_recorded_failure_text(value, max_chars=320)
+ if not question:
+ return ""
+ lowered = question.lower()
+ if any(phrase in lowered for phrase in _GENERIC_MISSING_CONTEXT_PHRASES):
+ return ""
+ if question[-1] not in ".?!":
+ question += "."
+ return question
+
+
+def _join_human_list(items: list[str]) -> str:
+ if len(items) <= 1:
+ return items[0] if items else ""
+ if len(items) == 2:
+ return f"{items[0]} and {items[1]}"
+ return ", ".join(items[:-1]) + f", and {items[-1]}"
+
+
+def _required_context_label(value: Any) -> str:
+ if isinstance(value, RequiredContextKey):
+ return _REQUIRED_CONTEXT_LABELS[value]
+ if isinstance(value, str):
+ if value in _DIAGNOSIS_MISSING_CONTEXT_LABELS:
+ return _DIAGNOSIS_MISSING_CONTEXT_LABELS[value]
+ try:
+ return _REQUIRED_CONTEXT_LABELS[RequiredContextKey(value)]
+ except ValueError:
+ return _clean_recorded_failure_text(value, max_chars=120)
+ return ""
+
+
+def _turn_context_missing_context_labels(ctx: CopilotContext) -> list[str]:
+ packet = getattr(ctx, "turn_context_packet", None)
+ omissions = getattr(packet, "omissions", None)
+ if not isinstance(omissions, list):
+ return []
+ labels: list[str] = []
+ for omission in omissions:
+ label = _required_context_label(getattr(omission, "context_key", None))
+ if label:
+ labels.append(label)
+ return list(dict.fromkeys(labels))
+
+
+def _diagnosis_missing_context_labels(ctx: CopilotContext) -> list[str]:
+ contract = getattr(ctx, "latest_diagnosis_repair_contract", None)
+ diagnosis = getattr(contract, "diagnosis_result", None)
+ missing_context = getattr(diagnosis, "missing_context", None)
+ if not isinstance(missing_context, list):
+ return []
+ labels = [_required_context_label(item) for item in missing_context]
+ return list(dict.fromkeys(label for label in labels if label))
+
+
+def _unbacked_workflow_delivery_reply(ctx: CopilotContext) -> str:
+ turn_intent = getattr(ctx, "turn_intent", None)
+ if isinstance(turn_intent, TurnIntent):
+ question = _specific_missing_context_question(turn_intent.missing_context_question)
+ if question:
+ return f"{_UNBACKED_WORKFLOW_DELIVERY_PREFIX} I need this before I can build and test it: {question}"
+
+ request_policy = ctx.request_policy if isinstance(ctx.request_policy, RequestPolicy) else None
+ if request_policy is not None:
+ question = _specific_missing_context_question(request_policy.clarification_question)
+ if question:
+ return f"{_UNBACKED_WORKFLOW_DELIVERY_PREFIX} I need this before I can build and test it: {question}"
+
+ missing_context = _diagnosis_missing_context_labels(ctx) or _turn_context_missing_context_labels(ctx)
+ if missing_context:
+ items = _join_human_list(missing_context)
+ return f"{_UNBACKED_WORKFLOW_DELIVERY_PREFIX} Required context was unavailable: {items}."
+
+ reason, status_sentence = _recorded_failure_summary(ctx)
+ if reason:
+ return f"{_UNBACKED_WORKFLOW_DELIVERY_PREFIX} The recorded blocker was: {reason}.{status_sentence}"
+
+ return _UNBACKED_WORKFLOW_DELIVERY_REPLY
+
+
def _last_good_failure_reply(ctx: CopilotContext, tested_reply: str) -> str:
reason, status_sentence = _recorded_failure_summary(ctx)
if not reason:
@@ -1156,6 +1258,7 @@ def _translate_to_agent_result(
)
output_policy_verdict = _copy_output_policy_verdict(raw_output_policy_verdict)
soft_rewrite_reasons: list[OutputPolicyReason] = []
+ unbacked_workflow_delivery_rewritten = False
if OutputPolicyReason.INTERNAL_BLOCK_TAXONOMY_LEAK in output_policy_verdict.reason_codes:
user_response = _INTERNAL_BLOCK_TAXONOMY_REPLY
soft_rewrite_reasons.append(OutputPolicyReason.INTERNAL_BLOCK_TAXONOMY_LEAK)
@@ -1171,7 +1274,10 @@ def _translate_to_agent_result(
# Preserve the unbacked-proposal correction when both soft rewrites apply:
# a reply must not imply a workflow exists when no proposal was produced.
if OutputPolicyReason.UNBACKED_WORKFLOW_DELIVERY_CLAIM in output_policy_verdict.reason_codes:
- user_response = _UNBACKED_WORKFLOW_DELIVERY_REPLY
+ user_response = _unbacked_workflow_delivery_reply(ctx)
+ resp_type = "ASK_QUESTION"
+ output_policy_verdict.output_kind = CopilotOutputKind.CLARIFICATION_REQUEST
+ unbacked_workflow_delivery_rewritten = True
soft_rewrite_reasons.append(OutputPolicyReason.UNBACKED_WORKFLOW_DELIVERY_CLAIM)
output_policy_verdict.remove(OutputPolicyReason.UNBACKED_WORKFLOW_DELIVERY_CLAIM)
if OutputPolicyReason.MISSING_PROPOSAL_STATE in output_policy_verdict.reason_codes:
@@ -1221,7 +1327,13 @@ def _translate_to_agent_result(
workflow_was_persisted=ctx.workflow_persisted,
total_tokens=ctx.total_tokens_used,
clear_proposed_workflow=resp_type == "ASK_QUESTION",
- proposal_disposition="review_untested" if unvalidated else "auto_applicable",
+ proposal_disposition=(
+ "no_proposal"
+ if unbacked_workflow_delivery_rewritten and last_workflow is None
+ else "review_untested"
+ if unvalidated
+ else "auto_applicable"
+ ),
output_policy_diagnostics=output_policy_diagnostics,
)
diff --git a/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py b/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py
index dbb7586a4..3a5e44867 100644
--- a/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py
+++ b/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-import re
from enum import StrEnum
from typing import Any
@@ -8,12 +7,12 @@ from pydantic import BaseModel, ConfigDict, Field
from skyvern.forge.sdk.copilot.output_policy import url_origin
from skyvern.forge.sdk.copilot.request_policy import redact_raw_secrets_for_prompt
+from skyvern.forge.sdk.copilot.workflow_credential_utils import URL_CANDIDATE_RE
_TEXT_MAX = 240
_SUMMARY_MAX = 180
_MAX_ITEMS = 20
_FAILED_STATUSES = {"failed", "terminated", "canceled", "timed_out"}
-_URL_CANDIDATE_RE = re.compile(r"https?://[^\s)>,]+")
class StrictModel(BaseModel):
@@ -217,7 +216,7 @@ def _safe_str(value: Any) -> str | None:
def _safe_text(value: str | None, max_chars: int = _TEXT_MAX) -> str:
text = redact_raw_secrets_for_prompt((value or "").strip())
- text = _URL_CANDIDATE_RE.sub(lambda m: url_origin(m.group(0)) or "[URL]", text)
+ text = URL_CANDIDATE_RE.sub(lambda m: url_origin(m.group(0)) or "[URL]", text)
return text if len(text) <= max_chars else text[: max_chars - 3].rstrip() + "..."
diff --git a/skyvern/forge/sdk/copilot/recoverable_failure.py b/skyvern/forge/sdk/copilot/recoverable_failure.py
index 8834afc5f..da5631f0e 100644
--- a/skyvern/forge/sdk/copilot/recoverable_failure.py
+++ b/skyvern/forge/sdk/copilot/recoverable_failure.py
@@ -13,15 +13,14 @@ from pydantic import ValidationError
from skyvern.forge.sdk.api.llm.exceptions import LLMProviderError
from skyvern.forge.sdk.copilot.context import StructuredContext
-from skyvern.forge.sdk.copilot.output_policy import url_origin
from skyvern.forge.sdk.copilot.request_policy import redact_raw_secrets_for_prompt
+from skyvern.forge.sdk.copilot.workflow_credential_utils import URL_CANDIDATE_RE, url_origin
from skyvern.forge.sdk.workflow.exceptions import BaseWorkflowHTTPException
RecoverableFailureKind = Literal["validation", "tool_call", "external_dep", "timeout", "unknown"]
_REASON_SUMMARY_MAX_CHARS = 120
_RECOVERABLE_ERROR_ID_PREFIX = "cpe"
-_RECORDED_FAILURE_URL_RE = re.compile(r"https?://[^\s)>,]+")
_RECORDED_FAILURE_CREDENTIAL_ID_RE = re.compile(r"\bcred_[A-Za-z0-9][A-Za-z0-9_-]*\b")
_BROWSER_SESSION_ID_RE = re.compile(r"\bpbs_[A-Za-z0-9_-]+\b")
_BROWSER_SESSION_WITH_ID_RE = re.compile(r"\bbrowser session\s+pbs_[A-Za-z0-9_-]+\b", re.IGNORECASE)
@@ -69,7 +68,7 @@ def clean_recorded_failure_text(value: object, max_chars: int = _REASON_SUMMARY_
text = redact_raw_secrets_for_prompt(" ".join(text.split()))
text = _redact_browser_session_references(text)
text = _RECORDED_FAILURE_CREDENTIAL_ID_RE.sub("[CREDENTIAL_ID]", text)
- text = _RECORDED_FAILURE_URL_RE.sub(lambda match: url_origin(match.group(0)) or "[URL]", text)
+ text = URL_CANDIDATE_RE.sub(lambda match: url_origin(match.group(0)) or "[URL]", text)
if len(text) > max_chars:
text = text[: max_chars - 3].rstrip() + "..."
return text
diff --git a/skyvern/forge/sdk/copilot/workflow_credential_utils.py b/skyvern/forge/sdk/copilot/workflow_credential_utils.py
index dbcea7cf5..da9866b6e 100644
--- a/skyvern/forge/sdk/copilot/workflow_credential_utils.py
+++ b/skyvern/forge/sdk/copilot/workflow_credential_utils.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import re
from typing import Any
from urllib.parse import urlparse
@@ -7,6 +8,7 @@ from skyvern.utils.yaml_loader import safe_load_no_dates
_NESTED_BLOCK_LIST_KEYS = ("loop_blocks", "blocks")
_BRANCH_LIST_KEYS = ("branch_conditions", "branches", "ordered_branches")
+URL_CANDIDATE_RE = re.compile(r"\b(?:https?://[^\s)>,]+|www\.[^\s)>,]+)", re.IGNORECASE)
def parse_workflow_yaml(workflow_yaml: str) -> Any:
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index 398ad93b5..04bfadc57 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -26,6 +26,8 @@ from skyvern.forge.sdk.copilot.request_policy import (
build_transcript_context,
redact_raw_secrets_for_prompt,
)
+from skyvern.forge.sdk.copilot.turn_context import TranscriptContext, TurnContextOmission, TurnContextPacket
+from skyvern.forge.sdk.copilot.turn_intent import TurnIntent, TurnIntentAuthority, TurnIntentMode
from skyvern.forge.sdk.schemas.workflow_copilot import (
WorkflowCopilotChatHistoryMessage,
WorkflowCopilotChatSender,
@@ -1229,8 +1231,81 @@ workflow_definition:
assert "here's the workflow" not in agent_result.user_response.lower()
assert "wasn't able to produce a workflow proposal" in agent_result.user_response
+ assert "provide the missing details" not in agent_result.user_response
+ assert "couldn't identify which details were missing" in agent_result.user_response
assert agent_result.updated_workflow is None
assert agent_result.workflow_yaml is None
+ assert agent_result.response_type == "ASK_QUESTION"
+
+ def test_unbacked_workflow_claim_uses_turn_intent_missing_context(self) -> None:
+ ctx = _ctx(
+ last_test_ok=None,
+ turn_intent=TurnIntent(
+ mode=TurnIntentMode.BUILD,
+ user_goal="Buy tickets for Wrexham vs LA Galaxy",
+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=True),
+ missing_context_question=(
+ "Which ticketing site or seller should the workflow use? "
+ "Actual purchase or payment requires explicit human approval."
+ ),
+ ),
+ )
+ result = _fake_run_result({"type": "REPLY", "user_response": "Here's the workflow."})
+ agent_result = agent_module._translate_to_agent_result(
+ result, ctx, global_llm_context=None, chat_request=_chat_request(), organization_id="org-1"
+ )
+
+ assert "here's the workflow" not in agent_result.user_response.lower()
+ assert "Which ticketing site or seller should the workflow use?" in agent_result.user_response
+ assert "Actual purchase or payment requires explicit human approval." in agent_result.user_response
+ assert "provide the missing details" not in agent_result.user_response
+ assert agent_result.response_type == "ASK_QUESTION"
+ assert agent_result.updated_workflow is None
+
+ def test_unbacked_workflow_claim_renders_diagnosis_missing_context_labels(self) -> None:
+ ctx = _ctx(
+ last_test_ok=None,
+ latest_diagnosis_repair_contract=SimpleNamespace(
+ diagnosis_result=SimpleNamespace(missing_context=["workflow_run_id", "block_results"])
+ ),
+ )
+ result = _fake_run_result({"type": "REPLY", "user_response": "I've drafted a workflow for you."})
+ agent_result = agent_module._translate_to_agent_result(
+ result, ctx, global_llm_context=None, chat_request=_chat_request(), organization_id="org-1"
+ )
+
+ assert "Required context was unavailable: the workflow run ID and the block run results." in (
+ agent_result.user_response
+ )
+ assert "workflow_run_id" not in agent_result.user_response
+ assert "block_results" not in agent_result.user_response
+
+ def test_unbacked_workflow_claim_renders_turn_context_omissions(self) -> None:
+ ctx = _ctx(
+ last_test_ok=None,
+ turn_context_packet=TurnContextPacket(
+ turn_intent_summary={},
+ transcript_context=TranscriptContext(
+ earliest_user_turn="",
+ latest_prior_user_turn="",
+ latest_assistant_turn="",
+ retained_history="",
+ omitted_any=False,
+ ),
+ omissions=[
+ TurnContextOmission(
+ context_key="browser_state",
+ reason="not_implemented",
+ )
+ ],
+ ),
+ )
+ result = _fake_run_result({"type": "REPLY", "user_response": "I've drafted a workflow for you."})
+ agent_result = agent_module._translate_to_agent_result(
+ result, ctx, global_llm_context=None, chat_request=_chat_request(), organization_id="org-1"
+ )
+
+ assert "Required context was unavailable: the current browser tab or page state." in agent_result.user_response
def test_initial_part_workflow_claim_is_rewritten_without_proposal(self) -> None:
ctx = _ctx(last_test_ok=None)
@@ -1246,6 +1321,7 @@ workflow_definition:
assert "initial part of your workflow" not in agent_result.user_response.lower()
assert "wasn't able to produce a workflow proposal" in agent_result.user_response
+ assert "provide the missing details" not in agent_result.user_response
assert agent_result.updated_workflow is None
assert agent_result.workflow_yaml is None
diff --git a/tests/unit/test_copilot_output_policy.py b/tests/unit/test_copilot_output_policy.py
index c0033b01e..6cbc65848 100644
--- a/tests/unit/test_copilot_output_policy.py
+++ b/tests/unit/test_copilot_output_policy.py
@@ -1227,7 +1227,19 @@ def test_translate_to_agent_result_rewrites_unbacked_workflow_claim() -> None:
)
assert "wasn't able to produce a workflow proposal" in agent_result.user_response
+ assert "provide the missing details" not in agent_result.user_response
+ assert "couldn't identify which details were missing" in agent_result.user_response
+ assert agent_result.response_type == "ASK_QUESTION"
assert agent_result.updated_workflow is None
+ assert agent_result.output_policy_diagnostics == {
+ "raw_output_kind": "informational_answer",
+ "final_output_kind": "clarification_request",
+ "hard_block_reason_codes": [],
+ "soft_rewrite_reason_codes": ["unbacked_workflow_delivery_claim", "missing_proposal_state"],
+ "raw_would_have_failed": True,
+ "contained_failure": True,
+ "final_output_policy_allowed": True,
+ }
def test_translate_to_agent_result_rewrites_deprecated_block_taxonomy() -> None:
@@ -1294,6 +1306,8 @@ def test_translate_to_agent_result_prioritizes_unbacked_workflow_claim_over_taxo
assert "wasn't able to produce a workflow proposal" in agent_result.user_response
assert "task_v2" not in agent_result.user_response
+ assert agent_result.output_policy_diagnostics is not None
+ assert "unbacked_workflow_delivery_claim" in agent_result.output_policy_diagnostics["soft_rewrite_reason_codes"]
assert agent_result.updated_workflow is None