Skip to content

Automate browser based workflows with AI

SKY-14045 Copilot: stop re-deciding login blocks the workflow already has (#8206)

Andrew Neilson6dc0104f559f
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index e2cdb289a..1507fc27f 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -198,11 +198,12 @@ WORKFLOW_KNOWLEDGE_BASE_PATH = (
_COPILOT_TURN_SPAN_NAME = "copilot.turn"
-def _render_code_only_browser_authoring_prompt() -> str:
+def _render_code_only_browser_authoring_prompt(ctx: CopilotContext | None = None) -> str:
from skyvern.forge.sdk.copilot.tools.banned_blocks import _code_only_browser_authoring_prompt
+ settled_block_types = ctx.code_only_settled_block_types if isinstance(ctx, CopilotContext) else frozenset()
return (
- _code_only_browser_authoring_prompt()
+ _code_only_browser_authoring_prompt(settled_block_types)
+ "\n\nWhen a SYNTHESIZED CODE BLOCK is offered to you, it already encodes the page\n"
"interactions you scouted as deterministic Playwright. Persist that block VERBATIM\n"
"via update_workflow / update_and_run_blocks — do not rewrite, reorder, or\n"
@@ -597,8 +598,6 @@ def _build_system_prompt(
# suffix, so its complete rendered prompt is safe to mark stable.
stable_prefix = prompt_with_boundary
dynamic_suffix = ""
- if not answer_only and copilot_config.block_authoring_policy == BlockAuthoringPolicy.CODE_ONLY_BROWSER:
- dynamic_suffix = f"{dynamic_suffix}\n\n{_render_code_only_browser_authoring_prompt()}"
return CacheableSystemInstructions(stable_prefix, dynamic_suffix)
@@ -1024,6 +1023,8 @@ def _build_dynamic_system_prompt(tool_usage_guide: str, config: CopilotConfig) -
+ _code_authoring_repair_context_prompt(ctx)
+ todo_list_prompt(ctx)
)
+ if config.block_authoring_policy == BlockAuthoringPolicy.CODE_ONLY_BROWSER:
+ dynamic_context = f"{dynamic_context}\n\n{_render_code_only_browser_authoring_prompt(ctx)}"
if isinstance(base_system_prompt, CacheableSystemInstructions):
return CacheableSystemInstructions(
base_system_prompt.stable_prefix,
diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.py
index 0abb1d386..4d2353ade 100644
--- a/skyvern/forge/sdk/copilot/context.py
+++ b/skyvern/forge/sdk/copilot/context.py
@@ -807,11 +807,18 @@ class CopilotContext(AgentContext):
turn_started_at: str | None = None
turn_ended_at: str | None = None
+ # Block types the workflow already carried when the turn opened. Tools reassign
+ # ``workflow_yaml`` mid-turn, so this must never be recomputed from it.
+ code_only_settled_block_types: frozenset[str] = field(init=False, default=frozenset())
+
def __post_init__(self) -> None:
parent_post_init = getattr(super(), "__post_init__", None)
if callable(parent_post_init):
parent_post_init()
from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome
+ from skyvern.forge.sdk.copilot.tools.banned_blocks import _extract_existing_code_only_pending_block_types
+
+ self.code_only_settled_block_types = _extract_existing_code_only_pending_block_types(self.workflow_yaml)
if isinstance(self.last_run_outcome, RecordedRunOutcome):
super().__setattr__("terminal_envelope_run_outcomes", [self.last_run_outcome])
diff --git a/skyvern/forge/sdk/copilot/tools/banned_blocks.py b/skyvern/forge/sdk/copilot/tools/banned_blocks.py
index 17709cdb7..e306b88d2 100644
--- a/skyvern/forge/sdk/copilot/tools/banned_blocks.py
+++ b/skyvern/forge/sdk/copilot/tools/banned_blocks.py
@@ -192,15 +192,36 @@ def _code_only_browser_unavailable_types() -> list[str]:
)
-def _code_only_browser_pending_details() -> list[str]:
+def _code_only_browser_pending_details(settled_block_types: frozenset[str] | None = None) -> list[str]:
+ settled = settled_block_types or frozenset()
return [
_render_block_policy_detail(block_type, policy)
for block_type, policy in sorted(_COPILOT_BLOCK_TYPE_POLICIES.items())
if policy.scope == CopilotBlockPolicyScope.CODE_ONLY_BROWSER
and policy.status == CopilotBlockPolicyStatus.CODE_NATIVE_PENDING
+ and block_type not in settled
]
+def _extract_existing_code_only_pending_block_types(prior_workflow_yaml: str | None) -> frozenset[str]:
+ blocks = _parse_workflow_blocks(prior_workflow_yaml)
+ if not blocks:
+ return frozenset()
+
+ existing_types: set[str] = set()
+ for _label, block_type in _collect_banned_block_items(blocks, _COPILOT_CODE_ONLY_BROWSER_BANNED_BLOCK_TYPES):
+ normalized = normalize_copilot_block_type_alias(block_type.strip().lower())
+ policy = _COPILOT_BLOCK_TYPE_POLICIES.get(normalized)
+ if (
+ policy is not None
+ and policy.scope == CopilotBlockPolicyScope.CODE_ONLY_BROWSER
+ and policy.status == CopilotBlockPolicyStatus.CODE_NATIVE_PENDING
+ ):
+ existing_types.add(normalized)
+
+ return frozenset(existing_types)
+
+
def _code_only_browser_unavailable_summary() -> str:
unavailable = ", ".join(f"`{block_type}`" for block_type in _code_only_browser_unavailable_types())
return (
@@ -217,8 +238,12 @@ def _code_only_browser_validation_guidance() -> str:
)
-def _code_only_browser_schema_guidance() -> list[str]:
- return [
+def _login_is_settled(settled_block_types: frozenset[str] | None) -> bool:
+ return bool(settled_block_types) and "login" in (settled_block_types or frozenset())
+
+
+def _code_only_browser_schema_guidance(settled_block_types: frozenset[str] | None = None) -> list[str]:
+ guidance = [
"Use one focused code block per durable browser goal, such as open, search, submit, expand, or extract.",
_code_only_browser_unavailable_summary(),
"Use concrete selectors and text anchors found during exploration. If only intent targeting is available, inspect the page again before mutating.",
@@ -226,14 +251,86 @@ def _code_only_browser_schema_guidance() -> list[str]:
"Keep block outputs JSON-safe and include visible evidence text when extracting records, products, totals, confirmations, or identifiers.",
"Wait for the value the block returns, not for a URL or a navigation. A page reaches its final URL while it is still rendering, so a URL check passes before the value exists and a navigation wait fails on a page that has already arrived.",
"Deciding which of two page states you are in costs no wait: wait once on `a.or_(b).first`, then branch with `is_visible()` or `count()`. Build each side to match only visible elements — `page.locator('#x >> visible=true')` — because `.first` is the first match in DOM order, not the first to become visible, so a hidden sign-in form that precedes the signed-in view captures the wait and spends the whole ceiling. Give that combined entry wait `timeout=90000`, because a cold first load can hydrate for a minute and the wait returns the instant either state appears, so a fast page pays nothing for the generous window.",
- "For saved credentials: bind the credential as a workflow parameter with workflow_parameter_type credential_id and the credential ID in default_value. At runtime the parameter key resolves to a credential object — read <key>.username and <key>.password, and use await <key>.otp() for authenticator, email, or SMS one-time codes. Never put literal secret values in code; scout credential fields with fill_credential_field.",
- credential_otp_authoring_guidance("<key>"),
]
+ if not _login_is_settled(settled_block_types):
+ guidance.extend(
+ [
+ "For saved credentials: bind the credential as a workflow parameter with workflow_parameter_type credential_id and the credential ID in default_value. At runtime the parameter key resolves to a credential object — read <key>.username and <key>.password, and use await <key>.otp() for authenticator, email, or SMS one-time codes. Never put literal secret values in code; scout credential fields with fill_credential_field.",
+ credential_otp_authoring_guidance("<key>"),
+ ]
+ )
+ return guidance
-def _code_only_browser_authoring_prompt() -> str:
- pending = "\n".join(f"- {detail}" for detail in _code_only_browser_pending_details())
+def _code_only_browser_credential_login_rules(settled_block_types: frozenset[str] | None = None) -> str:
+ """Credential bullets for the runtime-facts section, in their original order.
+
+ Two kinds of text live here. The accessor contract and `solve_captcha` are facts about the
+ code runtime — both exist in every code block's namespace, and this is the only place either
+ is described, so they render unconditionally. The step-by-step login procedure is authoring
+ steering and is withheld once a login block is settled, which is what stopped the model
+ rewriting a block the user asked to keep.
+ """
otp_guidance = credential_otp_authoring_guidance("<credential_key>")
+ login_procedure_withheld = _login_is_settled(settled_block_types)
+
+ accessor_fact = """- A `credential_id` workflow parameter resolves to a credential object with
+ `<key>.username`, `<key>.password`, and `await <key>.otp()` for one-time codes; scout fields with
+ `fill_credential_field`, never embed literal secrets."""
+
+ login_procedure = """- Credentialed login code must be idempotent. After `goto`, wait once on the two
+ states together, then branch without waiting again. Build each side to match only
+ visible elements, since `.first` takes the first match in DOM order rather than the
+ first to become visible, and a sign-in form that is present but hidden on an
+ already-authenticated page would otherwise capture the wait and hold it to the ceiling:
+ `login_form = page.locator("#login-form >> visible=true")`,
+ `authenticated_anchor = page.locator("#account-menu >> visible=true")`, then
+ `await login_form.or_(authenticated_anchor).first.wait_for(state="visible", timeout=90000)`,
+ then `if await login_form.is_visible():` to fill username/password. The generous window
+ covers a cold first load whose hydration lands well after Playwright's default, and the
+ combined wait still returns the instant either state appears. Waiting on the
+ login form by itself spends the entire timeout proving it is absent whenever the
+ session is already authenticated. After submit, use the scouting trajectory to reach and
+ observe a logged-in page anchor instead of relying only on `networkidle`."""
+
+ captcha_fact = """- After a credentialed login submit or navigation commit, call
+ `await solve_captcha(page)` before waiting for post-login anchors. This helper
+ owns any platform-managed verification challenge; do not locate or interact
+ with challenge controls directly."""
+
+ otp_procedure = (
+ """- After challenge handling, wait for either the observed one-time-code field or
+ a real authenticated-page anchor. If an OTP field appears, fill it with
+ `await <credential_key>.otp()`, submit it with the exact control the scout
+ demonstrated (its recorded selector and label, never a guessed one). """
+ + otp_guidance
+ + """
+ Do not treat disappearance of the login fields as proof of authentication."""
+ )
+
+ bullets = (
+ [accessor_fact, captcha_fact]
+ if login_procedure_withheld
+ else [accessor_fact, login_procedure, captcha_fact, otp_procedure]
+ )
+ return "\n".join(bullets) + "\n"
+
+
+def _code_only_browser_block_status_section(settled_block_types: frozenset[str] | None = None) -> str:
+ sections = []
+ details = _code_only_browser_pending_details(settled_block_types)
+ if details:
+ rendered = "\n".join(f"- {detail}" for detail in details)
+ sections.append(f"Code-native capabilities still pending plumbing:\n{rendered}")
+ if settled_block_types:
+ settled = ", ".join(f"`{block_type}`" for block_type in sorted(settled_block_types))
+ sections.append(f"Already saved in this workflow, inherited as-is and not pending conversion: {settled}.")
+ return "\n\n".join(sections)
+
+
+def _code_only_browser_authoring_prompt(settled_block_types: frozenset[str] | None = None) -> str:
+ pending = _code_only_browser_block_status_section(settled_block_types)
+ credential_login_rules = _code_only_browser_credential_login_rules(settled_block_types)
return f"""
ACTIVE BLOCK AUTHORING POLICY: CODE-ONLY BROWSER MODE
@@ -245,7 +342,6 @@ Rules:
`while_loop`, `send_email`, S3/Google Sheets helpers, file parsers, and triggers.
- {_code_only_browser_validation_guidance()}
-Code-native capabilities still pending plumbing:
{pending}
Runtime facts:
@@ -257,33 +353,7 @@ Runtime facts:
`wait_for_load_state`, `locator`, `get_by_role`, and locator text/count APIs.
- For browser reads, prefer visible anchors, locator text, block outputs, and
MCP/scout evidence gathered before authoring.
-- A `credential_id` workflow parameter resolves to a credential object with
- `<key>.username`, `<key>.password`, and `await <key>.otp()` for one-time codes; scout fields with
- `fill_credential_field`, never embed literal secrets.
-- Credentialed login code must be idempotent. After `goto`, wait once on the two
- states together, then branch without waiting again. Build each side to match only
- visible elements, since `.first` takes the first match in DOM order rather than the
- first to become visible, and a sign-in form that is present but hidden on an
- already-authenticated page would otherwise capture the wait and hold it to the ceiling:
- `login_form = page.locator("#login-form >> visible=true")`,
- `authenticated_anchor = page.locator("#account-menu >> visible=true")`, then
- `await login_form.or_(authenticated_anchor).first.wait_for(state="visible", timeout=90000)`,
- then `if await login_form.is_visible():` to fill username/password. The generous window
- covers a cold first load whose hydration lands well after Playwright's default, and the
- combined wait still returns the instant either state appears. Waiting on the
- login form by itself spends the entire timeout proving it is absent whenever the
- session is already authenticated. After submit, use the scouting trajectory to reach and
- observe a logged-in page anchor instead of relying only on `networkidle`.
-- After a credentialed login submit or navigation commit, call
- `await solve_captcha(page)` before waiting for post-login anchors. This helper
- owns any platform-managed verification challenge; do not locate or interact
- with challenge controls directly.
-- After challenge handling, wait for either the observed one-time-code field or
- a real authenticated-page anchor. If an OTP field appears, fill it with
- `await <credential_key>.otp()`, submit it with the exact control the scout
- demonstrated (its recorded selector and label, never a guessed one). {otp_guidance}
- Do not treat disappearance of the login fields as proof of authentication.
-- Return JSON-safe structured data plus visible evidence text for records, totals,
+{credential_login_rules}- Return JSON-safe structured data plus visible evidence text for records, totals,
confirmations, and identifiers.
- For an extraction-intent `code` block, derive a typed `extraction_schema` (named
fields with types) from the goal and the scouted page, carry it as
diff --git a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
index c5c41860f..0d04f2aa1 100644
--- a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
+++ b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
@@ -239,7 +239,8 @@ async def _get_block_schema_post_hook(
if _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.CODE_ONLY_BROWSER and block_type == "code":
ctx.code_only_code_schema_seen = True
data["code_only_note"] = _code_only_browser_unavailable_summary()
- data["code_only_guidance"] = _code_only_browser_schema_guidance()
+ settled_block_types = ctx.code_only_settled_block_types if isinstance(ctx, CopilotContext) else frozenset()
+ data["code_only_guidance"] = _code_only_browser_schema_guidance(settled_block_types)
data["download_claim_helper_contract"] = download_claim_helper_contract()
demonstrated = _demonstrated_step_facts(ctx)
if demonstrated:
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index 50d19e019..03de1c870 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -39,7 +39,7 @@ from skyvern.forge.sdk.copilot.completion_verification import (
gradeable_completion_criteria,
)
from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy, CopilotConfig
-from skyvern.forge.sdk.copilot.context import CodeAuthoringRepairContext
+from skyvern.forge.sdk.copilot.context import CodeAuthoringRepairContext, CopilotContext
from skyvern.forge.sdk.copilot.diagnosis_repair_contract import (
DiagnosisInput,
DiagnosisRepairContract,
@@ -2902,10 +2902,22 @@ class TestCredentialRefusalReachesAgent:
assert "redacted from the outbound client stream" not in prompt
def test_code_only_prompt_renders_policy_table_and_helper_validation_guidance(self) -> None:
- from skyvern.forge.sdk.copilot.agent import _build_system_prompt
-
config = CopilotConfig(block_authoring_policy=BlockAuthoringPolicy.CODE_ONLY_BROWSER)
- prompt = _build_system_prompt("", config=config)
+ prompt = agent_module._build_dynamic_system_prompt(tool_usage_guide="", config=config)(
+ SimpleNamespace(
+ context=CopilotContext(
+ organization_id="o_test",
+ workflow_id="w_test",
+ workflow_permanent_id="wpid_test",
+ workflow_yaml="",
+ browser_session_id=None,
+ stream=SimpleNamespace(),
+ workflow_copilot_chat_id="wcc_test",
+ request_policy=RequestPolicy(),
+ )
+ ),
+ None,
+ )
assert "ACTIVE BLOCK AUTHORING POLICY: CODE-ONLY BROWSER MODE" in prompt
assert "credential-typed code" in prompt
diff --git a/tests/unit/test_copilot_banned_block_policy.py b/tests/unit/test_copilot_banned_block_policy.py
index 373bd557b..a2f5a1cd3 100644
--- a/tests/unit/test_copilot_banned_block_policy.py
+++ b/tests/unit/test_copilot_banned_block_policy.py
@@ -21,12 +21,15 @@ from __future__ import annotations
import json
import re
import textwrap
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
import yaml
+from skyvern.forge.sdk.copilot.agent import _render_code_only_browser_authoring_prompt
from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy
+from skyvern.forge.sdk.copilot.context import CopilotContext
from skyvern.forge.sdk.copilot.request_policy import RequestPolicy
from skyvern.forge.sdk.copilot.tools import (
_COPILOT_BANNED_BLOCK_TYPES,
@@ -43,6 +46,7 @@ from skyvern.forge.sdk.copilot.tools.banned_blocks import (
CopilotBlockPolicyStatus,
_code_only_browser_authoring_prompt,
_code_only_browser_schema_guidance,
+ _extract_existing_code_only_pending_block_types,
)
from skyvern.forge.sdk.copilot.tools.mcp_hooks import _validate_block_pre_hook
from skyvern.schemas.runs import ProxyLocation
@@ -793,6 +797,154 @@ async def test_code_only_update_workflow_rejects_new_browser_block_with_policy_t
mock_span.assert_called_once_with("_update_workflow", [("login_step", "login")])
+def _copilot_ctx(workflow_yaml: str) -> CopilotContext:
+ return CopilotContext(
+ organization_id="org_test",
+ workflow_id="w_test",
+ workflow_permanent_id="wpid_test",
+ workflow_yaml=workflow_yaml,
+ browser_session_id=None,
+ stream=SimpleNamespace(), # type: ignore[arg-type]
+ workflow_copilot_chat_id="wcc_test",
+ request_policy=RequestPolicy(),
+ )
+
+
+def test_settled_gating_is_a_no_op_for_a_new_workflow() -> None:
+ # The contract is that an empty settled set withholds nothing, so the three ways of asking
+ # for "no settled blocks" render identically. Asserting the prompt's exact prose instead
+ # would fail on any unrelated edit to it, which is not what this change owns.
+ absent = _code_only_browser_authoring_prompt()
+ empty = _code_only_browser_authoring_prompt(frozenset())
+ unrelated = _code_only_browser_authoring_prompt(frozenset({"file_upload"}))
+
+ assert absent == empty
+ assert "Already saved in this workflow" not in absent
+ for withheld_only_when_settled in (
+ "Credentialed login code must be idempotent",
+ "wait for either the observed one-time-code field",
+ ):
+ assert withheld_only_when_settled in absent
+ # A settled type this prompt does not gate leaves the login guidance intact.
+ assert "Credentialed login code must be idempotent" in unrelated
+
+
+def test_code_only_authoring_prompt_for_new_workflow_keeps_every_pending_type() -> None:
+ prompt = _code_only_browser_authoring_prompt(frozenset())
+
+ assert "credential-typed code" in prompt
+ assert "download registration" in prompt
+ assert "file materialization" in prompt
+ assert "Already saved in this workflow" not in prompt
+
+
+def test_code_only_authoring_prompt_drops_conversion_guidance_for_settled_login() -> None:
+ settled = _extract_existing_code_only_pending_block_types(_yaml({"block_type": "login", "label": "login_step"}))
+
+ prompt = _code_only_browser_authoring_prompt(settled)
+
+ assert "credential-typed code" not in prompt
+ assert "credential_id workflow parameter" not in prompt
+ assert "download registration" in prompt
+ assert "file materialization" in prompt
+
+
+def test_code_only_authoring_prompt_marks_settled_login_as_inherited() -> None:
+ settled = _extract_existing_code_only_pending_block_types(_yaml({"block_type": "login", "label": "login_step"}))
+
+ prompt = _code_only_browser_authoring_prompt(settled)
+
+ assert "Already saved in this workflow, inherited as-is and not pending conversion: `login`." in prompt
+
+
+def test_code_only_authoring_prompt_drops_conversion_guidance_for_settled_file_download() -> None:
+ settled = _extract_existing_code_only_pending_block_types(
+ _yaml({"block_type": "file_download", "label": "download_step"})
+ )
+
+ prompt = _code_only_browser_authoring_prompt(settled)
+
+ assert "download registration" not in prompt
+ assert "credential-typed code" in prompt
+ assert "file materialization" in prompt
+
+
+def test_code_only_authoring_prompt_suppresses_pending_header_when_all_types_settled() -> None:
+ settled = _extract_existing_code_only_pending_block_types(
+ _yaml(
+ {"block_type": "login", "label": "login_step"},
+ {"block_type": "file_download", "label": "download_step"},
+ {"block_type": "file_upload", "label": "upload_step"},
+ )
+ )
+
+ prompt = _code_only_browser_authoring_prompt(settled)
+
+ assert "still pending plumbing" not in prompt
+ assert "credential-typed code" not in prompt
+ assert "download registration" not in prompt
+ assert "file materialization" not in prompt
+ assert (
+ "Already saved in this workflow, inherited as-is and not pending conversion: "
+ "`file_download`, `file_upload`, `login`." in prompt
+ )
+
+
+def test_settled_block_types_snapshot_ignores_mid_turn_workflow_writes() -> None:
+ ctx = _copilot_ctx("")
+ assert ctx.code_only_settled_block_types == frozenset()
+
+ ctx.workflow_yaml = _yaml({"block_type": "login", "label": "login_step"})
+
+ prompt = _render_code_only_browser_authoring_prompt(ctx)
+
+ assert ctx.code_only_settled_block_types == frozenset()
+ assert "credential-typed code" in prompt
+ assert "Already saved in this workflow" not in prompt
+
+
+def test_settled_block_types_snapshot_reads_the_turn_start_workflow() -> None:
+ ctx = _copilot_ctx(_yaml({"block_type": "login", "label": "login_step"}))
+
+ prompt = _render_code_only_browser_authoring_prompt(ctx)
+
+ assert ctx.code_only_settled_block_types == frozenset({"login"})
+ assert "credential-typed code" not in prompt
+ assert "Already saved in this workflow, inherited as-is and not pending conversion: `login`." in prompt
+
+
+def test_extract_existing_block_types_from_empty_workflow() -> None:
+ assert _extract_existing_code_only_pending_block_types(None) == frozenset()
+ assert _extract_existing_code_only_pending_block_types("") == frozenset()
+
+
+def test_extract_existing_block_types_from_malformed_yaml() -> None:
+ assert _extract_existing_code_only_pending_block_types("not valid yaml: {{{") == frozenset()
+
+
+def test_extract_existing_block_types_identifies_pending_block_types() -> None:
+ prior_yaml = _yaml(
+ {"block_type": "login", "label": "login_step"},
+ {"block_type": "file_download", "label": "download_step"},
+ {"block_type": "file_upload", "label": "upload_step"},
+ )
+
+ assert _extract_existing_code_only_pending_block_types(prior_yaml) == frozenset(
+ {"login", "file_download", "file_upload"}
+ )
+
+
+def test_extract_existing_block_types_ignores_blocks_outside_the_pending_set() -> None:
+ prior_yaml = _yaml(
+ {"block_type": "login", "label": "login_step"},
+ {"block_type": "navigation", "label": "nav_step"},
+ {"block_type": "code", "label": "code_step"},
+ {"block_type": "task", "label": "task_step"},
+ )
+
+ assert _extract_existing_code_only_pending_block_types(prior_yaml) == frozenset({"login"})
+
+
# ---------- Cross-layer sync guard ----------
@@ -831,3 +983,45 @@ def test_schema_guidance_keeps_post_login_wait_ceiling_model_owned() -> None:
assert 'authenticated_anchor.wait_for(state="visible", timeout=' not in authoring_prompt
assert "After the submit action, await that anchor" not in guidance
assert "and then\n wait for the authenticated anchor" not in authoring_prompt
+
+
+def test_schema_guidance_drops_credential_binding_when_login_is_settled() -> None:
+ from skyvern.forge.sdk.copilot.tools.banned_blocks import _code_only_browser_schema_guidance
+
+ new_workflow = " ".join(_code_only_browser_schema_guidance(frozenset()))
+ settled = " ".join(_code_only_browser_schema_guidance(frozenset({"login"})))
+
+ assert "workflow_parameter_type credential_id" in new_workflow
+ assert "workflow_parameter_type credential_id" not in settled
+ assert "bind the credential as a workflow parameter" not in settled
+ assert "Use one focused code block per durable browser goal" in settled
+
+
+def test_authoring_prompt_drops_login_procedure_when_login_is_settled() -> None:
+ settled = _code_only_browser_authoring_prompt(frozenset({"login"}))
+
+ # Step-by-step login authoring is steering; it is what drove the model to rewrite a
+ # settled block, so it is withheld.
+ assert "Credentialed login code must be idempotent" not in settled
+ assert "wait for either the observed one-time-code field" not in settled
+ assert "Return JSON-safe structured data" in settled
+
+
+def test_authoring_prompt_keeps_runtime_facts_when_login_is_settled() -> None:
+ settled = _code_only_browser_authoring_prompt(frozenset({"login"}))
+
+ # These describe the code runtime, not how to author a login, and this prompt is the only
+ # place either is described. Withholding them strands a helper that exists in the namespace.
+ assert "await solve_captcha(page)" in settled
+ assert "`credential_id` workflow parameter resolves to a credential object" in settled
+
+
+def test_authoring_prompt_keeps_credentialed_login_rules_for_a_new_login() -> None:
+ for settled_types in (frozenset(), frozenset({"file_download"})):
+ rendered = _code_only_browser_authoring_prompt(settled_types)
+ assert "Credentialed login code must be idempotent" in rendered
+ assert "await solve_captcha(page)" in rendered
+
+
+def test_settled_login_does_not_change_new_workflow_rendering() -> None:
+ assert _code_only_browser_authoring_prompt(frozenset()) == _code_only_browser_authoring_prompt(None)
diff --git a/tests/unit/test_copilot_cache_envelope.py b/tests/unit/test_copilot_cache_envelope.py
index a80fe8d54..0ddd21992 100644
--- a/tests/unit/test_copilot_cache_envelope.py
+++ b/tests/unit/test_copilot_cache_envelope.py
@@ -13,9 +13,12 @@ from skyvern.forge.sdk.copilot.cache_envelope import (
ExplicitCacheEnvelope,
build_explicit_cache_envelope,
)
+from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy
from skyvern.forge.sdk.copilot.context import CopilotContext
from skyvern.forge.sdk.copilot.request_policy import RequestPolicy
+_CODE_ONLY_HEADER = "ACTIVE BLOCK AUTHORING POLICY: CODE-ONLY BROWSER MODE"
+
@function_tool
def _first_tool(value: str) -> str:
@@ -175,3 +178,29 @@ def test_system_prompt_places_datetime_and_runtime_context_after_breakpoint(
assert base_prompt.dynamic_suffix in prompt.dynamic_suffix
assert "TURN SAFETY AND REQUEST CONTEXT" in prompt.dynamic_suffix
assert str(prompt) == prompt.stable_prefix + prompt.dynamic_suffix
+
+
+def test_code_only_authoring_policy_renders_into_the_dynamic_tail_only() -> None:
+ config = agent_module.CopilotConfig(block_authoring_policy=BlockAuthoringPolicy.CODE_ONLY_BROWSER)
+
+ base_prompt = agent_module._build_system_prompt(tool_usage_guide="tools", config=config)
+ prompt = agent_module._build_dynamic_system_prompt(tool_usage_guide="tools", config=config)(
+ SimpleNamespace(
+ context=CopilotContext(
+ organization_id="org_one",
+ workflow_id="workflow_one",
+ workflow_permanent_id="wpid_one",
+ workflow_yaml="",
+ browser_session_id=None,
+ stream=SimpleNamespace(), # type: ignore[arg-type]
+ workflow_copilot_chat_id="wcc_one",
+ request_policy=RequestPolicy(),
+ )
+ ),
+ None,
+ )
+
+ assert _CODE_ONLY_HEADER not in str(base_prompt)
+ assert isinstance(prompt, CacheableSystemInstructions)
+ assert _CODE_ONLY_HEADER not in prompt.stable_prefix
+ assert _CODE_ONLY_HEADER in prompt.dynamic_suffix