Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-12760: Ask for login credentials at turn start, not end-of-turn (#7629)
Andrew Neilson00000b832fc4
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2index 734c83f48..170d0e261 100644--- a/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2@@ -21,7 +21,7 @@ PRIMARY COMPLETION CRITERIA:```{{ reconciliation_criteria }}```{% else %}Classify the latest Workflow Copilot request. Return only JSON with keys:-testing_intent=require_test|skip_test|unspecified; authoring_intent=author_now|defer_authoring; credential_input_kind=none|raw_secret|credential_id|credential_name|website_stored_credential|placeholder; credential_refs; login_page_urls; requires_user_clarification; clarification_reason; completion_contract; completion_criteria; raw_secret_evidence; raw_secret_handling=none|block|redacted_draft.+testing_intent=require_test|skip_test|unspecified; authoring_intent=author_now|defer_authoring; credential_input_kind=none|raw_secret|credential_id|credential_name|website_stored_credential|placeholder; credential_refs; login_page_urls; login_intent; requires_user_clarification; clarification_reason; completion_contract; completion_criteria; raw_secret_evidence; raw_secret_handling=none|block|redacted_draft.terminal_action priority:- Separate authentication from the requested end state before writing completion_criteria. Authentication is a prefix@@ -51,6 +51,12 @@ credential_input_kind:- placeholder: the user asks to add credential/password/username fields but explicitly says there are no real credentials yet.- none: the request mentions a login workflow but does not provide, request, or refer to any credential material.+login_intent:+- true when the latest request explicitly asks the workflow to authenticate — sign in, log in, authenticate, or get past a login gate — as part of reaching the goal. "Log in and place an order" and a pure "log into <site>" are both true.+- false for an ordinary task with no authentication step, for a message that is essentially just a URL or a URL paired only with task language such as "scrape", "extract", "fill the form", "navigate to", or "go to", and for session-reuse phrasing such as "I'm already signed in" or "use my current browser session".+- false on a first-touch task phrase that merely implies an eventual login without explicitly asking to sign in or authenticate, for example "check my account balance" or "download my invoices". Let task or URL clarification happen first.+- Independent of credential_input_kind: decide it from whether authentication is required, not from whether the user supplied credential material. It is true for an explicit login request that names a saved credential and true for one that names none.+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.diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex 17d27c3af..378ed06ab 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -100,6 +100,7 @@ from skyvern.forge.sdk.copilot.context import (render_loaded_result_context_for_prompt,sanitize_global_llm_context_for_prompt,)+from skyvern.forge.sdk.copilot.credential_pause import preflight_credential_pausefrom skyvern.forge.sdk.copilot.data_write_defaults import default_data_write_continue_on_failurefrom skyvern.forge.sdk.copilot.enforcement import (BUILT_UNVERIFIED_REPAIR_INERT_TERMINAL_REASON,@@ -534,7 +535,31 @@ def _store_request_policy_on_context(chat_history_text=policy_inputs.chat_history_text,previous_user_message=policy_inputs.previous_user_message,)- turn_intent = build_turn_intent(+ ctx.turn_intent_classifier_result = turn_intent_classifier_result+ _derive_turn_intent_on_context(ctx, policy, policy_inputs)+ _reconcile_completion_criteria_on_context(ctx, policy, policy_inputs)+ ctx.request_policy = policy+ ctx.allow_untested_workflow_draft = policy.testing_intent == "skip_test"+ ctx.user_message = agent_user_message+ ctx.block_goal_main_goal = _build_block_goal_main_goal(+ user_message=agent_user_message,+ chat_history_text=policy_chat_history_text,+ global_llm_context=policy_inputs.global_llm_context,+ )+++def _derive_turn_intent_on_context(+ ctx: CopilotContext,+ policy: RequestPolicy,+ policy_inputs: RequestPolicyGuardrailInputs,+) -> None:+ """Snapshot ``policy``'s authority into ``ctx.turn_intent``.++ build_turn_intent hard-clears may_update_workflow/may_run_blocks for a CLARIFY+ policy, so any code that later un-blocks the policy must re-derive here or the+ turn keeps clarify-shaped authority.+ """+ ctx.turn_intent = build_turn_intent(user_message=policy_inputs.user_message,workflow_yaml=policy_inputs.workflow_yaml,chat_history=policy_inputs.chat_history_messages,@@ -544,19 +569,9 @@ 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,- classifier_result=turn_intent_classifier_result,+ classifier_result=ctx.turn_intent_classifier_result,fix_origin=policy_inputs.fix_origin,)- _reconcile_completion_criteria_on_context(ctx, policy, policy_inputs)- ctx.request_policy = policy- ctx.allow_untested_workflow_draft = policy.testing_intent == "skip_test"- ctx.user_message = agent_user_message- ctx.block_goal_main_goal = _build_block_goal_main_goal(- user_message=agent_user_message,- chat_history_text=policy_chat_history_text,- global_llm_context=policy_inputs.global_llm_context,- )- ctx.turn_intent = turn_intentdef _turn_intent_log_fields(intent: TurnIntent | None) -> dict[str, Any]:@@ -5272,12 +5287,18 @@ async def _run_copilot_turn_impl(prior_copilot_workflow_yaml=prior_copilot_workflow_yaml,)if request_policy is not None and request_policy_guardrail_result.output.tripwire_triggered:- return _build_request_policy_clarification_result(- request_policy,- prior_global_llm_context=global_llm_context,- prior_workflow_yaml=chat_request.workflow_yaml,- ctx=ctx,- )+ preflight_resolution = None+ if request_policy.clarification_reason == "login_credentials_unresolved":+ preflight_resolution = await preflight_credential_pause(ctx, stream, copilot_config)+ if preflight_resolution is not None:+ _derive_turn_intent_on_context(ctx, request_policy, policy_inputs)+ if preflight_resolution is None:+ return _build_request_policy_clarification_result(+ request_policy,+ prior_global_llm_context=global_llm_context,+ prior_workflow_yaml=chat_request.workflow_yaml,+ ctx=ctx,+ )if request_policy is None:raise CopilotRequestPolicyMissingError()diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.pyindex ff4a754ec..c00516a19 100644--- a/skyvern/forge/sdk/copilot/context.py+++ b/skyvern/forge/sdk/copilot/context.py@@ -130,7 +130,7 @@ if TYPE_CHECKING:from skyvern.forge.sdk.copilot.schema_incompatibility import SchemaIncompatibilityfrom skyvern.forge.sdk.copilot.turn_context import TurnContextPacketfrom skyvern.forge.sdk.copilot.turn_halt import TurnHalt- from skyvern.forge.sdk.copilot.turn_intent import TurnIntent+ from skyvern.forge.sdk.copilot.turn_intent import TurnIntent, TurnIntentClassifierResultfrom skyvern.forge.sdk.schemas.copilot_turn_outcome import TurnOutcome@@ -678,6 +678,9 @@ class CopilotContext(AgentContext):impose_synthesized_code_block: bool = Falsetarget_block_label: str | None = Noneturn_intent: TurnIntent | None = None+ # Retained so a policy mutated after the pre-flight credential pause can be+ # re-derived into an authority envelope without re-running the classifier.+ turn_intent_classifier_result: TurnIntentClassifierResult | None = Noneturn_context_packet: TurnContextPacket | None = Noneprior_turn_outcome: TurnOutcome | None = Nonelatest_diagnosis_repair_contract: DiagnosisRepairContract | None = Nonediff --git a/skyvern/forge/sdk/copilot/credential_pause.py b/skyvern/forge/sdk/copilot/credential_pause.pyindex e6f6f85c0..0d31fe8d6 100644--- a/skyvern/forge/sdk/copilot/credential_pause.py+++ b/skyvern/forge/sdk/copilot/credential_pause.py@@ -44,6 +44,8 @@ from skyvern.forge.sdk.schemas.workflow_copilot import (if TYPE_CHECKING:from agents.result import RunResultStreaming+ from skyvern.forge.sdk.copilot.context import CopilotContext+# Importing the routes package at module scope pulls in workflow_copilot.py -># agent.py -> enforcement.py, which imports this module -> circular import.from skyvern.forge.sdk.core.event_source_stream import EventSourceStream@@ -237,6 +239,9 @@ def credential_pause_reason(ctx: Any) -> str | None:"""policy = getattr(ctx, "request_policy", None)skip_test = isinstance(policy, RequestPolicy) and policy.testing_intent == "skip_test"+ if isinstance(policy, RequestPolicy) and policy.clarification_reason == "login_credentials_unresolved":+ return "login_credentials_unresolved"+if getattr(ctx, "last_run_skipped_unbound_credentials", False) and not skip_test:# A skip_test turn can still land here: _request_policy_allows_update_and_skip_run# (guardrails.py) skips the run for a skip_test-deferred credential, same as it@@ -393,18 +398,18 @@ async def _wait_for_credential_response(return None-async def maybe_credential_pause(+async def _run_credential_pause(ctx: Any,- result: RunResultStreaming,+ message: str,stream: EventSourceStream,copilot_config: CopilotConfig,-) -> list[dict[str, Any]] | None:- """Pause a finalizing turn that hit a typed mid-build credential ask.+) -> CredentialPauseResolution | None:+ """Send the credential card and wait for the user's decision.- Returns the resume messages to re-enter the loop with, or None to let- the caller finalize normally (kill-switch off, client can't render the- frame, already paused once this turn, no cache configured or not shared- across workers, client gone, or no typed signal fired).+ Returns the resolution, or None to let the caller proceed without one+ (kill-switch off, client can't render the frame, already paused once this+ turn, no cache configured or not shared across workers, client gone, no+ typed signal fired, or the wait timed out)."""if not credential_pause_would_fire(ctx, copilot_config):return None@@ -448,12 +453,6 @@ async def maybe_credential_pause(ex=_credential_pause_record_ttl(timeout_seconds),)- # Local import: same module-load-cycle reason as _assemble_resume_messages.- from skyvern.forge.sdk.copilot.enforcement import _parse_normalized_final_response-- parsed = _parse_normalized_final_response(result)- message = str((parsed or {}).get("user_response") or "")-await stream.send(WorkflowCopilotCredentialRequiredUpdate(type=WorkflowCopilotStreamMessageType.CREDENTIAL_REQUIRED,@@ -530,7 +529,7 @@ async def maybe_credential_pause(# last_test_ok=False; without clearing it, the resumed reply is intercepted# by the generic failed-test nudge instead of honoring the skip decision.ctx.last_test_ok = None- return _assemble_resume_messages(ctx, _SKIP_RESUME_TEXT)+ return resolutioncredential = resolution.credentialif credential is None:@@ -539,4 +538,70 @@ async def maybe_credential_pause(if isinstance(policy, RequestPolicy):_apply_connected_credential_to_policy(ctx, policy, credential)ctx.credential_pause_outcome = "connected"+ return resolution+++async def maybe_credential_pause(+ ctx: Any,+ result: RunResultStreaming,+ stream: EventSourceStream,+ copilot_config: CopilotConfig,+) -> list[dict[str, Any]] | None:+ """Pause a finalizing turn that hit a typed mid-build credential ask.++ Returns the resume messages to re-enter the loop with, or None to let the+ caller finalize normally.+ """+ if not credential_pause_would_fire(ctx, copilot_config):+ return None+ # Local import: same module-load-cycle reason as _assemble_resume_messages.+ from skyvern.forge.sdk.copilot.enforcement import _parse_normalized_final_response++ parsed = _parse_normalized_final_response(result)+ resolution = await _run_credential_pause(+ ctx,+ str((parsed or {}).get("user_response") or ""),+ stream,+ copilot_config,+ )+ if resolution is None:+ return None+ if resolution.action == "skip":+ return _assemble_resume_messages(ctx, _SKIP_RESUME_TEXT)+ credential = resolution.credential+ if credential is None:+ return Nonereturn _assemble_resume_messages(ctx, _connected_resume_text(credential))+++async def preflight_credential_pause(+ ctx: CopilotContext,+ stream: EventSourceStream,+ copilot_config: CopilotConfig,+) -> CredentialPauseResolution | None:+ """Ask for a credential before the agent loop starts, so no build precedes the ask.++ Both decisions clear the clarification block the request policy raised, so the+ caller falls through into a normal run instead of the terminal clarify; a+ declined turn must not keep a reason that would re-surface the card CTA.+ """+ policy = ctx.request_policy+ question = (policy.clarification_question or "") if policy is not None else ""+ resolution = await _run_credential_pause(ctx, question, stream, copilot_config)+ if resolution is None or policy is None:+ return resolution+ policy.user_response_policy = "proceed"+ if policy.authoring_intent == "defer_authoring":+ # Lifting the credential clarification must not also lift the user's+ # explicit defer_authoring hold. Re-apply it, overriding the run grant+ # a connect resolution stamped via _apply_connected_credential_to_policy.+ policy.allow_update_workflow = False+ policy.allow_run_blocks = False+ else:+ policy.allow_update_workflow = True+ policy.allow_run_blocks = True+ if resolution.action == "skip":+ policy.allow_missing_credentials_in_draft = True+ policy.requires_user_clarification = False+ policy.clarification_reason = "none"+ return resolutiondiff --git a/skyvern/forge/sdk/copilot/request_policy.py b/skyvern/forge/sdk/copilot/request_policy.pyindex ac56525c0..9fb6d28d6 100644--- a/skyvern/forge/sdk/copilot/request_policy.py+++ b/skyvern/forge/sdk/copilot/request_policy.py@@ -38,7 +38,11 @@ from skyvern.forge.sdk.copilot.secret_redaction import (redact_raw_secrets_for_prompt,)from skyvern.forge.sdk.copilot.tracing_setup import copilot_span-from skyvern.forge.sdk.copilot.workflow_credential_utils import workflow_credential_ids, workflow_credential_origins+from skyvern.forge.sdk.copilot.workflow_credential_utils import (+ URL_CANDIDATE_RE,+ workflow_credential_ids,+ workflow_credential_origins,+)from skyvern.forge.sdk.schemas.credentials import Credentialfrom skyvern.forge.sdk.schemas.workflow_copilot import (WorkflowCopilotChatHistoryMessage,@@ -69,6 +73,7 @@ _CLASSIFICATION_RESPONSE_FIELDS = {"credential_input_kind","credential_refs","login_page_urls",+ "login_intent","requires_user_clarification","completion_contract","completion_criteria",@@ -92,16 +97,26 @@ ClarificationReason = Literal["missing_conditional_condition","missing_target_context","workflow_credential_inputs_unbound",+ "login_credentials_unresolved",]RawSecretHandling = Literal["none", "block", "redacted_draft"]_VALID_CLARIFICATION_REASONS: frozenset[ClarificationReason] = frozenset(get_args(ClarificationReason))+# Only deterministic post-resolution code may mint these; a classifier emission would+# skip the concrete-target and credential-reachability checks the reason stands for.+_DETERMINISTIC_ONLY_CLARIFICATION_REASONS: frozenset[ClarificationReason] = frozenset({"login_credentials_unresolved"})# Gates guardrails.py's deferred-draft tool authority — narrower than the prompt set below.CREDENTIAL_DEFERRED_DRAFT_REASONS: frozenset[ClarificationReason] = frozenset({"workflow_credential_inputs_unbound", "credential_name_unresolved"})# Broader: any reason credential_prompt_reason() should surface an add-credential CTA for.CREDENTIAL_PROMPT_CLARIFICATION_REASONS: frozenset[ClarificationReason] = frozenset(- {"raw_secret", "credential_name_unresolved", "credential_invention_requested", "workflow_credential_inputs_unbound"}+ {+ "raw_secret",+ "credential_name_unresolved",+ "credential_invention_requested",+ "workflow_credential_inputs_unbound",+ "login_credentials_unresolved",+ })_PRE_RESOLUTION_CLARIFICATION_REASONS = {"credential_invention_requested",@@ -110,6 +125,11 @@ _PRE_RESOLUTION_CLARIFICATION_REASONS = {"missing_conditional_condition","missing_target_context",}+# A failed credential lookup under explicit login intent is the same condition+# login_credentials_unresolved names, so it may be upgraded; other planes may not.+_LOGIN_CREDENTIAL_OVERRIDABLE_REASONS: frozenset[ClarificationReason] = frozenset(+ {"none", "credential_name_unresolved"}+)_REASONS_OVERRIDDEN_BY_CREDENTIAL_REFS = {"ambiguous_loop_edit","invalid_conditional_container",@@ -132,6 +152,11 @@ _RAW_SECRET_QUESTION = ()_SAVED_CREDENTIAL_NAME_QUESTION_STABLE_PREFIX = "Which saved credential should I use? Please provide the exact credential name or a credential ID beginning with cred_."_SAVED_CREDENTIAL_NAME_QUESTION = f"{_SAVED_CREDENTIAL_NAME_QUESTION_STABLE_PREFIX} {_CREDENTIALS_UI_DIRECTIONS}"+_LOGIN_CREDENTIAL_QUESTION_STABLE_PREFIX = (+ "This request needs to sign in, and no saved credential for it is available yet. "+ "Please connect one, or reply with its exact saved credential name or a credential ID beginning with cred_."+)+_LOGIN_CREDENTIAL_QUESTION = f"{_LOGIN_CREDENTIAL_QUESTION_STABLE_PREFIX} {_CREDENTIALS_UI_DIRECTIONS}"_STORED_CREDENTIAL_URL_QUESTION_STABLE_PREFIX = ("Which website or login page should I use to look up the stored credential?")@@ -452,6 +477,7 @@ class RequestPolicy:credential_input_kind: str = "none"credential_refs: list[str] = field(default_factory=list)login_page_urls: list[str] = field(default_factory=list)+ login_intent: bool = Falserequires_user_clarification: bool = Falseallow_update_workflow: bool = Trueallow_run_blocks: bool = True@@ -491,6 +517,7 @@ class RequestPolicy:"testing_intent": self.testing_intent,"authoring_intent": self.authoring_intent,"credential_input_kind": self.credential_input_kind,+ "login_intent": self.login_intent,"clarification_reason": self.clarification_reason,"allow_update_workflow": self.allow_update_workflow,"allow_run_blocks": self.allow_run_blocks,@@ -872,7 +899,7 @@ def _verify_raw_secret_evidence(evidence: str | None, user_message: str) -> booldef _coerce_clarification_reason(value: Any) -> ClarificationReason:- if value in _VALID_CLARIFICATION_REASONS:+ if value in _VALID_CLARIFICATION_REASONS and value not in _DETERMINISTIC_ONLY_CLARIFICATION_REASONS:return cast(ClarificationReason, value)return "none"@@ -1810,6 +1837,7 @@ def _classification_from_raw(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 []),+ login_intent=bool(raw.get("login_intent")),requires_user_clarification=bool(raw.get("requires_user_clarification")),completion_contract=completion_contract or None,completion_criteria=completion_criteria,@@ -3882,6 +3910,43 @@ def _has_resolvable_credential_scope(policy: RequestPolicy) -> bool:return False+def _login_target_is_concrete(policy: RequestPolicy, user_message: str, workflow_yaml: str) -> bool:+ """A login phrase with no site, workflow, or URL yet has nothing to hold a credential.++ Asking there would demand a credential on first touch, before the task and URL+ clarification the user still owes.+ """+ return bool(+ policy.login_page_urls+ or workflow_yaml.strip()+ or policy.existing_workflow_credential_ids+ or URL_CANDIDATE_RE.search(user_message)+ )+++def _login_credentials_unresolved(policy: RequestPolicy, user_message: str, workflow_yaml: str) -> bool:+ """Login was explicitly requested against a concrete target and no credential is reachable.++ Evaluated after ``_resolve_credentials`` so an org/URL/name match counts as+ resolved; a user-named credential keeps ``credential_name_unresolved`` because+ naming one makes the lookup failure, not the absence of login credentials, the ask.+ """+ if not policy.login_intent or policy.raw_secret_detected:+ return False+ if policy.testing_intent == "skip_test" or policy.allow_missing_credentials_in_draft:+ return False+ if policy.clarification_reason not in _LOGIN_CREDENTIAL_OVERRIDABLE_REASONS:+ return False+ if not _login_target_is_concrete(policy, user_message, workflow_yaml):+ return False+ return not (+ policy.credential_refs+ or policy.resolved_credentials+ or policy.discovered_credentials+ or policy.existing_workflow_credential_ids+ )++def _prioritize_credential_clarification(policy: RequestPolicy) -> None:if policy.credential_input_kind not in ("credential_id", "credential_name"):return@@ -4301,6 +4366,12 @@ async def build_request_policy("I could not verify the requested credential metadata for this organization. Please provide a valid saved credential by exact name or a credential ID beginning with cred_.",)+ if _login_credentials_unresolved(policy, user_message, workflow_yaml):+ if policy.clarification_reason == "none":+ _block(policy, _LOGIN_CREDENTIAL_QUESTION, reason="login_credentials_unresolved")+ else:+ policy.clarification_reason = "login_credentials_unresolved"+if policy.authoring_intent == "defer_authoring":policy.allow_update_workflow = Falsepolicy.allow_run_blocks = Falsediff --git a/skyvern/forge/sdk/schemas/workflow_copilot.py b/skyvern/forge/sdk/schemas/workflow_copilot.pyindex ba10f1060..5f1b79881 100644--- a/skyvern/forge/sdk/schemas/workflow_copilot.py+++ b/skyvern/forge/sdk/schemas/workflow_copilot.py@@ -453,6 +453,7 @@ class WorkflowCopilotCredentialRequiredUpdate(BaseModel):"workflow_credential_inputs_unbound","missing_credential_run_failure","credential_deferred_draft",+ "login_credentials_unresolved",] = Field(..., description="Typed signal that triggered the pause")message: str = Field(..., description="The agent's explanatory text at the moment of pausing")login_page_urls: list[str] = Field(default_factory=list, description="Candidate login page URLs, if known")diff --git a/tests/unit/test_copilot_credential_pause.py b/tests/unit/test_copilot_credential_pause.pyindex 1a8719f71..4d0614c87 100644--- a/tests/unit/test_copilot_credential_pause.py+++ b/tests/unit/test_copilot_credential_pause.py@@ -36,6 +36,7 @@ from skyvern.forge import appfrom skyvern.forge.sdk.cache.base import NoopLockfrom skyvern.forge.sdk.copilot import credential_pause as credential_pause_modulefrom skyvern.forge.sdk.copilot import tools as tools_module+from skyvern.forge.sdk.copilot.agent import RequestPolicyGuardrailInputs, _derive_turn_intent_on_contextfrom skyvern.forge.sdk.copilot.config import CopilotConfigfrom skyvern.forge.sdk.copilot.context import CopilotContextfrom skyvern.forge.sdk.copilot.credential_pause import (@@ -46,6 +47,7 @@ from skyvern.forge.sdk.copilot.credential_pause import (credential_response_cache_key,encode_credential_response,maybe_credential_pause,+ preflight_credential_pause,resolve_credential_pause,)from skyvern.forge.sdk.copilot.diagnosis_repair_contract import (@@ -64,7 +66,11 @@ from skyvern.forge.sdk.copilot.enforcement import (_elapsed_run_seconds,run_with_enforcement,)-from skyvern.forge.sdk.copilot.request_policy import RequestPolicy, credential_prompt_reason+from skyvern.forge.sdk.copilot.request_policy import (+ CREDENTIAL_PROMPT_CLARIFICATION_REASONS,+ RequestPolicy,+ credential_prompt_reason,+)from skyvern.forge.sdk.copilot.turn_intent import TurnIntent, TurnIntentAuthority, TurnIntentModefrom skyvern.forge.sdk.routes.workflow_copilot import (WorkflowCopilotCredentialResponseRequest,@@ -1833,3 +1839,228 @@ async def test_non_shared_cache_never_pauses(monkeypatch: pytest.MonkeyPatch) ->def test_credential_pause_resolution_defaults_credential_to_none() -> None:resolution = CredentialPauseResolution(action="skip")assert resolution.credential is None+++def _blocked_login_policy() -> RequestPolicy:+ """A policy shaped the way build_request_policy leaves an unresolved login ask."""+ return RequestPolicy(+ login_intent=True,+ clarification_reason="login_credentials_unresolved",+ clarification_question="Connect a saved credential to sign in.",+ requires_user_clarification=True,+ user_response_policy="ask_clarification",+ allow_update_workflow=False,+ allow_run_blocks=False,+ )+++def _preflight_ctx() -> CopilotContext:+ ctx = make_copilot_context()+ ctx.organization_id = "org-1"+ ctx.turn_id = "turn-1"+ ctx.workflow_copilot_chat_id = "chat-1"+ ctx.client_supports_credential_pause = True+ ctx.request_policy = _blocked_login_policy()+ return ctx+++def test_reason_fires_on_unresolved_login_credentials() -> None:+ ctx = make_copilot_context()+ ctx.request_policy = _blocked_login_policy()++ assert credential_pause_module.credential_pause_reason(ctx) == "login_credentials_unresolved"+++def test_reason_does_not_fire_for_a_login_ask_that_resolved_to_a_credential() -> None:+ ctx = make_copilot_context()+ ctx.request_policy = RequestPolicy(login_intent=True, clarification_reason="none")++ assert credential_pause_module.credential_pause_reason(ctx) is None+++async def test_preflight_connect_binds_the_credential_and_clears_the_clarification_block(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ ctx = _preflight_ctx()+ cache = _FakeCache()+ cache.store[credential_response_cache_key("org-1", "chat-1", "turn-1")] = encode_credential_response(+ "connected", "cred_1"+ )+ monkeypatch.setattr(credential_pause_module.app._inst, "CACHE", cache, raising=False)+ credential = _make_credential()+ monkeypatch.setattr(+ credential_pause_module.app,+ "DATABASE",+ SimpleNamespace(credentials=SimpleNamespace(get_credentials_by_ids=AsyncMock(return_value=[credential]))),+ )+ monkeypatch.setattr(credential_pause_module, "CREDENTIAL_RESPONSE_POLL_SECONDS", 0.01)+ stream = _make_stream()+ config = CopilotConfig(credential_pause_enabled=True, credential_pause_timeout_seconds=5)++ resolution = await preflight_credential_pause(ctx, stream, config)++ assert resolution is not None and resolution.action == "connected"+ assert ctx.credential_pause_outcome == "connected"+ policy = ctx.request_policy+ assert policy.resolved_credentials == [credential]+ assert policy.allow_run_blocks is True+ assert policy.clarification_reason == "none"+ assert policy.user_response_policy == "proceed"+ assert policy.allow_update_workflow is True+ assert policy.requires_user_clarification is False+ sent_types = [call.args[0].type for call in stream.send.await_args_list]+ assert sent_types == [WorkflowCopilotStreamMessageType.CREDENTIAL_REQUIRED]+++async def test_preflight_connect_preserves_an_explicit_defer_authoring_hold(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ ctx = _preflight_ctx()+ ctx.request_policy.authoring_intent = "defer_authoring"+ cache = _FakeCache()+ cache.store[credential_response_cache_key("org-1", "chat-1", "turn-1")] = encode_credential_response(+ "connected", "cred_1"+ )+ monkeypatch.setattr(credential_pause_module.app._inst, "CACHE", cache, raising=False)+ credential = _make_credential()+ monkeypatch.setattr(+ credential_pause_module.app,+ "DATABASE",+ SimpleNamespace(credentials=SimpleNamespace(get_credentials_by_ids=AsyncMock(return_value=[credential]))),+ )+ monkeypatch.setattr(credential_pause_module, "CREDENTIAL_RESPONSE_POLL_SECONDS", 0.01)+ config = CopilotConfig(credential_pause_enabled=True, credential_pause_timeout_seconds=5)++ resolution = await preflight_credential_pause(ctx, _make_stream(), config)++ assert resolution is not None and resolution.action == "connected"+ policy = ctx.request_policy+ assert policy.user_response_policy == "proceed"+ assert policy.resolved_credentials == [credential]+ assert policy.allow_update_workflow is False+ assert policy.allow_run_blocks is False+++def _preflight_policy_inputs() -> RequestPolicyGuardrailInputs:+ return RequestPolicyGuardrailInputs(+ user_message="Log in to https://portal.example.com/login and download the invoices.",+ workflow_yaml="",+ chat_history_text="",+ chat_history_messages=[],+ global_llm_context="",+ organization_id="org-1",+ request_policy_handler=None,+ turn_intent_handler=None,+ )+++async def test_preflight_connect_re_derives_run_authority_onto_the_turn_intent(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ ctx = _preflight_ctx()+ policy_inputs = _preflight_policy_inputs()+ _derive_turn_intent_on_context(ctx, ctx.request_policy, policy_inputs)+ assert ctx.turn_intent.mode is TurnIntentMode.CLARIFY+ assert ctx.turn_intent.authority.may_update_workflow is False++ cache = _FakeCache()+ cache.store[credential_response_cache_key("org-1", "chat-1", "turn-1")] = encode_credential_response(+ "connected", "cred_1"+ )+ monkeypatch.setattr(credential_pause_module.app._inst, "CACHE", cache, raising=False)+ monkeypatch.setattr(+ credential_pause_module.app,+ "DATABASE",+ SimpleNamespace(+ credentials=SimpleNamespace(get_credentials_by_ids=AsyncMock(return_value=[_make_credential()]))+ ),+ )+ monkeypatch.setattr(credential_pause_module, "CREDENTIAL_RESPONSE_POLL_SECONDS", 0.01)+ config = CopilotConfig(credential_pause_enabled=True, credential_pause_timeout_seconds=5)++ resolution = await preflight_credential_pause(ctx, _make_stream(), config)+ assert resolution is not None and resolution.action == "connected"+ _derive_turn_intent_on_context(ctx, ctx.request_policy, policy_inputs)++ assert ctx.request_policy.clarification_reason == "none"+ assert ctx.turn_intent.mode is not TurnIntentMode.CLARIFY+ assert ctx.turn_intent.authority.may_update_workflow is True+ assert ctx.turn_intent.authority.may_run_blocks is True+++async def test_preflight_skip_clears_the_reason_so_the_declined_turn_shows_no_card_cta(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A stale login_credentials_unresolved would still route through+ CREDENTIAL_PROMPT_CLARIFICATION_REASONS and stamp a credential CTA on the+ reply for a turn the user explicitly declined."""+ ctx = _preflight_ctx()+ cache = _FakeCache()+ cache.store[credential_response_cache_key("org-1", "chat-1", "turn-1")] = encode_credential_response("skip", None)+ monkeypatch.setattr(credential_pause_module.app._inst, "CACHE", cache, raising=False)+ monkeypatch.setattr(credential_pause_module, "CREDENTIAL_RESPONSE_POLL_SECONDS", 0.01)+ stream = _make_stream()+ config = CopilotConfig(credential_pause_enabled=True, credential_pause_timeout_seconds=5)++ resolution = await preflight_credential_pause(ctx, stream, config)++ assert resolution is not None and resolution.action == "skip"+ policy = ctx.request_policy+ assert policy.clarification_reason == "none"+ assert policy.clarification_reason not in CREDENTIAL_PROMPT_CLARIFICATION_REASONS+ assert policy.requires_user_clarification is False+ assert policy.allow_missing_credentials_in_draft is True+ assert policy.user_response_policy == "proceed"+ assert policy.allow_update_workflow is True+++async def test_preflight_timeout_leaves_the_clarification_block_for_the_terminal_clarify(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ ctx = _preflight_ctx()+ monkeypatch.setattr(credential_pause_module.app._inst, "CACHE", _FakeCache(), raising=False)+ monkeypatch.setattr(credential_pause_module, "CREDENTIAL_RESPONSE_POLL_SECONDS", 0.01)+ stream = _make_stream()+ config = CopilotConfig(credential_pause_enabled=True, credential_pause_timeout_seconds=0)++ resolution = await preflight_credential_pause(ctx, stream, config)++ assert resolution is None+ assert ctx.credential_pause_outcome == "timeout"+ policy = ctx.request_policy+ assert policy.user_response_policy == "ask_clarification"+ assert policy.clarification_reason == "login_credentials_unresolved"+++async def test_preflight_declines_when_the_client_cannot_render_the_card() -> None:+ ctx = _preflight_ctx()+ ctx.client_supports_credential_pause = False+ stream = _make_stream()+ config = CopilotConfig(credential_pause_enabled=True, credential_pause_timeout_seconds=5)++ assert await preflight_credential_pause(ctx, stream, config) is None+ stream.send.assert_not_awaited()+++async def test_preflight_consumes_the_one_pause_per_turn_latch(monkeypatch: pytest.MonkeyPatch) -> None:+ ctx = _preflight_ctx()+ cache = _FakeCache()+ cache.store[credential_response_cache_key("org-1", "chat-1", "turn-1")] = encode_credential_response("skip", None)+ monkeypatch.setattr(credential_pause_module.app._inst, "CACHE", cache, raising=False)+ monkeypatch.setattr(credential_pause_module, "CREDENTIAL_RESPONSE_POLL_SECONDS", 0.01)+ stream = _make_stream()+ config = CopilotConfig(credential_pause_enabled=True, credential_pause_timeout_seconds=5)++ await preflight_credential_pause(ctx, stream, config)+ assert ctx.credential_pause_used is True++ ctx.request_policy = _blocked_login_policy()+ assert await maybe_credential_pause(ctx, _fake_result(), stream, config) is None+ assert len(stream.send.await_args_list) == 1diff --git a/tests/unit/test_copilot_request_policy_prompt.py b/tests/unit/test_copilot_request_policy_prompt.pyindex b59e32e3a..ada6e8853 100644--- a/tests/unit/test_copilot_request_policy_prompt.py+++ b/tests/unit/test_copilot_request_policy_prompt.py@@ -737,3 +737,39 @@ class TestClassifierFallbackCompletionCriteria:},)]+++class TestLoginIntentSignal:+ def test_prompt_declares_login_intent_in_the_output_contract(self) -> None:+ rendered = _render()+ assert "login_intent" in rendered++ def test_prompt_keeps_login_intent_orthogonal_to_credential_input_kind(self) -> None:+ rendered = _render()+ assert "Independent of credential_input_kind" in rendered++ @pytest.mark.asyncio+ async def test_classifier_login_intent_is_carried_onto_the_policy(self) -> None:+ async def stub(prompt: str, prompt_name: str) -> dict[str, object]:+ return {"credential_input_kind": "none", "login_intent": True}++ policy = await _classify_request(+ user_message="Log in to the billing portal and export the statement.",+ workflow_yaml="",+ chat_history=[],+ global_llm_context="",+ handler=stub,+ )++ assert policy.login_intent is True++ @pytest.mark.asyncio+ async def test_absent_login_intent_defaults_to_false(self) -> None:+ policy = await _classify("Build a workflow that scrapes the product table.", kind="none")++ assert policy.login_intent is False++ def test_login_intent_is_stamped_in_turn_telemetry(self) -> None:+ """QA discards runs whose request_policy span carries no typed signal."""+ assert request_policy_module.RequestPolicy(login_intent=True).to_trace_data()["login_intent"] is True+ assert request_policy_module.RequestPolicy().to_trace_data()["login_intent"] is Falsediff --git a/tests/unit/test_copilot_request_policy_workflow_credentials.py b/tests/unit/test_copilot_request_policy_workflow_credentials.pyindex e1d5e5e49..337cb7031 100644--- a/tests/unit/test_copilot_request_policy_workflow_credentials.py+++ b/tests/unit/test_copilot_request_policy_workflow_credentials.py@@ -12,6 +12,7 @@ from skyvern.forge.sdk.copilot.request_policy import (CREDENTIAL_DEFERRED_DRAFT_REASONS,CREDENTIAL_PROMPT_CLARIFICATION_REASONS,RequestPolicy,+ _classification_from_raw,_workflow_credential_inputs_unbound,build_request_policy,credential_prompt_reason,@@ -352,6 +353,7 @@ def test_credential_prompt_clarification_reasons_membership() -> None:"credential_name_unresolved","credential_invention_requested","workflow_credential_inputs_unbound",+ "login_credentials_unresolved",}@@ -454,6 +456,7 @@ async def _build_with_forced_classifier(org_credentials: list[SimpleNamespace],get_credentials: AsyncMock | None = None,get_credentials_by_ids: AsyncMock | None = None,+ workflow_yaml: str = "",) -> RequestPolicy:load_mock = get_credentials or AsyncMock(return_value=org_credentials)by_ids_mock = get_credentials_by_ids or AsyncMock(return_value=[])@@ -467,7 +470,7 @@ async def _build_with_forced_classifier():return await build_request_policy(user_message=user_message,- workflow_yaml="",+ workflow_yaml=workflow_yaml,chat_history=[],global_llm_context="",organization_id="o_test",@@ -681,3 +684,199 @@ async def test_success_raw_secret_blocks_name_scan_before_loading_credentials()assert policy.resolved_credentials == []load_mock.assert_not_awaited()+++async def test_login_intent_with_no_reachable_credential_asks_before_any_build() -> None:+ policy = await _build_with_forced_classifier(+ user_message="Log in to https://portal.example.com/login and download this month's invoices.",+ classifier_policy=RequestPolicy(+ login_intent=True,+ credential_input_kind="website_stored_credential",+ login_page_urls=["https://portal.example.com/login"],+ classifier_status="success",+ ),+ org_credentials=[],+ )++ assert policy.clarification_reason == "login_credentials_unresolved"+ assert policy.user_response_policy == "ask_clarification"+ assert policy.requires_user_clarification is True+ assert policy.allow_run_blocks is False+ assert policy.allow_update_workflow is False+ assert policy.resolved_credentials == []+++async def test_first_touch_bare_login_task_without_a_concrete_target_draws_no_credential_ask() -> None:+ policy = await _build_with_forced_classifier(+ user_message="Let's log in to the webpage and export the latest statement.",+ classifier_policy=RequestPolicy(login_intent=True, classifier_status="success"),+ org_credentials=[],+ )++ assert policy.clarification_reason != "login_credentials_unresolved"+ assert policy.user_response_policy == "proceed"+ assert policy.clarification_question is None+++async def test_login_intent_without_credential_phrasing_asks_once_a_url_names_the_target() -> None:+ policy = await _build_with_forced_classifier(+ user_message="Sign in to https://billing.example.com and export the statement.",+ classifier_policy=RequestPolicy(login_intent=True, classifier_status="success"),+ org_credentials=[],+ )++ assert policy.clarification_reason == "login_credentials_unresolved"+ assert policy.user_response_policy == "ask_clarification"+ assert policy.clarification_question is not None+++async def test_login_intent_on_an_existing_workflow_asks_without_a_url_in_the_message() -> None:+ policy = await _build_with_forced_classifier(+ user_message="Sign in to the billing portal and export the statement.",+ classifier_policy=RequestPolicy(login_intent=True, classifier_status="success"),+ org_credentials=[],+ workflow_yaml=_yaml(+ """+ title: Billing export+ workflow_definition:+ blocks:+ - block_type: task+ label: export+ """+ ),+ )++ assert policy.clarification_reason == "login_credentials_unresolved"+ assert policy.user_response_policy == "ask_clarification"+++async def test_classifier_emitted_login_credentials_unresolved_is_not_trusted() -> None:+ policy = _classification_from_raw(+ {+ "testing_intent": "unspecified",+ "credential_input_kind": "none",+ "credential_refs": [],+ "login_page_urls": [],+ "requires_user_clarification": True,+ "clarification_reason": "login_credentials_unresolved",+ "completion_contract": None,+ }+ )++ assert policy.clarification_reason == "none"+++async def test_login_intent_satisfied_by_matching_org_credential_draws_no_ask() -> None:+ credential = _cred("portal-cred", "cred_url", tested_url="https://portal.example.com/login")+ policy = await _build_with_forced_classifier(+ user_message="Log in to https://portal.example.com/login and download this month's invoices.",+ classifier_policy=RequestPolicy(+ login_intent=True,+ credential_input_kind="website_stored_credential",+ login_page_urls=["https://portal.example.com/login"],+ classifier_status="success",+ ),+ org_credentials=[credential],+ )++ assert [c.credential_id for c in policy.resolved_credentials] == ["cred_url"]+ assert policy.clarification_reason != "login_credentials_unresolved"+ assert policy.user_response_policy == "proceed"+ assert policy.clarification_question is None+++async def test_login_intent_satisfied_by_a_workflow_bound_credential_draws_no_ask() -> None:+ yaml = _yaml(+ """+ title: example+ workflow_definition:+ parameters:+ - key: portal_login+ parameter_type: credential+ credential_id: cred_bound+ blocks: []+ """+ )+ policy = await _build_with_forced_classifier(+ user_message="Sign in to the portal and export the statement.",+ classifier_policy=RequestPolicy(login_intent=True, classifier_status="success"),+ org_credentials=[],+ workflow_yaml=yaml,+ )++ assert policy.existing_workflow_credential_ids == ["cred_bound"]+ assert policy.clarification_reason != "login_credentials_unresolved"+ assert policy.user_response_policy == "proceed"+++async def test_a_non_login_request_never_draws_the_login_credential_ask() -> None:+ policy = await _build_with_forced_classifier(+ user_message="Go to https://portal.example.com/login and tell me what fields the form has.",+ classifier_policy=RequestPolicy(login_intent=False, classifier_status="success"),+ org_credentials=[],+ )++ assert policy.clarification_reason != "login_credentials_unresolved"+ assert policy.user_response_policy == "proceed"+ assert policy.clarification_question is None+++async def test_a_user_named_credential_that_misses_keeps_the_name_unresolved_ask() -> None:+ policy = await _build_with_forced_classifier(+ user_message="Log in using my saved credential named portal-login.",+ classifier_policy=RequestPolicy(+ login_intent=True,+ credential_input_kind="credential_name",+ credential_refs=["portal-login"],+ classifier_status="success",+ ),+ org_credentials=[_cred("something-else", "cred_other")],+ )++ assert policy.clarification_reason == "credential_name_unresolved"+++async def test_an_explicit_draft_only_login_request_is_not_interrupted_for_a_credential() -> None:+ policy = await _build_with_forced_classifier(+ user_message="Draft a workflow that logs in to the portal. Don't run it, I'll test it myself.",+ classifier_policy=RequestPolicy(+ login_intent=True,+ testing_intent="skip_test",+ classifier_status="success",+ ),+ org_credentials=[],+ )++ assert policy.clarification_reason != "login_credentials_unresolved"+ assert policy.allow_missing_credentials_in_draft is True+++async def test_a_pasted_secret_under_login_intent_keeps_the_raw_secret_refusal() -> None:+ policy = await _build_with_forced_classifier(+ user_message="Log in with password hunter2",+ classifier_policy=RequestPolicy(+ login_intent=True,+ credential_input_kind="raw_secret",+ raw_secret_detected=True,+ classifier_status="success",+ ),+ org_credentials=[],+ )++ assert policy.clarification_reason == "raw_secret"+++def test_login_credentials_unresolved_surfaces_a_prompt_but_grants_no_deferred_draft_authority() -> None:+ assert "login_credentials_unresolved" in CREDENTIAL_PROMPT_CLARIFICATION_REASONS+ assert "login_credentials_unresolved" not in CREDENTIAL_DEFERRED_DRAFT_REASONS