Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Keep a credential named earlier in the conversation approved when the user confirms (SKY-12812) (#7648)
Andrew Neilson3c8fb0a849d5
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex 378ed06ab..7850e27d0 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -96,7 +96,9 @@ from skyvern.forge.sdk.copilot.context import (ResponseType,StructuredContext,TurnNarrativePayload,+ adopt_model_authored_context,finalize_discovery_counter_in_global_llm_context,+ record_approved_credentials_in_global_llm_context,render_loaded_result_context_for_prompt,sanitize_global_llm_context_for_prompt,)@@ -1743,7 +1745,9 @@ def _make_agent_result(normal translate-result, missing-SDK fallback, unexpected-error fallback)."""final_context = (- finalize_discovery_counter_in_global_llm_context(ctx, global_llm_context)+ record_approved_credentials_in_global_llm_context(+ ctx, finalize_discovery_counter_in_global_llm_context(ctx, global_llm_context)+ )if ctx is not Noneelse global_llm_context)@@ -3968,15 +3972,7 @@ async def _translate_to_agent_result(last_workflow = Nonelast_workflow_yaml = None- llm_context_raw = action_data.get("global_llm_context")- structured = StructuredContext.from_json_str(global_llm_context)- if isinstance(llm_context_raw, dict):- try:- structured = StructuredContext.model_validate(llm_context_raw)- except Exception:- pass- elif isinstance(llm_context_raw, str):- structured = StructuredContext.from_json_str(llm_context_raw)+ structured = adopt_model_authored_context(global_llm_context, action_data.get("global_llm_context"))structured.merge_turn_summary(ctx.tool_activity)enriched_context = structured.to_json_str()workflow_attempted = ctx.has_genuine_workflow_attempt()diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.pyindex c00516a19..0327026aa 100644--- a/skyvern/forge/sdk/copilot/context.py+++ b/skyvern/forge/sdk/copilot/context.py@@ -151,6 +151,10 @@ class CredentialCheck(BaseModel):found: bool = False+class ApprovedCredential(BaseModel):+ credential_id: str++class ObservedPage(BaseModel):"""Compact cross-turn record of a page the agent scouted (SKY-10562).@@ -245,6 +249,7 @@ class StructuredContext(BaseModel):urls_visited: list[UrlVisit] = Field(default_factory=list)fields_filled: list[FieldFilled] = Field(default_factory=list)credentials_checked: list[CredentialCheck] = Field(default_factory=list)+ approved_credentials: list[ApprovedCredential] = Field(default_factory=list)decisions_made: list[str] = Field(default_factory=list)workflow_state: str = ""# Per-chat discovery budget. Survives turn boundaries via@@ -588,6 +593,50 @@ def finalize_discovery_counter_in_global_llm_context(ctx: Any, raw_context: strreturn sc.to_json_str()+_MAX_APPROVED_CREDENTIALS = 20+++def record_approved_credentials_in_global_llm_context(ctx: CopilotContext, raw_context: str | None) -> str | None:+ """Persist resolved credentials as durable cross-turn approval. Records only from+ resolved_credentials, never discovered_credentials, so ADR-0002's run/draft split+ holds by construction.+ """+ policy = ctx.request_policy+ if policy is None or not policy.resolved_credentials:+ return raw_context+ sc = StructuredContext.from_json_str(raw_context)+ existing_ids = {record.credential_id for record in sc.approved_credentials}+ for credential in policy.resolved_credentials:+ if credential.credential_id in existing_ids:+ continue+ sc.approved_credentials.append(ApprovedCredential(credential_id=credential.credential_id))+ existing_ids.add(credential.credential_id)+ if len(sc.approved_credentials) > _MAX_APPROVED_CREDENTIALS:+ sc.approved_credentials = sc.approved_credentials[-_MAX_APPROVED_CREDENTIALS:]+ return sc.to_json_str()+++def adopt_model_authored_context(trusted_raw: str | None, model_raw: object) -> StructuredContext:+ """Take the model's context but keep `approved_credentials` server-owned.++ Approval is recorded only from server-resolved credentials; an entry the model+ supplied would be promoted into `resolved_credentials` on the next turn and clear+ the unapproved-credential gate for a credential the user never named. Membership+ of the org is not evidence the user named it.+ """+ trusted = StructuredContext.from_json_str(trusted_raw)+ structured = trusted+ if isinstance(model_raw, dict):+ try:+ structured = StructuredContext.model_validate(model_raw)+ except Exception:+ structured = trusted+ elif isinstance(model_raw, str):+ structured = StructuredContext.from_json_str(model_raw)+ structured.approved_credentials = list(trusted.approved_credentials)+ return structured++@dataclassclass AgentResult:user_response: strdiff --git a/skyvern/forge/sdk/copilot/request_policy.py b/skyvern/forge/sdk/copilot/request_policy.pyindex 9fb6d28d6..e47b1c927 100644--- a/skyvern/forge/sdk/copilot/request_policy.py+++ b/skyvern/forge/sdk/copilot/request_policy.py@@ -3989,6 +3989,35 @@ async def _seed_discovered_credentials()+def _prior_approved_credential_ids_from_context(global_llm_context: str) -> set[str]:+ structured = StructuredContext.from_json_str(global_llm_context)+ return {+ record.credential_id for record in structured.approved_credentials if record.credential_id.startswith("cred_")+ }+++async def _seed_prior_approved_credentials(+ policy: RequestPolicy,+ *,+ organization_id: str,+ global_llm_context: str,+) -> None:+ prior_ids = _prior_approved_credential_ids_from_context(global_llm_context)+ carry_ids = sorted(prior_ids - {credential.credential_id for credential in policy.resolved_credentials})+ if not carry_ids:+ return+ carried = await app.DATABASE.credentials.get_credentials_by_ids(carry_ids, organization_id=organization_id)+ if not carried:+ return+ policy.resolved_credentials = list(policy.resolved_credentials) + carried+ LOG.info(+ "request-policy prior approved credentials carried",+ organization_id=organization_id,+ carried_credential_ids=[credential.credential_id for credential in carried],+ carried_count=len(carried),+ )++def _last_assistant_message_was_saved_credential_question(chat_history: list[WorkflowCopilotChatHistoryMessage],) -> bool:@@ -4366,6 +4395,21 @@ 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_.",)+ # Seeded before the login-credential reachability check so a credential approved on an+ # earlier turn counts as reachable and a confirmation-only turn does not re-ask for it.+ try:+ await _seed_prior_approved_credentials(+ policy,+ organization_id=organization_id,+ global_llm_context=global_llm_context,+ )+ except Exception:+ LOG.warning(+ "request-policy prior approved credential seeding failed",+ organization_id=organization_id,+ exc_info=True,+ )+if _login_credentials_unresolved(policy, user_message, workflow_yaml):if policy.clarification_reason == "none":_block(policy, _LOGIN_CREDENTIAL_QUESTION, reason="login_credentials_unresolved")diff --git a/skyvern/forge/sdk/routes/workflow_copilot.py b/skyvern/forge/sdk/routes/workflow_copilot.pyindex d599c2afa..57b7709c1 100644--- a/skyvern/forge/sdk/routes/workflow_copilot.py+++ b/skyvern/forge/sdk/routes/workflow_copilot.py@@ -39,6 +39,7 @@ from skyvern.forge.sdk.copilot.context import (AgentResult,ProposalDisposition,TurnNarrativePayload,+ adopt_model_authored_context,render_loaded_result_context_for_prompt,sanitize_global_llm_context_for_prompt,)@@ -1194,9 +1195,11 @@ async def copilot_call_llm(action_type=action_type,)- global_llm_context = action_data.get("global_llm_context")- if global_llm_context is not None:- global_llm_context = sanitize_global_llm_context_for_prompt(str(global_llm_context))+ model_authored_context = action_data.get("global_llm_context")+ if model_authored_context is not None:+ global_llm_context = sanitize_global_llm_context_for_prompt(+ adopt_model_authored_context(global_llm_context, model_authored_context).to_json_str()+ )if action_type == "REPLACE_WORKFLOW":llm_workflow_yaml = default_data_write_continue_on_failure(diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.pyindex 2a70dc841..84eb17633 100644--- a/tests/unit/test_copilot_agent_helpers.py+++ b/tests/unit/test_copilot_agent_helpers.py@@ -100,6 +100,7 @@ from skyvern.forge.sdk.copilot.tools.completion import (_completion_verification_criteria,_maybe_run_completion_verification,)+from skyvern.forge.sdk.copilot.tools.credentials import _credential_run_approval_errorfrom skyvern.forge.sdk.copilot.turn_context import TranscriptContext, TurnContextOmission, TurnContextPacketfrom skyvern.forge.sdk.copilot.turn_halt import (CopilotTurnHalt,@@ -5411,6 +5412,15 @@ workflow_definition:assert ids == ["cred_valid"]+ def test_carried_credential_does_not_approve_a_never_named_id(self) -> None:+ policy = RequestPolicy(resolved_credentials=[SimpleNamespace(credential_id="cred_A")])++ assert _credential_run_approval_error(["cred_A"], policy) is None+ error = _credential_run_approval_error(["cred_X"], policy)+ assert error is not None+ assert "unapproved_credential_reference" in error+ assert "cred_X" in error+@pytest.mark.asyncioasync def test_missing_tool_credential_reference_returns_blocking_error(self, monkeypatch) -> None:from skyvern.forge.sdk.copilot.tools import _credential_reference_validation_errordiff --git a/tests/unit/test_copilot_context.py b/tests/unit/test_copilot_context.pyindex 5cc7ba613..72991fb4b 100644--- a/tests/unit/test_copilot_context.py+++ b/tests/unit/test_copilot_context.py@@ -10,13 +10,16 @@ from unittest.mock import MagicMockimport pytestfrom skyvern.forge.sdk.copilot.context import (+ ApprovedCredential,FillCarry,LoadedResultTargetContext,ObservedPage,StructuredContext,_fill_carry_from_scout_trajectory,_merge_observed_acted_pages,+ adopt_model_authored_context,finalize_discovery_counter_in_global_llm_context,+ record_approved_credentials_in_global_llm_context,render_loaded_result_context_for_prompt,sanitize_global_llm_context_for_prompt,)@@ -662,3 +665,88 @@ class TestCopilotContext:assert ctx.last_failure_signature is Noneassert ctx.repeated_failure_streak_count == 0assert ctx.repeated_failure_nudge_emitted_at_streak == 0+++def _policy_ctx(resolved: list[SimpleNamespace], credential_input_kind: str = "credential_name") -> SimpleNamespace:+ return SimpleNamespace(+ request_policy=SimpleNamespace(resolved_credentials=resolved, credential_input_kind=credential_input_kind)+ )+++def test_record_approved_credentials_persists_resolved_ids() -> None:+ ctx = _policy_ctx([SimpleNamespace(credential_id="cred_portal", name="mock-portal-login")])++ raw = record_approved_credentials_in_global_llm_context(ctx, None)++ records = StructuredContext.from_json_str(raw).approved_credentials+ assert records == [ApprovedCredential(credential_id="cred_portal")]+++def test_record_approved_credentials_is_idempotent_across_turns() -> None:+ ctx = _policy_ctx([SimpleNamespace(credential_id="cred_portal", name="mock-portal-login")])++ first = record_approved_credentials_in_global_llm_context(ctx, None)+ second = record_approved_credentials_in_global_llm_context(ctx, first)++ ids = [record.credential_id for record in StructuredContext.from_json_str(second).approved_credentials]+ assert ids == ["cred_portal"]+++def test_record_approved_credentials_caps_at_twenty() -> None:+ prior = StructuredContext(+ approved_credentials=[ApprovedCredential(credential_id=f"cred_{i}") for i in range(20)]+ ).to_json_str()+ ctx = _policy_ctx([SimpleNamespace(credential_id="cred_new", name="")])++ raw = record_approved_credentials_in_global_llm_context(ctx, prior)++ records = StructuredContext.from_json_str(raw).approved_credentials+ assert len(records) == 20+ assert records[-1].credential_id == "cred_new"+ assert "cred_0" not in {record.credential_id for record in records}+++def test_record_approved_credentials_survive_prompt_sanitization() -> None:+ ctx = _policy_ctx([SimpleNamespace(credential_id="cred_portal", name="mock-portal-login")])++ recorded = record_approved_credentials_in_global_llm_context(ctx, None)+ sanitized = sanitize_global_llm_context_for_prompt(recorded)++ ids = [record.credential_id for record in StructuredContext.from_json_str(sanitized).approved_credentials]+ assert ids == ["cred_portal"]+++def test_record_approved_credentials_no_ops_without_resolved() -> None:+ assert record_approved_credentials_in_global_llm_context(_policy_ctx([]), None) is None+ assert record_approved_credentials_in_global_llm_context(SimpleNamespace(request_policy=None), "prior") == "prior"+++def test_model_authored_context_cannot_introduce_approved_credentials() -> None:+ # Org membership is not evidence the user named a credential: an entry the model+ # supplies must not survive into the recorded set, or the next turn would promote+ # it into resolved_credentials and clear the unapproved-credential gate.+ trusted = StructuredContext(approved_credentials=[ApprovedCredential(credential_id="cred_named")]).to_json_str()+ model_authored = {+ "user_goal": "log in",+ "approved_credentials": [{"credential_id": "cred_never_named"}],+ }++ adopted = adopt_model_authored_context(trusted, model_authored)++ assert [r.credential_id for r in adopted.approved_credentials] == ["cred_named"]+ assert adopted.user_goal == "log in"+++def test_model_authored_context_cannot_drop_a_server_recorded_approval() -> None:+ trusted = StructuredContext(approved_credentials=[ApprovedCredential(credential_id="cred_named")]).to_json_str()++ adopted = adopt_model_authored_context(trusted, {"user_goal": "x", "approved_credentials": []})++ assert [r.credential_id for r in adopted.approved_credentials] == ["cred_named"]+++def test_model_authored_free_text_context_is_preserved_without_approvals() -> None:+ adopted = adopt_model_authored_context(None, "just some prose the model emitted")++ assert adopted.user_goal == "just some prose the model emitted"+ assert adopted.approved_credentials == []diff --git a/tests/unit/test_copilot_make_agent_result_backfill.py b/tests/unit/test_copilot_make_agent_result_backfill.pyindex 42840045f..a68667165 100644--- a/tests/unit/test_copilot_make_agent_result_backfill.py+++ b/tests/unit/test_copilot_make_agent_result_backfill.py@@ -7,6 +7,7 @@ from __future__ import annotationsimport base64import jsonfrom io import BytesIO+from types import SimpleNamespacefrom typing import Anyimport pytest@@ -15,7 +16,12 @@ from PIL import Image, PngImagePluginfrom skyvern.forge.sdk.copilot import agent as agent_modulefrom skyvern.forge.sdk.copilot.agent import _finalize_result_with_blocker_override, _make_agent_resultfrom skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal-from skyvern.forge.sdk.copilot.context import AgentResult, CopilotContext, DeliveredUnverifiedPublicOutputs+from skyvern.forge.sdk.copilot.context import (+ AgentResult,+ CopilotContext,+ DeliveredUnverifiedPublicOutputs,+ StructuredContext,+)from skyvern.forge.sdk.copilot.request_policy import RequestPolicyfrom skyvern.forge.sdk.schemas.copilot_turn_outcome import ResponseKind, TurnOutcomefrom tests.unit.copilot_test_helpers import make_copilot_ctx as _ctx@@ -875,3 +881,12 @@ def test_delivered_unverified_image_data_url_is_canonicalized_without_metadata()result.narrative_payload["deliveredUnverifiedObservedOutputs"]["result"]["image"], validate=True)assert secret.encode() not in published+++def test_make_agent_result_records_resolved_credentials_as_durable_approval() -> None:+ ctx = _ctx(request_policy=RequestPolicy(resolved_credentials=[SimpleNamespace(credential_id="cred_portal")]))++ result = _result(ctx, narrative_payload=_payload())++ approved = StructuredContext.from_json_str(result.global_llm_context).approved_credentials+ assert [record.credential_id for record in approved] == ["cred_portal"]diff --git a/tests/unit/test_copilot_request_policy_workflow_credentials.py b/tests/unit/test_copilot_request_policy_workflow_credentials.pyindex 337cb7031..1f9238c40 100644--- a/tests/unit/test_copilot_request_policy_workflow_credentials.py+++ b/tests/unit/test_copilot_request_policy_workflow_credentials.py@@ -7,7 +7,11 @@ from unittest.mock import AsyncMock, patchimport pytestfrom skyvern.config import settings-from skyvern.forge.sdk.copilot.context import CredentialCheck, StructuredContext+from skyvern.forge.sdk.copilot.context import (+ CredentialCheck,+ StructuredContext,+ record_approved_credentials_in_global_llm_context,+)from skyvern.forge.sdk.copilot.request_policy import (CREDENTIAL_DEFERRED_DRAFT_REASONS,CREDENTIAL_PROMPT_CLARIFICATION_REASONS,@@ -17,6 +21,7 @@ from skyvern.forge.sdk.copilot.request_policy import (build_request_policy,credential_prompt_reason,)+from skyvern.forge.sdk.copilot.tools.credentials import _credential_run_approval_errordef _yaml(body: str) -> str:@@ -457,6 +462,7 @@ async def _build_with_forced_classifier(get_credentials: AsyncMock | None = None,get_credentials_by_ids: AsyncMock | None = None,workflow_yaml: str = "",+ global_llm_context: str = "",) -> RequestPolicy:load_mock = get_credentials or AsyncMock(return_value=org_credentials)by_ids_mock = get_credentials_by_ids or AsyncMock(return_value=[])@@ -472,7 +478,7 @@ async def _build_with_forced_classifier(user_message=user_message,workflow_yaml=workflow_yaml,chat_history=[],- global_llm_context="",+ global_llm_context=global_llm_context,organization_id="o_test",handler=None,)@@ -880,3 +886,121 @@ async def test_a_pasted_secret_under_login_intent_keeps_the_raw_secret_refusal()def test_login_credentials_unresolved_surfaces_a_prompt_but_grants_no_deferred_draft_authority() -> None:assert "login_credentials_unresolved" in CREDENTIAL_PROMPT_CLARIFICATION_REASONSassert "login_credentials_unresolved" not in CREDENTIAL_DEFERRED_DRAFT_REASONS+++async def _resolve_named_credential_turn(credential: SimpleNamespace) -> RequestPolicy:+ return await _build_with_forced_classifier(+ user_message=f"Sign in with the saved credential named {credential.name}.",+ classifier_policy=RequestPolicy(+ credential_input_kind="credential_name",+ credential_refs=[credential.name],+ classifier_status="success",+ ),+ org_credentials=[credential],+ )+++async def test_prior_approved_credential_carried_into_confirmation_turn() -> None:+ credential = _cred("mock-portal-login", "cred_portal", tested_url="http://localhost:8951/x")+ turn_one = await _resolve_named_credential_turn(credential)+ assert [c.credential_id for c in turn_one.resolved_credentials] == ["cred_portal"]++ recorded = record_approved_credentials_in_global_llm_context(SimpleNamespace(request_policy=turn_one), None)++ turn_two = await _build_with_forced_classifier(+ user_message="yes",+ classifier_policy=RequestPolicy(credential_input_kind="none", classifier_status="success"),+ org_credentials=[],+ get_credentials_by_ids=AsyncMock(return_value=[credential]),+ global_llm_context=recorded,+ )++ assert turn_two.credential_input_kind == "none"+ assert "cred_portal" in {c.credential_id for c in turn_two.resolved_credentials}+ assert _credential_run_approval_error(["cred_portal"], turn_two) is None+++async def test_carried_credential_metadata_matches_turn_one_resolution() -> None:+ credential = _cred("mock-portal-login", "cred_portal", tested_url="http://localhost:8951/x")+ turn_one = await _resolve_named_credential_turn(credential)+ recorded = record_approved_credentials_in_global_llm_context(SimpleNamespace(request_policy=turn_one), None)++ turn_two = await _build_with_forced_classifier(+ user_message="yes",+ classifier_policy=RequestPolicy(credential_input_kind="none", classifier_status="success"),+ org_credentials=[],+ get_credentials_by_ids=AsyncMock(return_value=[credential]),+ global_llm_context=recorded,+ )++ carried = next(c for c in turn_two.resolved_credentials if c.credential_id == "cred_portal")+ assert carried.tested_url == "http://localhost:8951/x"+++async def test_soft_deleted_prior_approved_credential_drops_out_of_carry() -> None:+ credential = _cred("mock-portal-login", "cred_portal")+ turn_one = await _resolve_named_credential_turn(credential)+ recorded = record_approved_credentials_in_global_llm_context(SimpleNamespace(request_policy=turn_one), None)++ turn_two = await _build_with_forced_classifier(+ user_message="yes",+ classifier_policy=RequestPolicy(credential_input_kind="none", classifier_status="success"),+ org_credentials=[],+ get_credentials_by_ids=AsyncMock(return_value=[]),+ global_llm_context=recorded,+ )++ assert turn_two.resolved_credentials == []+ assert _credential_run_approval_error(["cred_portal"], turn_two) is not None+++async def test_ambiguous_named_credential_still_blocks_despite_carried_state() -> None:+ approved = _cred("mock-portal-login", "cred_portal")+ recorded = record_approved_credentials_in_global_llm_context(+ SimpleNamespace(request_policy=RequestPolicy(resolved_credentials=[approved])), None+ )+ duplicates = [_cred("payroll", "cred_payroll_a"), _cred("payroll", "cred_payroll_b")]++ turn_two = await _build_with_forced_classifier(+ user_message="use my payroll login",+ classifier_policy=RequestPolicy(+ credential_input_kind="credential_name",+ credential_refs=["payroll"],+ classifier_status="success",+ ),+ org_credentials=duplicates,+ get_credentials_by_ids=AsyncMock(return_value=[approved]),+ global_llm_context=recorded,+ )++ assert turn_two.requires_user_clarification is True+ assert turn_two.clarification_reason == "credential_name_unresolved"+++async def test_carried_credential_satisfies_the_login_reachability_ask() -> None:+ # The carry must be seeded before _login_credentials_unresolved runs; seeding after it+ # would re-ask for a credential approved on an earlier turn (SKY-12812 via SKY-12760's ask).+ credential = _cred("mock-portal-login", "cred_portal", tested_url="https://portal.example.com/login")+ turn_one = await _resolve_named_credential_turn(credential)+ recorded = record_approved_credentials_in_global_llm_context(SimpleNamespace(request_policy=turn_one), None)++ turn_two = 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=[],+ get_credentials_by_ids=AsyncMock(return_value=[credential]),+ global_llm_context=recorded,+ )++ assert turn_two.clarification_reason != "login_credentials_unresolved"+ assert "cred_portal" in {c.credential_id for c in turn_two.resolved_credentials}