Skip to content

Automate browser based workflows with AI

SKY-12917 Make Copilot credential resolution exhaustive (#7714)

Andrew Neilson3902e23ec50e
diff --git a/skyvern/forge/sdk/copilot/request_policy.py b/skyvern/forge/sdk/copilot/request_policy.py
index 5233f6ee1..05e891f6b 100644
--- a/skyvern/forge/sdk/copilot/request_policy.py
+++ b/skyvern/forge/sdk/copilot/request_policy.py
@@ -196,7 +196,70 @@ _NAMED_CREDENTIAL_TOKEN_RE = re.compile(
r"\b(?:saved\s+credential|credential)\s+(?:named|called)\s+([A-Za-z0-9_.@:-]{2,100})\b",
re.I,
)
+_DIRECT_CREDENTIAL_TOKEN_RE = re.compile(
+ r"\b(?:use|using|with)\s+(?:the\s+)?(?:saved\s+)?credential"
+ r"(?:\s+(?:named|called))?\s+([A-Za-z0-9_.@:-]{2,100})\b",
+ re.I,
+)
+_POSTFIX_CREDENTIAL_TOKEN_RE = re.compile(
+ r"\b(?:use|using|with)\s+(?:my\s+|the\s+)?(?:saved\s+)?([A-Za-z0-9_.@:-]{2,100})\s+credential\b",
+ re.I,
+)
+_EXPLICIT_CREDENTIAL_ID_CONTEXT_RE = re.compile(
+ r"\b(?:use|using|with|select|choose)\s+"
+ r"(?:(?:my|the|a)\s+)?(?:(?:saved|stored)\s+)?(?:credential(?:\s+id)?\s*)?"
+ r"(?::\s*)?$",
+ re.I,
+)
+_CREDENTIAL_ID_LABEL_CONTEXT_RE = re.compile(r"\bcredential\s+id\s*$", re.I)
+_CREDENTIAL_ID_COORDINATOR_RE = re.compile(r"\s*,?\s*(?:and|or)\s*$", re.I)
+_CREDENTIAL_REPLACEMENT_TARGET_RES = (
+ re.compile(
+ r"\bswitch(?:ing)?\s+to\b"
+ r"(?=\s+(?:(?:my|the|a)\s+)?(?:(?:saved|stored)\s+)?"
+ r"(?:credential\b|cred_|[A-Za-z0-9_.@:-]{2,100}\s+credential\b))",
+ re.I,
+ ),
+ re.compile(
+ r"\breplace\s+(?:(?:it|this|that)\b|cred_[A-Za-z0-9_-]+|"
+ r"(?:(?:my|the|a)\s+)?(?:(?:saved|stored)\s+)?credential"
+ r"(?:\s+(?:(?:id|named|called)\s+)?[A-Za-z0-9_.@:-]{2,100})?)"
+ r"\s+with\b"
+ r"(?=\s+(?:(?:my|the|a)\s+)?(?:(?:saved|stored)\s+)?"
+ r"(?:credential\b|cred_|[A-Za-z0-9_.@:-]{2,100}\s+credential\b))",
+ re.I,
+ ),
+)
+_REPLACEMENT_CONTEXT_RE = re.compile(
+ r"\breplace\b(?P<object>[^.!?\n,;]{1,80}?)\bwith\s+"
+ r"(?:(?:my|the|a)\s+)?(?:(?:saved|stored)\s+)?"
+ r"(?:credential(?:\s+(?:id|named|called))?\s*)?$",
+ re.I,
+)
+_CREDENTIAL_REPLACEMENT_OBJECT_RE = re.compile(
+ r"\s*(?:(?:it|this|that)|cred_[A-Za-z0-9_-]+|"
+ r"(?:(?:my|the|a)\s+)?(?:(?:saved|stored)\s+)?credential"
+ r"(?:\s+(?:(?:id|named|called)\s+)?[A-Za-z0-9_.@:-]{2,100})?)\s*",
+ re.I,
+)
_CREDENTIAL_QUOTE_CONTEXT_RE = re.compile(r"\b(?:credentials?|log[\s-]?in)\b", re.I)
+_NEGATED_CREDENTIAL_CONTEXT_RE = re.compile(
+ r"(?:"
+ r"\b(?:do\s+not|don't|never|without|avoid(?:ing)?|exclud(?:e|ed|es|ing))\b"
+ r"(?:(?!\b(?:but|instead)\b)[^.!?\n,;])*"
+ r"|\b(?:instead\s+of|rather\s+than|not|except)\s+"
+ r"(?:(?:the|a)\s+)?(?:(?:saved\s+)?credential(?:\s+id)?\s*)?"
+ r")$",
+ re.I,
+)
+_EXPLICIT_LOGIN_ACTION_RE = re.compile(
+ r"(?<![/\w-])(?:log[\s-]?in|login|sign[\s-]?in)\b"
+ r"(?!\s+(?:form|page|path|route|screen|url)\b)",
+ re.I,
+)
+_CREDENTIAL_REFERENCE_STOPWORDS = frozenset(
+ {"a", "an", "credential", "for", "login", "my", "saved", "stored", "the", "to"}
+)
_CODE_BLOCK_AUTHORING_MARKERS = ("code block", "code-block", "codeblock")
_LOGIN_BLOCK_BAN_MARKERS = ("do not create a login block", "don't create a login block", "no login block")
_CREDENTIAL_CODE_MARKERS = ("saved credential", "login_credentials", ".otp()", "one-time-code")
@@ -4140,68 +4203,131 @@ def _quote_in_credential_context(user_message: str, quote_start: int) -> bool:
return bool(_CREDENTIAL_QUOTE_CONTEXT_RE.search(user_message[max(0, quote_start - 48) : quote_start]))
+def _credential_reference_is_negated(user_message: str, reference_start: int) -> bool:
+ clause_start = max(user_message.rfind(delimiter, 0, reference_start) for delimiter in (".", "!", "?", "\n", ";"))
+ context = user_message[clause_start + 1 : reference_start]
+ context = re.sub(r",\s*(?=credential\b)", " ", context, flags=re.I)
+ if context.rstrip().endswith(",") and re.match(
+ r"\s*(?:credential\b|cred_|[`'\"])",
+ user_message[reference_start:],
+ re.I,
+ ):
+ context = f"{context.rstrip()[:-1]} "
+ return bool(_NEGATED_CREDENTIAL_CONTEXT_RE.search(context))
+
+
+def _credential_reference_is_unrelated_replacement(user_message: str, reference_start: int) -> bool:
+ clause_start = max(
+ user_message.rfind(delimiter, 0, reference_start) for delimiter in (".", "!", "?", "\n", ",", ";")
+ )
+ replacement = _REPLACEMENT_CONTEXT_RE.search(user_message[clause_start + 1 : reference_start])
+ return bool(replacement and not _CREDENTIAL_REPLACEMENT_OBJECT_RE.fullmatch(replacement.group("object")))
+
+
+def _credential_authority_text(user_message: str) -> str:
+ replacement_targets = [
+ match.end()
+ for pattern in _CREDENTIAL_REPLACEMENT_TARGET_RES
+ for match in pattern.finditer(user_message)
+ if not _credential_reference_is_negated(user_message, match.start())
+ ]
+ if not replacement_targets:
+ return user_message
+ return f"use {user_message[max(replacement_targets) :].lstrip()}"
+
+
def _exact_credential_name_candidates(user_message: str) -> list[str]:
- text = user_message or ""
- candidates: list[str] = []
+ text = _credential_authority_text(user_message or "")
+ mentions: list[tuple[str, int, bool, bool]] = []
+
+ def add_mention(value: str, start: int, *, context_matches: bool = True) -> None:
+ value = value.strip()
+ if not context_matches or not value or value.lower() in _CREDENTIAL_REFERENCE_STOPWORDS:
+ return
+ mentions.append(
+ (
+ value,
+ start,
+ _credential_reference_is_negated(text, start),
+ _credential_reference_is_unrelated_replacement(text, start),
+ )
+ )
+
for match in _QUOTED_CREDENTIAL_NAME_RE.finditer(text):
- value = next((group for group in match.groups() if group), "").strip()
- if value and _quote_in_credential_context(text, match.start()):
- candidates.append(value)
+ group_index = next((index for index, group in enumerate(match.groups(), start=1) if group), 1)
+ value = (match.group(group_index) or "").strip()
+ add_mention(
+ value,
+ match.start(),
+ context_matches=_quote_in_credential_context(text, match.start()),
+ )
for match in _NAMED_CREDENTIAL_TOKEN_RE.finditer(text):
- value = match.group(1).strip()
- if value:
- candidates.append(value)
- return _clean_list(candidates)
+ add_mention(match.group(1), match.start(1))
+ for match in _DIRECT_CREDENTIAL_TOKEN_RE.finditer(text):
+ add_mention(match.group(1), match.start(1))
+ for match in _POSTFIX_CREDENTIAL_TOKEN_RE.finditer(text):
+ add_mention(match.group(1), match.start(1))
+
+ last_negated_mention = {
+ value: start for value, start, is_negated, is_unrelated in mentions if is_negated and not is_unrelated
+ }
+ return _clean_list(
+ [
+ value
+ for value, start, is_negated, is_unrelated in mentions
+ if not is_negated and not is_unrelated and last_negated_mention.get(value, -1) < start
+ ]
+ )
-def _exact_credential_name_scan_eligible(policy: RequestPolicy) -> bool:
- if policy.raw_secret_detected:
- return False
- if policy.clarification_reason in _PRE_RESOLUTION_CLARIFICATION_REASONS:
- return False
- if policy.credential_input_kind == "credential_name" and policy.credential_refs:
- return False
- return policy.credential_input_kind in ("none", "credential_name", "website_stored_credential")
+def _credential_name_candidates(user_message: str) -> list[str]:
+ # Classifier refs are model-authored hints, not current-turn credential
+ # authority. Resolve names only from deterministic, affirmative references
+ # in the latest user message.
+ return _exact_credential_name_candidates(user_message)
-async def _apply_exact_credential_name_scope(
- policy: RequestPolicy,
- *,
- user_message: str,
- organization_id: str,
-) -> None:
- if not _exact_credential_name_scan_eligible(policy):
- return
- candidates = _exact_credential_name_candidates(user_message)
- if not candidates:
- return
- credentials = await _load_credentials(organization_id)
- if (
- policy.credential_input_kind == "website_stored_credential"
- and policy.login_page_urls
- and _match_by_url(
- [credential for credential in credentials if credential.credential_type == CredentialType.PASSWORD],
- policy.login_page_urls,
- )
- ):
- return
- matched_names = _clean_list(
- [candidate for candidate in candidates if any(credential.name == candidate for credential in credentials)]
+def _explicit_credential_ids(user_message: str) -> list[str]:
+ text = _credential_authority_text(user_message or "")
+ explicit: list[str] = []
+ matches = sorted(
+ [(match, match.group(0)) for match in _CREDENTIAL_ID_RE.finditer(text)]
+ + [(match, f"cred_{match.group(1)}") for match in _MALFORMED_CREDENTIAL_ID_RE.finditer(text)],
+ key=lambda item: item[0].start(),
)
- if len(matched_names) == 1:
- policy.credential_input_kind = "credential_name"
- policy.credential_refs = matched_names
- policy.requires_user_clarification = False
- policy.clarification_reason = "none"
- policy.clarification_question = None
- elif len(matched_names) > 1:
- matches = [credential for credential in credentials if credential.name in matched_names]
- _block(
- policy,
- "I found multiple saved credentials named in your request. Which one should I use?",
- matches,
- reason="credential_name_unresolved",
- )
+ last_negated_mention = {
+ credential_id: match.start()
+ for match, credential_id in matches
+ if _credential_reference_is_negated(text, match.start())
+ }
+ last_explicit_end: int | None = None
+ for match, credential_id in matches:
+ if last_negated_mention.get(credential_id, -1) > match.start():
+ continue
+ if _credential_reference_is_negated(text, match.start()) or _credential_reference_is_unrelated_replacement(
+ text, match.start()
+ ):
+ continue
+ context = text[max(0, match.start() - 64) : match.start()]
+ if (
+ _EXPLICIT_CREDENTIAL_ID_CONTEXT_RE.search(context)
+ or _CREDENTIAL_ID_LABEL_CONTEXT_RE.search(context)
+ or match.group(0).strip() == text.strip()
+ or (
+ last_explicit_end is not None
+ and _CREDENTIAL_ID_COORDINATOR_RE.fullmatch(text[last_explicit_end : match.start()])
+ )
+ ):
+ explicit.append(credential_id)
+ last_explicit_end = match.end()
+ return _clean_list(explicit)
+
+
+def _deduplicate_credentials(credentials: list[Credential]) -> list[Credential]:
+ by_id: dict[str, Credential] = {}
+ for credential in credentials:
+ by_id.setdefault(credential.credential_id, credential)
+ return list(by_id.values())
def _safe_label(credential: Credential) -> str:
@@ -4328,14 +4454,20 @@ def _clarification_question(policy: RequestPolicy, global_llm_context: str = "")
return "I need one more detail before I can build and test this workflow safely."
-def _has_resolvable_credential_scope(policy: RequestPolicy) -> bool:
- if policy.credential_input_kind == "credential_id":
- return any(ref.startswith("cred_") for ref in policy.credential_refs)
- if policy.credential_input_kind == "credential_name":
- return bool(policy.credential_refs)
- if policy.credential_input_kind == "website_stored_credential":
- return bool(policy.login_page_urls)
- return False
+def _has_resolvable_credential_scope(policy: RequestPolicy, user_message: str = "") -> bool:
+ if policy.raw_secret_detected:
+ return False
+ if _explicit_credential_ids(user_message):
+ return True
+ if _credential_name_candidates(user_message):
+ return True
+ if policy.login_page_urls:
+ return True
+ if not policy.login_intent:
+ return False
+ if policy.testing_intent == "skip_test" or policy.allow_missing_credentials_in_draft:
+ return False
+ return bool(_login_url_candidates(policy, user_message))
def _login_target_is_concrete(policy: RequestPolicy, user_message: str, workflow_yaml: str) -> bool:
@@ -4367,12 +4499,7 @@ def _login_credentials_unresolved(policy: RequestPolicy, user_message: str, work
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
- )
+ return not (policy.resolved_credentials or policy.discovered_credentials or policy.existing_workflow_credential_ids)
def _prioritize_credential_clarification(policy: RequestPolicy) -> None:
@@ -4465,6 +4592,11 @@ def _can_defer_unresolved_credential_name_for_draft(
) -> bool:
if policy.clarification_reason != "credential_name_unresolved":
return False
+ # A classifier-carried name may justify leaving an unvalidated placeholder
+ # in a draft, but _credential_name_candidates still requires current-turn
+ # anchoring before the name can enter resolved_credentials and authorize a run.
+ if policy.credential_refs:
+ return True
if _has_resolvable_credential_scope(policy):
return True
if _previous_credential_clarification_was_asked(global_llm_context):
@@ -4504,10 +4636,14 @@ async def _resolve_credentials(
user_message: str,
defer_unresolved_credential_name: bool = False,
) -> None:
- if policy.credential_input_kind == "credential_id":
- ids = _clean_list([ref for ref in policy.credential_refs if ref.startswith("cred_")])
- if not ids:
- return
+ if policy.raw_secret_detected:
+ return
+
+ # Explicit IDs are deterministic current-turn authority and must win
+ # regardless of the classifier label. Do not trust stale/model-authored
+ # credential_refs that are absent from the latest user message.
+ ids = _explicit_credential_ids(user_message)
+ if ids:
existing = await app.DATABASE.credentials.get_credentials_by_ids(ids, organization_id=organization_id)
found = {credential.credential_id for credential in existing}
policy.resolved_credentials = existing
@@ -4524,51 +4660,103 @@ async def _resolve_credentials(
policy.allow_missing_credentials_in_draft = True
return
- if policy.credential_input_kind == "credential_name" and not policy.credential_refs:
+ name_candidates = _credential_name_candidates(user_message)
+ credentials: list[Credential] | None = None
+ if name_candidates:
+ credentials = await _load_credentials(organization_id)
+ named_matches = _deduplicate_credentials(
+ [credential for credential in credentials if credential.name in name_candidates]
+ )
+ if len(named_matches) == 1:
+ policy.resolved_credentials = named_matches
+ if (
+ policy.classifier_status == "fallback"
+ and policy.credential_input_kind == "none"
+ and not policy.credential_refs
+ ):
+ # Preserve the pre-existing fallback telemetry contract while
+ # keeping successful classifier labels advisory.
+ policy.credential_input_kind = "credential_name"
+ policy.credential_refs = [named_matches[0].name]
+ return
+ if named_matches:
+ if policy.testing_intent == "skip_test" or policy.allow_missing_credentials_in_draft:
+ policy.allow_run_blocks = False
+ policy.allow_missing_credentials_in_draft = True
+ return
+ question = (
+ "I found multiple stored credentials with that exact name. Which one should I use?"
+ if len(name_candidates) == 1
+ else "I found multiple saved credentials named in your request. Which one should I use?"
+ )
+ _block(
+ policy,
+ question,
+ named_matches,
+ reason="credential_name_unresolved",
+ )
+ return
+ if policy.testing_intent == "skip_test" or defer_unresolved_credential_name:
+ policy.allow_run_blocks, policy.allow_missing_credentials_in_draft = False, True
+ if defer_unresolved_credential_name:
+ _defer_unresolved_credential_for_draft(policy)
+ return
if policy.allow_missing_credentials_in_draft:
policy.allow_run_blocks = False
return
- _block(
- policy,
- _SAVED_CREDENTIAL_NAME_QUESTION,
- reason="credential_name_unresolved",
+ question = (
+ f"I could not find a stored credential named `{name_candidates[0]}`. Please choose an existing credential "
+ "by exact name or a credential ID beginning with cred_."
+ if policy.credential_input_kind == "credential_name"
+ else _clarification_question(policy)
)
- return
- if policy.credential_input_kind == "website_stored_credential" and not policy.login_page_urls:
_block(
policy,
- _STORED_CREDENTIAL_URL_QUESTION,
- reason="missing_target_context",
+ question,
+ reason="credential_name_unresolved",
)
return
- if policy.credential_input_kind not in ("credential_name", "website_stored_credential", "none"):
- return
- if policy.credential_input_kind == "none":
- if not policy.login_intent or policy.raw_secret_detected:
- return
- if policy.testing_intent == "skip_test" or policy.allow_missing_credentials_in_draft:
- return
- candidates = _login_url_candidates(policy, user_message)
- if not candidates:
- return
- # Card/secret credentials can carry a tested_url too; a login turn
- # must only ever auto-bind a password credential.
- login_credentials = [
- credential
- for credential in await _load_credentials(organization_id)
- if credential.credential_type == CredentialType.PASSWORD
- ]
+ message_url_candidates = _clean_list(
+ [candidate.rstrip(".,;:!?") for candidate in URL_CANDIDATE_RE.findall(user_message)]
+ )
+ current_turn_login_authorized = policy.login_intent or bool(_EXPLICIT_LOGIN_ACTION_RE.search(user_message))
+ url_candidates: list[str] = []
+ allow_host_fallback = False
+ if (
+ current_turn_login_authorized
+ and policy.testing_intent != "skip_test"
+ and not policy.allow_missing_credentials_in_draft
+ ):
+ url_candidates = _login_url_candidates(policy, user_message)
+ allow_host_fallback = bool(policy.login_page_urls)
+ elif policy.credential_input_kind == "website_stored_credential" and message_url_candidates:
+ # A URL explicitly supplied by the current user is independent
+ # authority for the URL tier; classifier-only URLs are not.
+ url_candidates = message_url_candidates
+
+ if url_candidates:
+ if credentials is None:
+ credentials = await _load_credentials(organization_id)
+ url_credentials = credentials
+ if current_turn_login_authorized:
+ # Card/secret credentials can carry a tested_url too; a
+ # login turn must only ever auto-bind a password credential.
+ url_credentials = [
+ credential for credential in credentials if credential.credential_type == CredentialType.PASSWORD
+ ]
matches = _match_by_url(
- login_credentials,
- candidates,
+ url_credentials,
+ url_candidates,
# A URL merely mentioned in prose is a weaker signal than a
# classifier-extracted login page; require an exact tested-URL hit.
- allow_host_fallback=bool(policy.login_page_urls),
+ allow_host_fallback=allow_host_fallback,
)
+ matches = _deduplicate_credentials(matches)
if len(matches) == 1:
policy.resolved_credentials = matches
- elif matches:
+ return
+ if matches:
# Found-but-unbound keeps the unresolved-login override from
# relabeling this disambiguation ask as a missing-credential turn.
policy.discovered_credentials = matches
@@ -4578,68 +4766,51 @@ async def _resolve_credentials(
matches,
reason="credential_name_unresolved",
)
- return
-
- credentials = await _load_credentials(organization_id)
- if policy.credential_input_kind == "credential_name":
- for ref in policy.credential_refs:
- matches = [credential for credential in credentials if credential.name == ref]
- if len(matches) == 1:
- policy.resolved_credentials.append(matches[0])
- elif matches:
- _block(
- policy,
- "I found multiple stored credentials with that exact name. Which one should I use?",
- matches,
- reason="credential_name_unresolved",
- )
+ return
+ if current_turn_login_authorized:
+ # URL-matched password credentials rank first. If neither URL
+ # tier matches, credentials saved without a tested URL remain
+ # valid login candidates.
+ urlless = _deduplicate_credentials(
+ [credential for credential in url_credentials if not credential.tested_url]
+ )
+ if len(urlless) == 1:
+ policy.resolved_credentials = urlless
return
- elif policy.testing_intent == "skip_test" or defer_unresolved_credential_name:
- policy.allow_run_blocks, policy.allow_missing_credentials_in_draft = False, True
- if defer_unresolved_credential_name:
- _defer_unresolved_credential_for_draft(policy)
- else:
+ if urlless:
+ policy.discovered_credentials = urlless
_block(
policy,
- f"I could not find a stored credential named `{ref}`. Please choose an existing credential by exact name or a credential ID beginning with cred_.",
+ _AMBIGUOUS_URL_CREDENTIAL_QUESTION,
+ urlless,
reason="credential_name_unresolved",
)
return
- return
- login_credentials = [
- credential for credential in credentials if credential.credential_type == CredentialType.PASSWORD
- ]
- matches = _match_by_url(login_credentials, policy.login_page_urls)
- if not matches:
- # A credential saved without a tested_url is still a valid login credential,
- # so it stays a candidate once both URL tiers come up empty.
- urlless = [credential for credential in login_credentials if not credential.tested_url]
- if len(urlless) == 1:
- policy.resolved_credentials = urlless
+ if policy.credential_input_kind == "credential_name":
+ if policy.testing_intent == "skip_test" or defer_unresolved_credential_name:
+ policy.allow_run_blocks, policy.allow_missing_credentials_in_draft = False, True
+ if defer_unresolved_credential_name:
+ _defer_unresolved_credential_for_draft(policy)
return
- if urlless:
- # Found-but-unbound keeps the unresolved-login override from
- # relabeling this disambiguation ask as a missing-credential turn.
- policy.discovered_credentials = urlless
- _block(
- policy,
- _AMBIGUOUS_URL_CREDENTIAL_QUESTION,
- urlless,
- reason="credential_name_unresolved",
- )
+ if policy.allow_missing_credentials_in_draft:
+ policy.allow_run_blocks = False
return
- if len(matches) == 1:
- policy.resolved_credentials = matches
- elif matches:
- policy.discovered_credentials = matches
_block(
policy,
- _AMBIGUOUS_URL_CREDENTIAL_QUESTION,
- matches,
+ _SAVED_CREDENTIAL_NAME_QUESTION,
reason="credential_name_unresolved",
)
- else:
+ return
+
+ if policy.credential_input_kind == "website_stored_credential":
+ if not policy.login_page_urls:
+ _block(
+ policy,
+ _STORED_CREDENTIAL_URL_QUESTION,
+ reason="missing_target_context",
+ )
+ return
_block(
policy,
"I could not find a stored credential for that login page. Please select a saved credential by exact name or a credential ID beginning with cred_, or create one in the Credentials UI.",
@@ -4773,18 +4944,6 @@ async def build_request_policy(
policy.existing_workflow_credential_origins = {
credential_id: sorted(origins) for credential_id, origins in workflow_credential_origins(workflow_yaml).items()
}
- try:
- await _apply_exact_credential_name_scope(
- policy,
- user_message=user_message,
- organization_id=organization_id,
- )
- except Exception:
- LOG.warning(
- "request-policy exact credential-name extraction failed",
- organization_id=organization_id,
- exc_info=True,
- )
# This narrows classifier output only after the classifier has identified
# credential intent; running it earlier would be overwritten by the model verdict.
_apply_explicit_code_block_credential_draft_policy(policy, user_message)
@@ -4855,9 +5014,16 @@ async def build_request_policy(
question,
reason="raw_secret",
)
- elif policy.requires_user_clarification and policy.clarification_reason in _PRE_RESOLUTION_CLARIFICATION_REASONS:
+ elif (
+ policy.requires_user_clarification
+ and policy.clarification_reason in _PRE_RESOLUTION_CLARIFICATION_REASONS
+ and not (
+ policy.clarification_reason == "missing_target_context"
+ and _has_resolvable_credential_scope(policy, user_message)
+ )
+ ):
_block(policy, _clarification_question(policy, global_llm_context))
- elif policy.requires_user_clarification and not _has_resolvable_credential_scope(policy):
+ elif policy.requires_user_clarification and not _has_resolvable_credential_scope(policy, user_message):
_block(policy, _clarification_question(policy, global_llm_context))
else:
try:
@@ -4898,6 +5064,12 @@ async def build_request_policy(
exc_info=True,
)
+ if policy.resolved_credentials and policy.clarification_reason == "missing_target_context":
+ policy.requires_user_clarification = False
+ policy.user_response_policy = "proceed"
+ policy.clarification_reason = "none"
+ policy.clarification_question = None
+
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/copilot/tools/guardrails.py b/skyvern/forge/sdk/copilot/tools/guardrails.py
index 2b3047a08..4e588ebf1 100644
--- a/skyvern/forge/sdk/copilot/tools/guardrails.py
+++ b/skyvern/forge/sdk/copilot/tools/guardrails.py
@@ -327,8 +327,8 @@ def _request_policy_allows_untested_code_block_draft(ctx: Any) -> bool:
and policy.allow_update_workflow
and not policy.allow_run_blocks
and policy.testing_intent == "skip_test"
- and policy.credential_input_kind == "credential_name"
and policy.allow_missing_credentials_in_draft
+ and policy.credential_draft_deferred_explicitly
)
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index af053f742..fe82d4e72 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -4809,7 +4809,10 @@ workflow_definition:
tested_url="https://bank.example/login",
credential_type=CredentialType.PASSWORD,
)
- credentials = SimpleNamespace(get_credentials=AsyncMock(return_value=[credential]))
+ credentials = SimpleNamespace(
+ get_credentials=AsyncMock(return_value=[credential]),
+ get_credentials_by_ids=AsyncMock(return_value=[credential]),
+ )
monkeypatch.setattr(policy_module.app, "DATABASE", SimpleNamespace(credentials=credentials))
async def handler(**kwargs):
diff --git a/tests/unit/test_copilot_code_block_persist_seam.py b/tests/unit/test_copilot_code_block_persist_seam.py
index 4964c8f28..c7077fa96 100644
--- a/tests/unit/test_copilot_code_block_persist_seam.py
+++ b/tests/unit/test_copilot_code_block_persist_seam.py
@@ -451,6 +451,7 @@ def _draft_only_credential_ctx() -> CopilotContext:
allow_update_workflow=True,
allow_run_blocks=False,
allow_missing_credentials_in_draft=True,
+ credential_draft_deferred_explicitly=True,
resolved_credentials=[
SimpleNamespace(
credential_id="cred_missing",
diff --git a/tests/unit/test_copilot_request_policy_workflow_credentials.py b/tests/unit/test_copilot_request_policy_workflow_credentials.py
index 575dbda8a..9b56efccb 100644
--- a/tests/unit/test_copilot_request_policy_workflow_credentials.py
+++ b/tests/unit/test_copilot_request_policy_workflow_credentials.py
@@ -15,10 +15,13 @@ from skyvern.forge.sdk.copilot.context import (
from skyvern.forge.sdk.copilot.request_policy import (
_AMBIGUOUS_URL_CREDENTIAL_QUESTION,
_LOGIN_CREDENTIAL_QUESTION,
+ _SAVED_CREDENTIAL_NAME_QUESTION,
+ _STORED_CREDENTIAL_URL_QUESTION,
CREDENTIAL_DEFERRED_DRAFT_REASONS,
CREDENTIAL_PROMPT_CLARIFICATION_REASONS,
RequestPolicy,
_classification_from_raw,
+ _resolve_credentials,
_workflow_credential_inputs_unbound,
build_request_policy,
credential_prompt_reason,
@@ -495,7 +498,10 @@ async def _build_with_forced_classifier(
@pytest.mark.asyncio
[email protected]("kind", ["credential_name", "none"])
+ "kind",
+ ["none", "credential_id", "credential_name", "website_stored_credential", "placeholder"],
+)
async def test_success_empty_refs_resolves_named_credential(kind: str) -> None:
credential = _cred("mock-portal-login", "cred_login")
policy = await _build_with_forced_classifier(
@@ -505,7 +511,7 @@ async def test_success_empty_refs_resolves_named_credential(kind: str) -> None:
)
assert policy.classifier_status == "success"
- assert policy.credential_input_kind == "credential_name"
+ assert policy.credential_input_kind == kind
assert [c.credential_id for c in policy.resolved_credentials] == ["cred_login"]
assert policy.clarification_reason != "credential_name_unresolved"
@@ -529,7 +535,7 @@ async def test_success_website_kind_with_nonmatching_url_resolves_named_credenti
@pytest.mark.asyncio
-async def test_success_website_kind_with_matching_url_keeps_url_credential() -> None:
+async def test_success_website_kind_prefers_named_credential_over_matching_url() -> None:
url_credential = _cred("portal-cred", "cred_url", tested_url="https://portal.example.com/login")
named_credential = _cred("other-login", "cred_named", tested_url="https://elsewhere.example.net/login")
policy = await _build_with_forced_classifier(
@@ -543,7 +549,744 @@ async def test_success_website_kind_with_matching_url_keeps_url_credential() ->
)
assert policy.credential_input_kind == "website_stored_credential"
- assert [c.credential_id for c in policy.resolved_credentials] == ["cred_url"]
+ assert [c.credential_id for c in policy.resolved_credentials] == ["cred_named"]
+
+
+async def _resolve_direct(
+ policy: RequestPolicy,
+ *,
+ user_message: str,
+ org_credentials: list[SimpleNamespace],
+ get_credentials: AsyncMock | None = None,
+ get_credentials_by_ids: AsyncMock | None = None,
+) -> tuple[AsyncMock, AsyncMock]:
+ load_mock = get_credentials or AsyncMock(return_value=org_credentials)
+ by_ids_mock = get_credentials_by_ids or AsyncMock(return_value=[])
+ with (
+ patch("skyvern.forge.app.DATABASE.credentials.get_credentials", new=load_mock),
+ patch("skyvern.forge.app.DATABASE.credentials.get_credentials_by_ids", new=by_ids_mock),
+ ):
+ await _resolve_credentials(policy, "o_test", user_message=user_message)
+ return load_mock, by_ids_mock
+
+
+async def test_name_miss_does_not_advance_to_classifier_only_url() -> None:
+ url_credential = _cred("url-login", "cred_url", tested_url="https://portal.example.com/login")
+ policy = RequestPolicy(
+ credential_input_kind="credential_name",
+ credential_refs=["missing-name"],
+ login_page_urls=["https://portal.example.com/login"],
+ )
+
+ load_mock, _ = await _resolve_direct(
+ policy,
+ user_message="Use the saved credential named missing-name.",
+ org_credentials=[url_credential],
+ )
+
+ assert policy.resolved_credentials == []
+ assert policy.clarification_reason == "credential_name_unresolved"
+ assert "missing-name" in (policy.clarification_question or "")
+ load_mock.assert_awaited_once()
+
+
+ "kind",
+ ["none", "raw_secret", "credential_id", "credential_name", "website_stored_credential", "placeholder"],
+)
[email protected]("credential_refs", [[], ["mock-portal-login"]], ids=["without_refs", "with_refs"])
+async def test_resolver_exact_name_is_independent_of_classifier_label(
+ kind: str,
+ credential_refs: list[str],
+) -> None:
+ credential = _cred("mock-portal-login", "cred_login")
+ policy = RequestPolicy(credential_input_kind=kind, credential_refs=credential_refs)
+
+ await _resolve_direct(
+ policy,
+ user_message="Sign in with the saved credential named mock-portal-login.",
+ org_credentials=[credential],
+ )
+
+ assert policy.credential_input_kind == kind
+ assert [candidate.credential_id for candidate in policy.resolved_credentials] == ["cred_login"]
+ assert policy.clarification_question is None
+
+
+async def test_explicit_id_wins_and_skips_name_and_url_scan() -> None:
+ by_ids = AsyncMock(return_value=[_cred("id-login", "cred_explicit")])
+ load_mock = AsyncMock(side_effect=AssertionError("organization scan should not run after an ID hit"))
+ policy = RequestPolicy(
+ credential_input_kind="credential_id",
+ credential_refs=["cred_explicit", "named-login"],
+ login_page_urls=["https://portal.example.com/login"],
+ )
+
+ await _resolve_direct(
+ policy,
+ user_message="Use credential ID cred_explicit and the saved credential named named-login.",
+ org_credentials=[],
+ get_credentials=load_mock,
+ get_credentials_by_ids=by_ids,
+ )
+
+ assert [candidate.credential_id for candidate in policy.resolved_credentials] == ["cred_explicit"]
+ by_ids.assert_awaited_once_with(["cred_explicit"], organization_id="o_test")
+ load_mock.assert_not_awaited()
+
+
+async def test_explicit_id_wins_for_non_id_label_and_competing_url_match() -> None:
+ explicit = _cred("id-login", "cred_explicit")
+ competing = _cred("url-login", "cred_url", tested_url="https://portal.example.com/login")
+ by_ids = AsyncMock(return_value=[explicit])
+ load_mock = AsyncMock(side_effect=AssertionError("organization scan should not run after an ID hit"))
+ policy = RequestPolicy(
+ credential_input_kind="website_stored_credential",
+ credential_refs=["cred_explicit"],
+ login_page_urls=["https://portal.example.com/login"],
+ )
+
+ await _resolve_direct(
+ policy,
+ user_message="Use credential ID cred_explicit for https://portal.example.com/login.",
+ org_credentials=[competing],
+ get_credentials=load_mock,
+ get_credentials_by_ids=by_ids,
+ )
+
+ assert [candidate.credential_id for candidate in policy.resolved_credentials] == ["cred_explicit"]
+ by_ids.assert_awaited_once_with(["cred_explicit"], organization_id="o_test")
+ load_mock.assert_not_awaited()
+
+
+async def test_explicit_id_label_allows_colon() -> None:
+ by_ids = AsyncMock(return_value=[_cred("id-login", "cred_explicit")])
+ policy = RequestPolicy(credential_input_kind="credential_id")
+
+ await _resolve_direct(
+ policy,
+ user_message="Use credential ID: cred_explicit.",
+ org_credentials=[],
+ get_credentials_by_ids=by_ids,
+ )
+
+ assert [candidate.credential_id for candidate in policy.resolved_credentials] == ["cred_explicit"]
+ by_ids.assert_awaited_once_with(["cred_explicit"], organization_id="o_test")
+
+
+async def test_classifier_id_absent_from_current_message_does_not_resolve() -> None:
+ by_ids = AsyncMock(side_effect=AssertionError("stale classifier IDs must not be resolved"))
+ policy = RequestPolicy(
+ credential_input_kind="credential_id",
+ credential_refs=["cred_stale"],
+ )
+
+ await _resolve_direct(
+ policy,
+ user_message="Continue with the workflow.",
+ org_credentials=[],
+ get_credentials_by_ids=by_ids,
+ )
+
+ assert policy.resolved_credentials == []
+ by_ids.assert_not_awaited()
+
+
+ "user_message",
+ [
+ "Do not use cred_prod.",
+ "Avoid using cred_prod.",
+ "Exclude credential ID cred_prod.",
+ "Do not use the old workflow because it still mentions credential ID cred_prod.",
+ "Do not use this credential, credential ID cred_prod.",
+ ],
+)
+async def test_negated_explicit_id_does_not_resolve(user_message: str) -> None:
+ by_ids = AsyncMock(side_effect=AssertionError("negated credential IDs must not be resolved"))
+ policy = RequestPolicy(
+ credential_input_kind="credential_id",
+ credential_refs=["cred_prod"],
+ )
+
+ await _resolve_direct(
+ policy,
+ user_message=user_message,
+ org_credentials=[],
+ get_credentials_by_ids=by_ids,
+ )
+
+ assert policy.resolved_credentials == []
+ by_ids.assert_not_awaited()
+
+
+ "user_message",
+ [
+ "Use this as a documentation example: cred_prod.",
+ "Use the staging workflow; the notes mention cred_prod.",
+ "Do not use the old workflow because it mentions cred_prod.",
+ 'Document the string "cred_prod" in the workflow notes.',
+ ],
+)
+async def test_unrelated_explicit_id_mention_does_not_resolve(user_message: str) -> None:
+ by_ids = AsyncMock(side_effect=AssertionError("unrelated credential IDs must not be resolved"))
+ policy = RequestPolicy(
+ credential_input_kind="credential_id",
+ credential_refs=["cred_prod"],
+ )
+
+ await _resolve_direct(
+ policy,
+ user_message=user_message,
+ org_credentials=[],
+ get_credentials_by_ids=by_ids,
+ )
+
+ assert policy.resolved_credentials == []
+ by_ids.assert_not_awaited()
+
+
+ "user_message",
+ [
+ "Don't use cred_old; use cred_new.",
+ "Don't use cred_old but use cred_new.",
+ "Use cred_new instead of cred_old.",
+ "Use cred_new rather than cred_old.",
+ "Use cred_new instead of the credential cred_old.",
+ "Use cred_new rather than credential ID cred_old.",
+ "Use cred_new, not cred_old.",
+ ],
+)
+async def test_later_affirmative_id_resolves_after_excluded_id(user_message: str) -> None:
+ selected = _cred("new-login", "cred_new")
+ by_ids = AsyncMock(return_value=[selected])
+ policy = RequestPolicy(
+ credential_input_kind="credential_id",
+ credential_refs=["cred_old", "cred_new"],
+ )
+
+ await _resolve_direct(
+ policy,
+ user_message=user_message,
+ org_credentials=[],
+ get_credentials_by_ids=by_ids,
+ )
+
+ assert [credential.credential_id for credential in policy.resolved_credentials] == ["cred_new"]
+ by_ids.assert_awaited_once_with(["cred_new"], organization_id="o_test")
+
+
+ "user_message",
+ [
+ "Use cred_old; switch to cred_new instead.",
+ "Use cred_old, actually replace it with cred_new.",
+ ],
+)
+async def test_replacement_id_discards_superseded_candidate(user_message: str) -> None:
+ selected = _cred("new-login", "cred_new")
+ by_ids = AsyncMock(return_value=[selected])
+ policy = RequestPolicy(credential_input_kind="credential_id")
+
+ await _resolve_direct(
+ policy,
+ user_message=user_message,
+ org_credentials=[],
+ get_credentials_by_ids=by_ids,
+ )
+
+ assert [credential.credential_id for credential in policy.resolved_credentials] == ["cred_new"]
+ by_ids.assert_awaited_once_with(["cred_new"], organization_id="o_test")
+
+
+async def test_chained_replacement_uses_final_affirmative_id() -> None:
+ selected = _cred("final-login", "cred_final")
+ by_ids = AsyncMock(return_value=[selected])
+ policy = RequestPolicy(credential_input_kind="credential_id")
+
+ await _resolve_direct(
+ policy,
+ user_message="Replace cred_old with cred_new, but do not use cred_new; use cred_final.",
+ org_credentials=[],
+ get_credentials_by_ids=by_ids,
+ )
+
+ assert [credential.credential_id for credential in policy.resolved_credentials] == ["cred_final"]
+ by_ids.assert_awaited_once_with(["cred_final"], organization_id="o_test")
+
+
+async def test_unrelated_replacement_does_not_grant_credential_id_authority() -> None:
+ alpha = _cred("alpha", "cred_alpha")
+ by_ids = AsyncMock(side_effect=AssertionError("documentation ID must not gain credential authority"))
+ policy = RequestPolicy(credential_input_kind="credential_name")
+
+ await _resolve_direct(
+ policy,
+ user_message="Use credential alpha; replace the documentation credential example with cred_beta.",
+ org_credentials=[alpha],
+ get_credentials_by_ids=by_ids,
+ )
+
+ assert [credential.credential_id for credential in policy.resolved_credentials] == ["cred_alpha"]
+ by_ids.assert_not_awaited()
+
+
+async def test_unrelated_replacement_does_not_grant_credential_name_authority() -> None:
+ unrelated = _cred("new-login", "cred_new")
+ policy = RequestPolicy(credential_input_kind="credential_name")
+
+ await _resolve_direct(
+ policy,
+ user_message="Use credential alpha; replace this field with credential new-login.",
+ org_credentials=[unrelated],
+ )
+
+ assert policy.resolved_credentials == []
+ assert policy.clarification_reason == "credential_name_unresolved"
+ assert "alpha" in (policy.clarification_question or "")
+
+
+async def test_unrelated_replacement_does_not_grant_postfix_credential_name_authority() -> None:
+ unrelated = _cred("new-login", "cred_new")
+ policy = RequestPolicy(credential_input_kind="credential_name")
+
+ await _resolve_direct(
+ policy,
+ user_message="Use credential alpha; replace this field with the new-login credential.",
+ org_credentials=[unrelated],
+ )
+
+ assert policy.resolved_credentials == []
+ assert policy.clarification_reason == "credential_name_unresolved"
+ assert "alpha" in (policy.clarification_question or "")
+
+
+async def test_negated_replacement_does_not_select_rejected_id() -> None:
+ selected = _cred("old-login", "cred_old")
+ by_ids = AsyncMock(return_value=[selected])
+ policy = RequestPolicy(credential_input_kind="credential_id")
+
+ await _resolve_direct(
+ policy,
+ user_message="Use cred_old; do not switch to cred_new.",
+ org_credentials=[],
+ get_credentials_by_ids=by_ids,
+ )
+
+ assert [credential.credential_id for credential in policy.resolved_credentials] == ["cred_old"]
+ by_ids.assert_awaited_once_with(["cred_old"], organization_id="o_test")
+
+
+async def test_bare_id_appositive_negation_revokes_earlier_authority() -> None:
+ by_ids = AsyncMock(side_effect=AssertionError("later rejection must revoke the earlier ID"))
+ policy = RequestPolicy(credential_input_kind="credential_id")
+
+ await _resolve_direct(
+ policy,
+ user_message="Use cred_good; do not use cred_bad, cred_good.",
+ org_credentials=[],
+ get_credentials_by_ids=by_ids,
+ )
+
+ assert policy.resolved_credentials == []
+ by_ids.assert_not_awaited()
+
+
+async def test_invalid_explicit_id_does_not_fall_through_to_name() -> None:
+ load_mock = AsyncMock(side_effect=AssertionError("organization scan should not run after an explicit ID"))
+ policy = RequestPolicy(
+ credential_input_kind="credential_id",
+ credential_refs=["cred_missing", "named-login"],
+ )
+
+ await _resolve_direct(
+ policy,
+ user_message="Use credential ID cred_missing and the saved credential named named-login.",
+ org_credentials=[],
+ get_credentials=load_mock,
+ )
+
+ assert policy.invalid_credential_ids == ["cred_missing"]
+ assert policy.clarification_reason == "credential_name_unresolved"
+ load_mock.assert_not_awaited()
+
+
+async def test_duplicate_name_hits_are_deduplicated_by_credential_id() -> None:
+ credential = _cred("named-login", "cred_named")
+ policy = RequestPolicy(credential_input_kind="placeholder")
+
+ await _resolve_direct(
+ policy,
+ user_message="Use the saved credential named named-login.",
+ org_credentials=[credential, credential],
+ )
+
+ assert [candidate.credential_id for candidate in policy.resolved_credentials] == ["cred_named"]
+ assert policy.requires_user_clarification is False
+
+
+async def test_multiple_name_hits_keep_the_existing_picker_and_skip_url() -> None:
+ policy = RequestPolicy(
+ credential_input_kind="website_stored_credential",
+ login_page_urls=["https://portal.example.com/login"],
+ login_intent=True,
+ )
+
+ load_mock, _ = await _resolve_direct(
+ policy,
+ user_message="Use the credential named shared-login.",
+ org_credentials=[
+ _cred("shared-login", "cred_one"),
+ _cred("shared-login", "cred_two"),
+ _cred("url-login", "cred_url", tested_url="https://portal.example.com/login"),
+ ],
+ )
+
+ assert policy.requires_user_clarification is True
+ assert policy.clarification_question is not None
+ assert policy.clarification_question.startswith(
+ "I found multiple stored credentials with that exact name. Which one should I use?"
+ )
+ assert "`cred_url`" not in policy.clarification_question
+ load_mock.assert_awaited_once()
+
+
+async def test_url_tier_deduplicates_and_keeps_existing_picker() -> None:
+ first = _cred("first", "cred_first", tested_url="https://portal.example.com/login")
+ second = _cred("second", "cred_second", tested_url="https://portal.example.com/login")
+ policy = RequestPolicy(
+ credential_input_kind="website_stored_credential",
+ login_page_urls=["https://portal.example.com/login"],
+ login_intent=True,
+ )
+
+ load_mock, _ = await _resolve_direct(
+ policy,
+ user_message="Use the portal login.",
+ org_credentials=[first, first, second],
+ )
+
+ assert policy.clarification_question is not None
+ assert policy.clarification_question.startswith(_AMBIGUOUS_URL_CREDENTIAL_QUESTION)
+ assert policy.clarification_question.count("`cred_first`") == 1
+ assert policy.clarification_question.count("`cred_second`") == 1
+ load_mock.assert_awaited_once()
+
+
+ ("kind", "expected"),
+ [
+ ("none", (False, "proceed", True, True, "none", None)),
+ ("raw_secret", (False, "proceed", True, True, "none", None)),
+ ("credential_id", (False, "proceed", True, True, "none", None)),
+ (
+ "credential_name",
+ (True, "ask_clarification", False, False, "credential_name_unresolved", _SAVED_CREDENTIAL_NAME_QUESTION),
+ ),
+ (
+ "website_stored_credential",
+ (True, "ask_clarification", False, False, "missing_target_context", _STORED_CREDENTIAL_URL_QUESTION),
+ ),
+ ("placeholder", (False, "proceed", True, True, "none", None)),
+ ],
+)
+async def test_zero_hit_policy_is_byte_identical_for_each_label(
+ kind: str,
+ expected: tuple[bool, str, bool, bool, str, str | None],
+) -> None:
+ policy = RequestPolicy(credential_input_kind=kind)
+
+ load_mock, by_ids = await _resolve_direct(
+ policy,
+ user_message="Continue with the workflow.",
+ org_credentials=[],
+ )
+
+ assert (
+ policy.requires_user_clarification,
+ policy.user_response_policy,
+ policy.allow_update_workflow,
+ policy.allow_run_blocks,
+ policy.clarification_reason,
+ policy.clarification_question,
+ ) == expected
+ load_mock.assert_not_awaited()
+ by_ids.assert_not_awaited()
+
+
+async def test_build_path_named_candidate_overrides_only_credential_target_clarification() -> None:
+ policy = await _build_with_forced_classifier(
+ user_message="Sign in with the saved credential named mock-portal-login.",
+ classifier_policy=RequestPolicy(
+ credential_input_kind="website_stored_credential",
+ requires_user_clarification=True,
+ clarification_reason="missing_target_context",
+ classifier_status="success",
+ ),
+ org_credentials=[_cred("mock-portal-login", "cred_login")],
+ )
+
+ assert [candidate.credential_id for candidate in policy.resolved_credentials] == ["cred_login"]
+ assert policy.credential_input_kind == "website_stored_credential"
+ assert policy.requires_user_clarification is False
+ assert policy.clarification_reason == "none"
+ assert policy.clarification_question is None
+ assert policy.to_trace_data()["clarification_reason"] == "none"
+ assert "clarification_reason: none" in policy.prompt_summary()
+
+
+async def test_classifier_stale_name_ref_without_current_message_anchor_does_not_resolve() -> None:
+ load_mock = AsyncMock(side_effect=AssertionError("stale classifier refs must not scan credentials"))
+ policy = await _build_with_forced_classifier(
+ user_message="Continue with the workflow.",
+ classifier_policy=RequestPolicy(
+ credential_input_kind="none",
+ credential_refs=["stale-login"],
+ classifier_status="success",
+ ),
+ org_credentials=[],
+ get_credentials=load_mock,
+ )
+
+ assert policy.resolved_credentials == []
+ assert policy.clarification_reason == "none"
+ load_mock.assert_not_awaited()
+
+
+ "user_message",
+ [
+ "Continue the production workflow.",
+ "Do not use credential prod.",
+ "Do not log in with 'prod'.",
+ "Avoid using credential prod.",
+ "Exclude credential named prod.",
+ "Never use the legacy workflow because it still points to credential named prod.",
+ "Do not use the credential, credential named prod.",
+ "Do not use the saved credential, `prod`.",
+ ],
+)
+async def test_classifier_name_ref_requires_exact_affirmative_credential_context(user_message: str) -> None:
+ load_mock = AsyncMock(side_effect=AssertionError("untrusted classifier refs must not scan credentials"))
+ policy = RequestPolicy(
+ credential_input_kind="credential_name",
+ credential_refs=["prod"],
+ )
+
+ await _resolve_direct(
+ policy,
+ user_message=user_message,
+ org_credentials=[],
+ get_credentials=load_mock,
+ )
+
+ assert policy.resolved_credentials == []
+ load_mock.assert_not_awaited()
+
+
+ "user_message",
+ [
+ "Don't use credential old; use credential new.",
+ "Don't use credential old but use credential new.",
+ ],
+)
+async def test_later_affirmative_name_resolves_after_excluded_name(user_message: str) -> None:
+ policy = RequestPolicy(
+ credential_input_kind="credential_name",
+ credential_refs=["old", "new"],
+ )
+
+ await _resolve_direct(
+ policy,
+ user_message=user_message,
+ org_credentials=[_cred("old", "cred_old"), _cred("new", "cred_new")],
+ )
+
+ assert [credential.credential_id for credential in policy.resolved_credentials] == ["cred_new"]
+
+
+async def test_login_with_credential_token_is_an_exact_name_candidate() -> None:
+ credential = _cred("mock-portal-login-totp", "cred_login")
+ policy = RequestPolicy(
+ credential_input_kind="website_stored_credential",
+ credential_refs=["mock-portal-login-totp"],
+ )
+
+ await _resolve_direct(
+ policy,
+ user_message="Login with credential mock-portal-login-totp and continue.",
+ org_credentials=[credential],
+ )
+
+ assert [candidate.credential_id for candidate in policy.resolved_credentials] == ["cred_login"]
+
+
+async def test_explicit_name_miss_does_not_fall_through_to_classifier_only_url() -> None:
+ url_credential = _cred("url-login", "cred_url", tested_url="https://portal.example.com/login")
+ policy = RequestPolicy(
+ credential_input_kind="credential_name",
+ credential_refs=["missing-name"],
+ login_page_urls=["https://portal.example.com/login"],
+ login_intent=False,
+ )
+
+ await _resolve_direct(
+ policy,
+ user_message="Use the saved credential named missing-name.",
+ org_credentials=[url_credential],
+ )
+
+ assert policy.resolved_credentials == []
+ assert policy.clarification_reason == "credential_name_unresolved"
+ assert "missing-name" in (policy.clarification_question or "")
+
+
+async def test_explicit_name_miss_does_not_fall_through_to_message_url() -> None:
+ url_credential = _cred("url-login", "cred_url", tested_url="https://portal.example.com/login")
+ policy = RequestPolicy(
+ credential_input_kind="credential_name",
+ credential_refs=["missing-name"],
+ login_intent=True,
+ )
+
+ await _resolve_direct(
+ policy,
+ user_message=("Sign in to https://portal.example.com/login with the saved credential named missing-name."),
+ org_credentials=[url_credential],
+ )
+
+ assert policy.resolved_credentials == []
+ assert policy.clarification_reason == "credential_name_unresolved"
+ assert "missing-name" in (policy.clarification_question or "")
+
+
+async def test_credential_grammar_word_does_not_preempt_message_url_resolution() -> None:
+ credential = _cred("portal-login", "cred_url", tested_url="https://portal.example.com/login")
+ policy = RequestPolicy(
+ credential_input_kind="website_stored_credential",
+ login_intent=False,
+ )
+
+ await _resolve_direct(
+ policy,
+ user_message="Use the credential to log in at https://portal.example.com/login.",
+ org_credentials=[credential],
+ )
+
+ assert [candidate.credential_id for candidate in policy.resolved_credentials] == ["cred_url"]
+ assert policy.clarification_question is None
+
+
+async def test_replacement_name_discards_superseded_candidate() -> None:
+ old = _cred("old-login", "cred_old")
+ new = _cred("new-login", "cred_new")
+ policy = RequestPolicy(credential_input_kind="credential_name")
+
+ await _resolve_direct(
+ policy,
+ user_message="Use credential old-login; switch to credential new-login instead.",
+ org_credentials=[old, new],
+ )
+
+ assert [credential.credential_id for credential in policy.resolved_credentials] == ["cred_new"]
+
+
+async def test_postfix_replacement_name_discards_superseded_candidate() -> None:
+ old = _cred("old-login", "cred_old")
+ new = _cred("new-login", "cred_new")
+ policy = RequestPolicy(credential_input_kind="credential_name")
+
+ await _resolve_direct(
+ policy,
+ user_message="Use credential old-login; switch to the new-login credential instead.",
+ org_credentials=[old, new],
+ )
+
+ assert [credential.credential_id for credential in policy.resolved_credentials] == ["cred_new"]
+
+
+async def test_chained_replacement_name_uses_final_affirmative_candidate() -> None:
+ old = _cred("old-login", "cred_old")
+ new = _cred("new-login", "cred_new")
+ final = _cred("final-login", "cred_final")
+ policy = RequestPolicy(credential_input_kind="credential_name")
+
+ await _resolve_direct(
+ policy,
+ user_message=(
+ "Replace credential old-login with credential new-login, "
+ "but do not use credential new-login; use credential final-login."
+ ),
+ org_credentials=[old, new, final],
+ )
+
+ assert [credential.credential_id for credential in policy.resolved_credentials] == ["cred_final"]
+
+
+async def test_unrelated_switch_preserves_credential_name_authority() -> None:
+ credential = _cred("prod-login", "cred_prod")
+ policy = RequestPolicy(credential_input_kind="credential_name")
+
+ await _resolve_direct(
+ policy,
+ user_message="Use credential prod-login, then switch to the reports tab.",
+ org_credentials=[credential],
+ )
+
+ assert [candidate.credential_id for candidate in policy.resolved_credentials] == ["cred_prod"]
+
+
+async def test_website_kind_stale_name_ref_keeps_original_zero_hit_question_and_reason() -> None:
+ policy = await _build_with_forced_classifier(
+ user_message="Continue with the workflow.",
+ classifier_policy=RequestPolicy(
+ credential_input_kind="website_stored_credential",
+ credential_refs=["stale-login"],
+ classifier_status="success",
+ ),
+ org_credentials=[_cred("stale-login", "cred_stale")],
+ )
+
+ assert policy.resolved_credentials == []
+ assert policy.clarification_reason == "missing_target_context"
+ assert policy.clarification_question == _STORED_CREDENTIAL_URL_QUESTION
@pytest.mark.asyncio
@@ -694,8 +1437,8 @@ async def test_website_kind_explicit_name_wins_over_url_matched_card() -> None:
],
)
- assert policy.credential_input_kind == "credential_name"
- assert policy.credential_refs == ["analytics-login"]
+ assert policy.credential_input_kind == "website_stored_credential"
+ assert policy.credential_refs == []
assert [c.credential_id for c in policy.resolved_credentials] == ["cred_named"]
assert policy.requires_user_clarification is False
assert policy.clarification_question is None
@@ -723,7 +1466,7 @@ async def test_success_credential_id_intent_is_not_overridden_by_name_scan() ->
@pytest.mark.asyncio
-async def test_success_populated_name_refs_are_not_narrowed_by_scan() -> None:
+async def test_success_populated_name_refs_resolve_the_single_matching_candidate() -> None:
policy = await _build_with_forced_classifier(
user_message="Use the saved credential named alpha.",
classifier_policy=RequestPolicy(
@@ -735,7 +1478,8 @@ async def test_success_populated_name_refs_are_not_narrowed_by_scan() -> None:
)
assert policy.credential_refs == ["alpha", "beta"]
- assert policy.clarification_reason == "credential_name_unresolved"
+ assert [candidate.credential_id for candidate in policy.resolved_credentials] == ["cred_alpha"]
+ assert policy.clarification_reason == "none"
@pytest.mark.asyncio
@@ -1030,6 +1774,68 @@ async def test_login_intent_none_kind_non_password_sole_match_does_not_bind() ->
assert policy.clarification_question == _LOGIN_CREDENTIAL_QUESTION
+ ("kind", "expected_question"),
+ [("credential_name", _SAVED_CREDENTIAL_NAME_QUESTION), ("placeholder", _LOGIN_CREDENTIAL_QUESTION)],
+)
+async def test_login_classifier_url_non_password_sole_match_does_not_bind(
+ kind: str,
+ expected_question: str,
+) -> None:
+ card = _cred(
+ "corp-card",
+ "cred_card",
+ tested_url="https://portal.example.com/login",
+ credential_type=CredentialType.CREDIT_CARD,
+ )
+ policy = await _build_with_forced_classifier(
+ user_message="Sign in to the portal and continue.",
+ classifier_policy=RequestPolicy(
+ login_intent=True,
+ credential_input_kind=kind,
+ login_page_urls=["https://portal.example.com/login"],
+ classifier_status="success",
+ ),
+ org_credentials=[card],
+ )
+
+ assert policy.resolved_credentials == []
+ assert policy.clarification_reason == "login_credentials_unresolved"
+ assert policy.clarification_question == expected_question
+
+
+ ("kind", "expected_question"),
+ [("credential_name", _SAVED_CREDENTIAL_NAME_QUESTION), ("placeholder", _LOGIN_CREDENTIAL_QUESTION)],
+)
+async def test_login_message_url_non_password_sole_match_does_not_bind(
+ kind: str,
+ expected_question: str,
+) -> None:
+ card = _cred(
+ "corp-card",
+ "cred_card",
+ tested_url="https://portal.example.com/login",
+ credential_type=CredentialType.CREDIT_CARD,
+ )
+ policy = await _build_with_forced_classifier(
+ user_message="Sign in to https://portal.example.com/login and continue.",
+ classifier_policy=RequestPolicy(
+ login_intent=True,
+ credential_input_kind=kind,
+ login_page_urls=[],
+ classifier_status="success",
+ ),
+ org_credentials=[card],
+ )
+
+ assert policy.resolved_credentials == []
+ assert policy.clarification_reason == "login_credentials_unresolved"
+ assert policy.clarification_question == expected_question
+
+
@pytest.mark.asyncio
async def test_login_intent_none_kind_classifier_url_keeps_host_fallback() -> None:
credential = _cred("portal-cred", "cred_url", tested_url="https://example.com/login")
@@ -1141,6 +1947,23 @@ async def test_login_intent_false_none_kind_never_loads_credentials_for_message_
assert policy.resolved_credentials == []
+async def test_login_path_does_not_grant_credential_authority_without_login_intent() -> None:
+ policy = RequestPolicy(
+ login_intent=False,
+ credential_input_kind="none",
+ )
+
+ await _resolve_direct(
+ policy,
+ user_message="Inspect https://portal.example.com/login and report its title.",
+ org_credentials=[_cred("portal", "cred_url", tested_url="https://portal.example.com/login")],
+ )
+
+ assert policy.resolved_credentials == []
+ assert policy.clarification_question is None
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
("testing_intent", "allow_missing_credentials_in_draft"),
@@ -1170,6 +1993,26 @@ async def test_login_intent_none_kind_skip_modes_do_not_lookup_credentials(
assert policy.resolved_credentials == []
+async def test_stale_classifier_ref_does_not_suppress_unresolved_login_ask() -> None:
+ policy = await _build_with_forced_classifier(
+ user_message="Sign in to https://billing.example.com/login and export the statement.",
+ classifier_policy=RequestPolicy(
+ login_intent=True,
+ credential_input_kind="none",
+ credential_refs=["stale-login"],
+ login_page_urls=["https://billing.example.com/login"],
+ classifier_status="success",
+ ),
+ org_credentials=[],
+ )
+
+ assert policy.resolved_credentials == []
+ assert policy.user_response_policy == "ask_clarification"
+ assert policy.allow_run_blocks is False
+ assert policy.clarification_reason == "login_credentials_unresolved"
+
+
@pytest.mark.asyncio
async def test_login_intent_none_kind_prefers_classifier_login_page_urls_over_message_urls() -> None:
classifier_url_credential = _cred("classifier-url", "cred_classifier", tested_url="https://alpha.example.com/login")
diff --git a/tests/unit/test_download_file_action_handler.py b/tests/unit/test_download_file_action_handler.py
index 8afd26a5a..bc9e34128 100644
--- a/tests/unit/test_download_file_action_handler.py
+++ b/tests/unit/test_download_file_action_handler.py
@@ -2382,7 +2382,9 @@ async def test_handle_action_download_without_explicit_timeout_has_bounded_in_fl
)
elapsed = time.monotonic() - started_at
- assert 0.03 <= elapsed < 0.15
+ # Keep a generous wall-clock runaway guard for loaded CI runners; the
+ # precise logical deadline is asserted via timeout_seconds below.
+ assert 0.03 <= elapsed < 1.0
assert results[-1].download_triggered is False
span_attrs = _download_wait_span_attrs(span_exporter)
assert span_attrs["no_signal_grace_seconds"] == 0.01