Skip to content

Automate browser based workflows with AI

fix(SKY-9693): trust request policy completion contracts (#5925)

Andrew Neilson6d2ddec81221
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2
index 4bf2133bc..f08b5e979 100644
--- a/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2
+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2
@@ -1,10 +1,11 @@
Classify the latest Workflow Copilot request. Return only JSON with keys:
-testing_intent=require_test|skip_test|unspecified; credential_input_kind=none|raw_secret|credential_id|credential_name|website_stored_credential|placeholder; credential_refs; login_page_urls; requires_user_clarification.
+testing_intent=require_test|skip_test|unspecified; credential_input_kind=none|raw_secret|credential_id|credential_name|website_stored_credential|placeholder; credential_refs; login_page_urls; requires_user_clarification; completion_contract.
testing_intent:
- skip_test: the user asks for an untested draft, says they will test it themselves, says draft only, just sketch it, no validation run, or skip testing.
- require_test: the user asks to build/create and test/run/verify/end-to-end it, or asks for a complete workflow that should be validated.
- unspecified: the user does not say whether Skyvern should test the workflow.
+- Do not use skip_test for a "done when", "complete when", or success-condition sentence; that is a completion_contract.
credential_input_kind:
- raw_secret: the user pasted inline login credentials or secrets, including passwords, API keys, tokens, bearer headers, cookies, TOTP/OTP codes, private keys, card numbers, or CVVs.
@@ -18,6 +19,11 @@ requires_user_clarification:
- true only when the user refers to credentials but does not provide enough information to identify a saved credential or login page.
- false for normal build/test/verify requests with no credential reference, for explicit credential IDs/names/URLs, for placeholders, and for skip_test requests.
+completion_contract:
+- Set to the user's explicit done/complete/success condition when they provide one.
+- The value must be an exact span copied from the latest user message. Do not paraphrase, summarize, or infer a completion condition.
+- Set to null when the user does not provide an explicit completion condition.
+
Latest user message:
```{{ user_message }}```
Recent chat history:
diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.py
index df72bd9df..aa6f70faa 100644
--- a/skyvern/forge/sdk/copilot/enforcement.py
+++ b/skyvern/forge/sdk/copilot/enforcement.py
@@ -262,22 +262,32 @@ _ACTION_CATEGORIES: list[list[str]] = [
_SEQUENTIAL_CONNECTORS = [" and then ", " then ", " after that ", " next ", " followed by ", " afterward "]
+def _request_completion_contract(ctx: Any) -> str | None:
+ request_policy = getattr(ctx, "request_policy", None)
+ completion_contract = getattr(request_policy, "completion_contract", None)
+ if isinstance(completion_contract, str) and completion_contract.strip():
+ return completion_contract.strip()
+ return None
+
+
def _nudge(config: CopilotConfig | None, key: str) -> str:
if config is None:
return DEFAULT_ENFORCEMENT_NUDGES[key]
return config.nudge(key)
-def _goal_likely_needs_more_blocks(user_message: Any, block_count: int) -> bool:
+def _goal_likely_needs_more_blocks(user_message: Any, block_count: int, completion_contract: str | None = None) -> bool:
"""Return True when the goal likely requires more blocks than currently exist."""
if block_count >= MIN_BLOCKS_FOR_AUTO_COMPLETE:
return False
if not isinstance(user_message, str):
return False
text = user_message.lower()
+ has_sequential = any(conn in text for conn in _SEQUENTIAL_CONNECTORS)
+ if block_count >= 1 and completion_contract:
+ return has_sequential and block_count < 2
matched_categories = sum(1 for category in _ACTION_CATEGORIES if any(keyword in text for keyword in category))
- has_sequential = any(conn in text for conn in _SEQUENTIAL_CONNECTORS)
estimated_min_blocks = max(matched_categories, 2) if has_sequential else matched_categories
return block_count < estimated_min_blocks
@@ -314,7 +324,10 @@ def _response_coverage_nudge(ctx: Any, parsed: dict[str, Any], config: CopilotCo
# ctx.user_message is set by the agent orchestrator in a later stack PR
# (06c). The getattr default keeps this gate working on partial stacks.
user_message = getattr(ctx, "user_message", "")
- if isinstance(block_count, int) and _goal_likely_needs_more_blocks(user_message, block_count):
+ completion_contract = _request_completion_contract(ctx)
+ if isinstance(block_count, int) and _goal_likely_needs_more_blocks(
+ user_message, block_count, completion_contract
+ ):
nudge_count = getattr(ctx, "coverage_nudge_count", 0)
if nudge_count < MAX_INTERMEDIATE_NUDGES:
ctx.coverage_nudge_count = nudge_count + 1
diff --git a/skyvern/forge/sdk/copilot/request_policy.py b/skyvern/forge/sdk/copilot/request_policy.py
index 5f4160b1f..65c6c1da3 100644
--- a/skyvern/forge/sdk/copilot/request_policy.py
+++ b/skyvern/forge/sdk/copilot/request_policy.py
@@ -44,6 +44,7 @@ class RequestPolicy:
allow_run_blocks: bool = True
allow_missing_credentials_in_draft: bool = False
user_response_policy: str = "proceed"
+ completion_contract: str | None = None
resolved_credentials: list[Credential] = field(default_factory=list)
invalid_credential_ids: list[str] = field(default_factory=list)
clarification_question: str | None = None
@@ -57,6 +58,7 @@ class RequestPolicy:
"allow_run_blocks": self.allow_run_blocks,
"allow_missing_credentials_in_draft": self.allow_missing_credentials_in_draft,
"resolved_credential_count": len(self.resolved_credentials),
+ "completion_contract": self.completion_contract,
"raw_secret_detected": self.raw_secret_detected,
}
@@ -68,6 +70,8 @@ class RequestPolicy:
f"allow_run_blocks: {self.allow_run_blocks}",
f"allow_missing_credentials_in_draft: {self.allow_missing_credentials_in_draft}",
]
+ if self.completion_contract:
+ lines.append(f"completion_contract: {self.completion_contract}")
if self.resolved_credentials:
lines += [
"resolved_credentials:",
@@ -104,16 +108,31 @@ def _classification_from_raw(raw: Any) -> RequestPolicy:
return RequestPolicy()
testing_intent = raw.get("testing_intent")
credential_input_kind = raw.get("credential_input_kind")
+ completion_contract_raw = raw.get("completion_contract")
+ completion_contract = completion_contract_raw.strip() if isinstance(completion_contract_raw, str) else None
policy = RequestPolicy(
testing_intent=testing_intent if testing_intent in _TESTING_INTENTS else "unspecified",
credential_input_kind=credential_input_kind if credential_input_kind in _KINDS else "none",
credential_refs=_clean_list(raw.get("credential_refs") or []),
login_page_urls=_clean_list(raw.get("login_page_urls") or []),
requires_user_clarification=bool(raw.get("requires_user_clarification")),
+ completion_contract=completion_contract or None,
)
return policy
+def _ground_completion_contract(user_message: str, value: str | None) -> str | None:
+ if not value or not value.strip():
+ return None
+
+ contract = value.strip()
+ message = user_message or ""
+ if contract.lower() in message.lower():
+ return contract
+
+ return None
+
+
async def _classify_request(
user_message: str, workflow_yaml: str, chat_history: str, global_llm_context: str, handler: Any
) -> RequestPolicy:
@@ -143,8 +162,11 @@ async def _classify_request(
return RequestPolicy(credential_input_kind="credential_id" if ids else "none", credential_refs=ids)
policy = _classification_from_raw(raw)
+ policy.completion_contract = _ground_completion_contract(user_message, policy.completion_contract)
policy.credential_refs = _clean_list(policy.credential_refs + ids)
- if ids and policy.credential_input_kind != "raw_secret":
+ if policy.testing_intent == "skip_test" and policy.completion_contract:
+ policy.testing_intent = "unspecified"
+ if ids and policy.credential_input_kind in ("none", "placeholder"):
policy.credential_input_kind = "credential_id"
return policy
diff --git a/skyvern/forge/sdk/copilot/tools.py b/skyvern/forge/sdk/copilot/tools.py
index 8f121de70..fb20a5572 100644
--- a/skyvern/forge/sdk/copilot/tools.py
+++ b/skyvern/forge/sdk/copilot/tools.py
@@ -25,7 +25,12 @@ from skyvern.forge.sdk.artifact.models import ArtifactType
from skyvern.forge.sdk.copilot.attribution import resolve_copilot_created_by_stamp
from skyvern.forge.sdk.copilot.block_goal_wrapping import wrap_block_goals
from skyvern.forge.sdk.copilot.context import CopilotContext
-from skyvern.forge.sdk.copilot.enforcement import PROBABLE_SITE_BLOCK_STREAK_STOP_AT, TOTAL_TIMEOUT_SECONDS
+from skyvern.forge.sdk.copilot.enforcement import (
+ POST_INTERMEDIATE_SUCCESS_NUDGE,
+ PROBABLE_SITE_BLOCK_STREAK_STOP_AT,
+ TOTAL_TIMEOUT_SECONDS,
+ _goal_likely_needs_more_blocks,
+)
from skyvern.forge.sdk.copilot.failure_tracking import (
PER_TOOL_BUDGET_FAILURE_CATEGORY,
_canonical_block_config,
@@ -3370,6 +3375,33 @@ def _record_workflow_update_result(copilot_ctx: Any, result: dict[str, Any]) ->
clear_failed_step_tracker_for_tools_in_ctx(copilot_ctx, BLOCK_RUNNING_TOOLS)
+def _pre_run_workflow_coverage_error(copilot_ctx: Any) -> str | None:
+ block_count = getattr(copilot_ctx, "last_update_block_count", None)
+ if not isinstance(block_count, int):
+ return None
+
+ user_message = getattr(copilot_ctx, "user_message", "")
+ request_policy = getattr(copilot_ctx, "request_policy", None)
+ completion_contract = getattr(request_policy, "completion_contract", None)
+ if isinstance(completion_contract, str):
+ completion_contract = completion_contract.strip() or None
+ else:
+ completion_contract = None
+
+ if not _goal_likely_needs_more_blocks(user_message, block_count, completion_contract):
+ return None
+
+ nudge_count = getattr(copilot_ctx, "coverage_nudge_count", 0)
+ if nudge_count >= 1:
+ return None
+ copilot_ctx.coverage_nudge_count = nudge_count + 1
+ return (
+ f"{POST_INTERMEDIATE_SUCCESS_NUDGE} The workflow was saved with {block_count} block"
+ f"{'' if block_count == 1 else 's'}, but it has not been run because the request-policy "
+ "completion contract still leaves distinct requested actions uncovered."
+ )
+
+
def _analyze_run_blocks(result: dict[str, Any]) -> tuple[str | None, bool, list[dict] | None]:
"""Single-pass analysis of run result blocks.
@@ -3842,6 +3874,20 @@ async def update_and_run_blocks_tool(
sanitized = sanitize_tool_result_for_llm("update_workflow", update_result)
return json.dumps(sanitized)
+ coverage_error = _pre_run_workflow_coverage_error(copilot_ctx)
+ if coverage_error:
+ result = {
+ "ok": False,
+ "error": coverage_error,
+ "data": {
+ "block_count": copilot_ctx.last_update_block_count,
+ "workflow_updated": True,
+ "workflow_run_skipped": True,
+ },
+ }
+ record_tool_step_result_for_ctx(copilot_ctx, "update_and_run_blocks", arguments, result)
+ return json.dumps(result)
+
# Step 2: Compute frontier and run the blocks
new_definition = None
if copilot_ctx.last_workflow is not None:
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index 19fdfe80d..ef24a8dcb 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -46,6 +46,35 @@ class TestFailedTestResponseNormalization:
assert "test failed" in rewritten.lower()
assert "Call log:" not in rewritten
+ def test_pre_run_coverage_guard_uses_completion_contract(self) -> None:
+ from skyvern.forge.sdk.copilot.tools import _pre_run_workflow_coverage_error
+
+ ctx = _ctx(
+ user_message="Go to https://the-internet.herokuapp.com/download and then download the first file.",
+ request_policy=SimpleNamespace(completion_contract="complete when the download starts"),
+ last_update_block_count=1,
+ coverage_nudge_count=0,
+ )
+
+ error = _pre_run_workflow_coverage_error(ctx)
+
+ assert error is not None
+ assert "has not been run" in error
+ assert ctx.coverage_nudge_count == 1
+
+ def test_pre_run_coverage_guard_allows_single_final_action_contract(self) -> None:
+ from skyvern.forge.sdk.copilot.tools import _pre_run_workflow_coverage_error
+
+ ctx = _ctx(
+ user_message="Click Delete. Your goal is complete when the Delete button disappears.",
+ request_policy=SimpleNamespace(completion_contract="complete when the Delete button disappears"),
+ last_update_block_count=1,
+ coverage_nudge_count=0,
+ )
+
+ assert _pre_run_workflow_coverage_error(ctx) is None
+ assert ctx.coverage_nudge_count == 0
+
def test_failed_run_does_not_clear_last_workflow_state(self) -> None:
from skyvern.forge.sdk.copilot.tools import _record_run_blocks_result
@@ -1063,6 +1092,59 @@ class TestRequestPolicyCredentialResolution:
assert skip_policy.allow_update_workflow and not skip_policy.allow_run_blocks
assert skip_policy.allow_missing_credentials_in_draft
+ handler.response = {
+ "testing_intent": "skip_test",
+ "completion_contract": "complete when the page says your message has been sent",
+ }
+ completion_not_skip_policy = await build_request_policy(
+ user_message=(
+ "Fill out the contact form and submit it. "
+ "Your goal is complete when the page says your message has been sent."
+ ),
+ chat_history="",
+ **args,
+ )
+ assert completion_not_skip_policy.testing_intent == "unspecified"
+ assert completion_not_skip_policy.allow_run_blocks
+ assert (
+ completion_not_skip_policy.completion_contract == "complete when the page says your message has been sent"
+ )
+
+ handler.response = {
+ "credential_input_kind": "website_stored_credential",
+ "login_page_urls": ["https://bank.co.uk/login"],
+ }
+ stored_credential_with_id_policy = await build_request_policy(
+ user_message="use the saved login for https://bank.co.uk/login, credential id cred_bank",
+ chat_history="",
+ **args,
+ )
+ assert stored_credential_with_id_policy.credential_input_kind == "website_stored_credential"
+ assert stored_credential_with_id_policy.credential_refs == ["cred_bank"]
+ assert stored_credential_with_id_policy.resolved_credentials == [credential]
+
+ handler.response = {
+ "completion_contract": "confirmation banner appears",
+ }
+ no_completion_condition_policy = await build_request_policy(
+ user_message="submit the contact form and report whether it worked",
+ chat_history="",
+ **args,
+ )
+ assert no_completion_condition_policy.completion_contract is None
+
+ handler.response = {
+ "completion_contract": "confirmation banner appears",
+ }
+ paraphrased_completion_policy = await build_request_policy(
+ user_message="submit the contact form until the requested success state is reached",
+ chat_history="",
+ **args,
+ )
+ assert paraphrased_completion_policy.completion_contract is None
+ assert "completion_contract:" not in paraphrased_completion_policy.prompt_summary()
+ assert paraphrased_completion_policy.to_trace_data()["completion_contract"] is None
+
def test_translate_untested_draft_request_surfaces_unvalidated_workflow(self) -> None:
wf = SimpleNamespace(name="drafted")
ctx = _ctx(
diff --git a/tests/unit/test_copilot_enforcement_pruning.py b/tests/unit/test_copilot_enforcement_pruning.py
index e3b9f0eb1..ae1b5813d 100644
--- a/tests/unit/test_copilot_enforcement_pruning.py
+++ b/tests/unit/test_copilot_enforcement_pruning.py
@@ -800,10 +800,10 @@ class TestEnforcement:
class TestGoalLikelyNeedsMoreBlocks:
@staticmethod
- def _check(user_message: str, block_count: int) -> bool:
+ def _check(user_message: str, block_count: int, completion_contract: str | None = None) -> bool:
from skyvern.forge.sdk.copilot.enforcement import _goal_likely_needs_more_blocks
- return _goal_likely_needs_more_blocks(user_message, block_count)
+ return _goal_likely_needs_more_blocks(user_message, block_count, completion_contract)
def test_navigate_and_download_needs_two(self) -> None:
assert self._check("Go to france.fr and then download regulations", 1) is True
@@ -817,6 +817,15 @@ class TestGoalLikelyNeedsMoreBlocks:
def test_single_action_does_not_need_more(self) -> None:
assert self._check("Go to france.fr", 1) is False
+ def test_completion_contract_does_not_force_extra_blocks_after_success(self) -> None:
+ user_message = "Go to example.com/contact, fill out the form, and submit it."
+ assert self._check(user_message, 1, "confirmation banner appears") is False
+
+ def test_completion_contract_still_requires_sequential_blocks(self) -> None:
+ user_message = "Go to example.com and then download the report."
+ assert self._check(user_message, 1, "download starts") is True
+ assert self._check(user_message, 2, "download starts") is False
+
def test_sequential_connector_needs_at_least_two(self) -> None:
assert self._check("Do X and then do Y", 1) is True
diff --git a/tests/unit/test_copilot_response_coverage_gate.py b/tests/unit/test_copilot_response_coverage_gate.py
index 20851daf2..bed985a31 100644
--- a/tests/unit/test_copilot_response_coverage_gate.py
+++ b/tests/unit/test_copilot_response_coverage_gate.py
@@ -12,6 +12,7 @@ from __future__ import annotations
import json
from dataclasses import dataclass, field
+from types import SimpleNamespace
from typing import Any
from skyvern.forge.sdk.copilot.enforcement import (
@@ -41,6 +42,7 @@ class _Ctx:
self.format_nudge_count = 0
self.no_workflow_nudge_count = 0
self.user_message = ""
+ self.request_policy = None
self.last_update_block_count = None
self.last_test_ok = None
self.last_test_failure_reason = None
@@ -98,6 +100,15 @@ def test_reply_with_coverage_gap_fires_nudge() -> None:
assert ctx.coverage_nudge_count == 1
+def test_reply_after_success_with_request_policy_completion_contract_passes_through() -> None:
+ ctx = _post_success_ctx("Go to https://example.com/contact. Fill out the contact form and submit it.")
+ ctx.request_policy = SimpleNamespace(completion_contract="confirmation banner appears")
+ parsed = {"type": "REPLY", "user_response": "I created and tested the workflow."}
+
+ assert _response_coverage_nudge(ctx, parsed) is None
+ assert ctx.coverage_nudge_count == 0
+
+
def test_coverage_nudge_respects_counter_cap() -> None:
ctx = _post_success_ctx("go to X and download Y")
parsed = {"type": "REPLY", "user_response": "one block draft"}