Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Keep real passwords out of generated login code, and stop endless safety-check retries (SKY-12866) (#7689)
Andrew Neilson918f553ab374
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex 1a3a15f6e..87ead44d6 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -102,6 +102,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_literal_rebind import rebind_scouted_credential_literalsfrom 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 (@@ -187,6 +188,7 @@ from skyvern.forge.sdk.copilot.streaming_adapter import (maybe_emit_design_end,)from skyvern.forge.sdk.copilot.terminal_envelope import assemble_terminal_envelope, reason_in_reply_shadow+from skyvern.forge.sdk.copilot.tools.guardrails import _record_output_policy_guardrail_churnfrom skyvern.forge.sdk.copilot.tracing_setup import _copilot_model_name, ensure_tracing_initialized, is_tracing_enabledfrom skyvern.forge.sdk.copilot.turn_context import TurnContextAssembler, TurnContextInputs, TurnContextPacketfrom skyvern.forge.sdk.copilot.turn_halt import (@@ -3790,6 +3792,33 @@ async def _resolve_wrapped_exception_exit_result(return _build_unexpected_error_exit_result(ctx, global_llm_context, error=error)+def _inline_replace_workflow_credential_verdict(+ ctx: CopilotContext, action_data: dict[str, Any], resp_type: str, user_response: str+) -> tuple[str, OutputPolicyVerdict, OutputPolicyVerdict]:+ """Rebind scouted credential literals into ``action_data['workflow_yaml']`` and evaluate the inline+ REPLACE_WORKFLOW output policy, recording churn when the hard-block verdict rejects. Returns the+ effective YAML plus the raw and hard-block verdicts."""+ workflow_yaml = action_data.get("workflow_yaml", "")+ inline_rebind = rebind_scouted_credential_literals(workflow_yaml, ctx.scout_trajectory)+ if inline_rebind.changed:+ workflow_yaml = inline_rebind.workflow_yaml+ action_data["workflow_yaml"] = workflow_yaml+ LOG.info("copilot inline REPLACE_WORKFLOW rebound scouted credential literals")+ raw_verdict = evaluate_output_policy(+ request_policy=ctx.request_policy,+ response_type=resp_type,+ user_response=str(user_response),+ workflow_yaml=workflow_yaml,+ tool_arguments=action_data,+ has_workflow_proposal=True,+ output_kind=CopilotOutputKind.WORKFLOW_DRAFT_PROPOSAL,+ )+ hard_block_verdict = hard_block_output_policy_verdict(raw_verdict)+ if not hard_block_verdict.allowed:+ _record_output_policy_guardrail_churn(ctx, "replace_workflow_inline", workflow_yaml, hard_block_verdict)+ return workflow_yaml, raw_verdict, hard_block_verdict++async def _translate_to_agent_result(result: RunResultStreaming,ctx: CopilotContext,@@ -3867,16 +3896,9 @@ async def _translate_to_agent_result(LOG.warning("Agent used inline REPLACE_WORKFLOW instead of update_workflow tool")workflow_yaml = action_data.get("workflow_yaml", "")if workflow_yaml:- inline_raw_verdict = evaluate_output_policy(- request_policy=ctx.request_policy,- response_type=resp_type,- user_response=str(user_response),- workflow_yaml=workflow_yaml,- tool_arguments=action_data,- has_workflow_proposal=True,- output_kind=CopilotOutputKind.WORKFLOW_DRAFT_PROPOSAL,+ workflow_yaml, inline_raw_verdict, inline_policy_verdict = _inline_replace_workflow_credential_verdict(+ ctx, action_data, resp_type, str(user_response))- inline_policy_verdict = hard_block_output_policy_verdict(inline_raw_verdict)if not inline_policy_verdict.allowed:inline_diagnostics = build_output_policy_diagnostics(raw_verdict=inline_raw_verdict,diff --git a/skyvern/forge/sdk/copilot/blocker_signal.py b/skyvern/forge/sdk/copilot/blocker_signal.pyindex 530bf96c9..9de32ac46 100644--- a/skyvern/forge/sdk/copilot/blocker_signal.py+++ b/skyvern/forge/sdk/copilot/blocker_signal.py@@ -323,6 +323,7 @@ class TerminalEvidence:@dataclass(frozen=True)class LoopBlockerEvidence(TerminalEvidence):latest_evaluate_result_composition_steer: LoadedResultCompositionEvidence | None = None+ output_policy_reject_reason_codes: frozenset[str] | None = Noneclass _LoopEvidenceCtx(Protocol):@@ -335,6 +336,7 @@ class _LoopEvidenceCtx(Protocol):staged_workflow_yaml: str | Nonehas_staged_proposal: boollatest_evaluate_result_composition_steer: LoadedResultCompositionEvidence | None+ last_output_policy_reject_reason_codes: frozenset[str] | Noneclass _BlockerSignalCtx(_LoopEvidenceCtx, Protocol):@@ -406,6 +408,7 @@ def loop_blocker_evidence_from_ctx(ctx: _LoopEvidenceCtx) -> LoopBlockerEvidenceevidence = terminal_evidence_from_ctx(ctx)# Older context snapshots may not carry fields added after the snapshot was created.result_steer = getattr(ctx, "latest_evaluate_result_composition_steer", None)+ reject_reason_codes = getattr(ctx, "last_output_policy_reject_reason_codes", None)return LoopBlockerEvidence(outcome_gate_reason=evidence.outcome_gate_reason,outcome_gate_workflow_run_id=evidence.outcome_gate_workflow_run_id,@@ -414,6 +417,7 @@ def loop_blocker_evidence_from_ctx(ctx: _LoopEvidenceCtx) -> LoopBlockerEvidenceanti_bot_blocked=evidence.anti_bot_blocked,has_draft=evidence.has_draft,latest_evaluate_result_composition_steer=result_steer,+ output_policy_reject_reason_codes=reject_reason_codes if isinstance(reject_reason_codes, frozenset) else None,)@@ -597,6 +601,14 @@ _LOOP_CREDENTIAL_TEMPLATE = (CREDENTIAL_SCOUT_VERIFY_REPLY = ("I need to verify the saved-credential login in the browser before I can save or run this code.")+# Mirrors OutputPolicyReason.RAW_SECRET_LEAK.value; kept local because output_policy imports this+# module, so importing back would be circular.+RAW_SECRET_LEAK_REASON_CODE = "raw_secret_leak"+RAW_SECRET_EMBED_REFUSAL_REPLY = (+ "I couldn't save this because the login code kept embedding the credential's secret value directly "+ "instead of referencing your saved credential. Your draft is preserved — tell me to reference the "+ "saved credential and I'll try again."+)_LOOP_BRANCH_COPY: dict[str, tuple[str, str]] = {"loop_detected_repeated_failed_step": ("I retried without making progress.",@@ -752,6 +764,9 @@ def compose_loop_blocker_user_facing_reason(if internal_reason_code == "loop_detected_credential_or_parameter_misconfig":return _LOOP_CREDENTIAL_TEMPLATE, draft_tierif internal_reason_code == "credential_priority_authoring_churn":+ reject_reason_codes = evidence.output_policy_reject_reason_codes if evidence is not None else None+ if reject_reason_codes == frozenset({RAW_SECRET_LEAK_REASON_CODE}):+ return RAW_SECRET_EMBED_REFUSAL_REPLY, draft_tierreturn CREDENTIAL_SCOUT_VERIFY_REPLY, draft_tierframing, ask = _LOOP_BRANCH_COPY.get(internal_reason_code or "", _LOOP_BRANCH_COPY["loop_detected_generic"])result_steer = evidence.latest_evaluate_result_composition_steer if evidence is not None else Nonediff --git a/skyvern/forge/sdk/copilot/credential_literal_rebind.py b/skyvern/forge/sdk/copilot/credential_literal_rebind.pyindex 32c0add30..0dc9831ab 100644--- a/skyvern/forge/sdk/copilot/credential_literal_rebind.py+++ b/skyvern/forge/sdk/copilot/credential_literal_rebind.py@@ -7,10 +7,16 @@ from typing import Any, Callable, Mapping, Sequenceimport yamlfrom skyvern.forge.sdk.copilot.code_block_synthesis import _CREDENTIAL_FIELDS, CREDENTIAL_FILL_TOOL_NAME-from skyvern.forge.sdk.copilot.workflow_credential_utils import credential_param_ids+from skyvern.forge.sdk.copilot.workflow_credential_utils import credential_param_ids, workflow_blocks_IDENTIFIER_RE = re.compile(r"[A-Za-z_]\w*")-_STRING_ASSIGN_TMPL = r"^[ \t]*{name}[ \t]*=[ \t]*(?P<q>['\"])(?:\\.|(?!(?P=q)).)*(?P=q)[ \t]*\n?"+_STRING_LITERAL_RE = re.compile(r"(?P<q>['\"])(?:\\.|(?!(?P=q)).)*(?P=q)")+_STRING_ASSIGN_TMPL = r"^[ \t]*{name}[ \t]*=[ \t]*" + _STRING_LITERAL_RE.pattern + r"[ \t]*\n?"+_GOTO_RE = re.compile(r"\.goto\(\s*['\"]([^'\"]+)['\"]")+++def _normalize_page_url(url: str) -> str:+ return url.split("#", 1)[0].strip().rstrip("/")@dataclass(frozen=True)@@ -21,8 +27,9 @@ class CredentialRebindResult:def scouted_credential_targets(scout_trajectory: Sequence[Mapping[str, Any]] | None) -> dict[str, tuple[str, str]]:- """Map each scouted selector to the (credential_id, field) that `fill_credential_field` typed into it."""+ """Map each scouted selector to the (credential_id, field) `fill_credential_field` typed into it, dropping any selector scouted with conflicting credential/field targets so its literals fall to the fail-closed refusal backstop rather than being rebound to an ambiguous parameter."""targets: dict[str, tuple[str, str]] = {}+ conflicted: set[str] = set()for interaction in scout_trajectory or []:if not isinstance(interaction, Mapping):continue@@ -33,10 +40,35 @@ def scouted_credential_targets(scout_trajectory: Sequence[Mapping[str, Any]] | Nfield = str(interaction.get("credential_field") or "").strip()if not selector or not credential_id or field not in _CREDENTIAL_FIELDS:continue- targets.setdefault(selector, (credential_id, field))+ mapping = (credential_id, field)+ existing = targets.get(selector)+ if existing is not None and existing != mapping:+ conflicted.add(selector)+ continue+ targets.setdefault(selector, mapping)+ for selector in conflicted:+ targets.pop(selector, None)return targets+def scouted_selector_source_urls(scout_trajectory: Sequence[Mapping[str, Any]] | None) -> dict[str, frozenset[str]]:+ """Map each `fill_credential_field` selector to the normalized page URL(s) it was scouted on, so a+ block that navigates elsewhere cannot rebind a same-named selector to a credential scouted on a+ different page."""+ by_selector: dict[str, set[str]] = {}+ for interaction in scout_trajectory or []:+ if not isinstance(interaction, Mapping):+ continue+ if str(interaction.get("tool_name") or "").strip() != CREDENTIAL_FILL_TOOL_NAME:+ continue+ selector = str(interaction.get("selector") or "").strip()+ source_url = _normalize_page_url(str(interaction.get("source_url") or ""))+ if not selector or not source_url:+ continue+ by_selector.setdefault(selector, set()).add(source_url)+ return {selector: frozenset(urls) for selector, urls in by_selector.items()}++def _existing_param_key(parameters: Sequence[object], credential_id: str) -> str | None:for key, credential_ids in credential_param_ids(parameters).items():if credential_id in credential_ids:@@ -55,6 +87,11 @@ def _mint_param_key(credential_id: str, used: set[str]) -> str:return candidate+def _identifier_bound_to_string_literal(code: str, name: str) -> bool:+ pattern = re.compile(_STRING_ASSIGN_TMPL.format(name=re.escape(name)), re.MULTILINE)+ return pattern.search(code) is not None++def _drop_dead_string_assignment(code: str, name: str) -> str:pattern = re.compile(_STRING_ASSIGN_TMPL.format(name=re.escape(name)), re.MULTILINE)match = pattern.search(code)@@ -67,22 +104,38 @@ def _drop_dead_string_assignment(code: str, name: str) -> str:return remaining+def _block_page_incompatible(block_goto_urls: set[str], target_source_urls: frozenset[str]) -> bool:+ # A block counts as a different page only when it navigates yet lands on none of the scout pages;+ # scoping is block-level, so a multi-goto block that mixes pages leans on the refusal backstop.+ return bool(block_goto_urls) and bool(target_source_urls) and not (block_goto_urls & target_source_urls)++def _rebind_block_code(- code: str, targets: Mapping[str, tuple[str, str]], param_key_for: Callable[[str], str]+ code: str,+ targets: Mapping[str, tuple[str, str]],+ param_key_for: Callable[[str], str],+ source_urls_by_selector: Mapping[str, frozenset[str]],) -> tuple[str, list[str], set[str]]:rebound: list[str] = []used_params: set[str] = set()replaced_identifiers: set[str] = set()new_code = code+ block_goto_urls = {_normalize_page_url(url) for url in _GOTO_RE.findall(code)}for selector, (credential_id, field) in targets.items():+ if _block_page_incompatible(block_goto_urls, source_urls_by_selector.get(selector, frozenset())):+ continueparam_key = param_key_for(credential_id)access = f"{param_key}.{field}"selector_pattern = re.escape(selector)patterns = (- re.compile(r"(\.(?:fill|type)\(\s*['\"]" + selector_pattern + r"['\"]\s*,\s*)([^),]+?)(\s*\))"),re.compile(- r"(\.locator\(\s*['\"]" + selector_pattern + r"['\"]\s*\)\s*\.(?:fill|type)\(\s*)([^),]+?)(\s*\))"+ r"(\.(?:fill|type|press_sequentially)\(\s*['\"]" + selector_pattern + r"['\"]\s*,\s*)([^),]+?)(\s*\))"+ ),+ re.compile(+ r"(\.locator\(\s*['\"]"+ + selector_pattern+ + r"['\"]\s*\)\s*\.(?:fill|type|press_sequentially)\(\s*)([^),]+?)(\s*\))"),)@@ -91,7 +144,12 @@ def _rebind_block_code(if argument == access:used_params.add(param_key)return match.group(0)- if _IDENTIFIER_RE.fullmatch(argument):+ bound_identifier = _IDENTIFIER_RE.fullmatch(argument) is not None and _identifier_bound_to_string_literal(+ code, argument+ )+ if not _STRING_LITERAL_RE.fullmatch(argument) and not bound_identifier:+ return match.group(0)+ if bound_identifier:replaced_identifiers.add(argument)rebound.append(f"{param_key}.{field}")used_params.add(param_key)@@ -121,6 +179,7 @@ def rebind_scouted_credential_literals(targets = scouted_credential_targets(scout_trajectory)if not targets:return empty+ source_urls_by_selector = scouted_selector_source_urls(scout_trajectory)try:parsed = yaml.safe_load(workflow_yaml)except yaml.YAMLError:@@ -130,8 +189,8 @@ def rebind_scouted_credential_literals(workflow_definition = parsed.get("workflow_definition")if not isinstance(workflow_definition, dict):return empty- blocks = workflow_definition.get("blocks")- if not isinstance(blocks, list):+ blocks = workflow_blocks(parsed)+ if not blocks:return emptyparameters = workflow_definition.get("parameters")@@ -155,7 +214,7 @@ def rebind_scouted_credential_literals(code = block.get("code")if not isinstance(code, str) or not code.strip():continue- new_code, rebound, used_params = _rebind_block_code(code, targets, param_key_for)+ new_code, rebound, used_params = _rebind_block_code(code, targets, param_key_for, source_urls_by_selector)if not rebound:continueblock["code"] = new_codediff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.pyindex dc19df0b3..036a74c1e 100644--- a/skyvern/forge/sdk/copilot/enforcement.py+++ b/skyvern/forge/sdk/copilot/enforcement.py@@ -19,6 +19,7 @@ from agents.run import Runnerfrom skyvern.forge.sdk.copilot import config as copilot_config_defaultsfrom skyvern.forge.sdk.copilot import streaming_adapterfrom skyvern.forge.sdk.copilot.blocker_signal import (+ RAW_SECRET_LEAK_REASON_CODE,SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE,UNCOVERED_OUTPUT_RESCOUT_STEER_REASON_CODE,CopilotToolBlockerSignal,@@ -470,10 +471,18 @@ def credential_priority_authoring_churn_stop_signal(ctx: Any) -> CopilotToolBlocuser_facing, _tiers = compose_loop_blocker_user_facing_reason("credential_priority_authoring_churn", evidence, blocked_tool="update_workflow")- agent_steering = (- f"The credential-scout gate has rejected the generated code {count} times without an accepted save; "- "stop rewriting it and report the recorded blocker from the preserved draft."- )+ # Older context snapshots may not carry fields added after the snapshot was created.+ reject_reason_codes = getattr(ctx, "last_output_policy_reject_reason_codes", None)+ if reject_reason_codes == frozenset({RAW_SECRET_LEAK_REASON_CODE}):+ agent_steering = (+ "The generated login code embedded the credential's secret value and was refused; "+ "stop rewriting it and report the recorded blocker from the preserved draft."+ )+ else:+ agent_steering = (+ f"The credential-scout gate has rejected the generated code {count} times without an accepted save; "+ "stop rewriting it and report the recorded blocker from the preserved draft."+ )return CopilotToolBlockerSignal(blocker_kind="loop_detected",agent_steering_text=agent_steering,@@ -595,7 +604,11 @@ def _scouted_spine_turn_end_nudge(ctx: AgentContext) -> str | None:def _record_code_authoring_guardrail_reject(- ctx: AgentContext, *, defer_churn_stop: bool = False, frontier_unchanged: bool = False+ ctx: AgentContext,+ *,+ defer_churn_stop: bool = False,+ frontier_unchanged: bool = False,+ output_policy_reason_codes: frozenset[str] | None = None,) -> None:# Callers record the current build-test outcome first so repeat detection compares that key to history.repeated_outcome = latest_recorded_build_test_outcome_repeated(ctx)@@ -605,6 +618,9 @@ def _record_code_authoring_guardrail_reject(ctx.code_authoring_guardrail_reject_count = 0ctx.code_authoring_guardrail_reject_count += 1ctx.last_code_authoring_reject_was_credential_priority = defer_churn_stop+ # Any non-output-policy reject clears the cause, so the credential-priority terminal never+ # attributes a scout-gate stop to a stale raw-secret-leak streak.+ ctx.last_output_policy_reject_reason_codes = output_policy_reason_codesLOG.info("copilot code-authoring guardrail reject recorded",reject_count=ctx.code_authoring_guardrail_reject_count,diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.pyindex dd89b7380..faecaa979 100644--- a/skyvern/forge/sdk/copilot/runtime.py+++ b/skyvern/forge/sdk/copilot/runtime.py@@ -380,6 +380,7 @@ class AgentContext:repeated_failure_nudge_emitted_at_streak: int = 0code_authoring_guardrail_reject_count: int = 0last_code_authoring_reject_was_credential_priority: bool = False+ last_output_policy_reject_reason_codes: frozenset[str] | None = None# Climbs on each click that made no verified forward progress (failed/timed-out# click or a hollow post-click observe); resets on verified progress.consecutive_no_progress_interaction_count: int = 0diff --git a/skyvern/forge/sdk/copilot/tools/guardrails.py b/skyvern/forge/sdk/copilot/tools/guardrails.pyindex 4654c9c32..692658b43 100644--- a/skyvern/forge/sdk/copilot/tools/guardrails.py+++ b/skyvern/forge/sdk/copilot/tools/guardrails.py@@ -23,7 +23,6 @@ from skyvern.forge.sdk.copilot.credential_literal_rebind import rebind_scouted_cfrom skyvern.forge.sdk.copilot.enforcement import _record_code_authoring_guardrail_rejectfrom skyvern.forge.sdk.copilot.loop_detection import record_consecutive_tool_result_boundary_for_ctxfrom skyvern.forge.sdk.copilot.output_policy import (- OutputPolicyReason,OutputPolicyVerdict,evaluate_output_policy,format_output_policy_tool_error,@@ -82,9 +81,13 @@ def _workflow_yaml_output_policy_guardrail(data: ToolInputGuardrailData) -> Tool)workflow_yaml_value = tool_arguments.get("workflow_yaml")workflow_yaml = workflow_yaml_value if isinstance(workflow_yaml_value, str) else None++ rebound_yaml = _rebind_scouted_credential_literals_in_place(tool_context, tool_arguments, workflow_yaml)+ effective_yaml = rebound_yaml if rebound_yaml is not None else workflow_yaml+verdict = evaluate_output_policy(request_policy=getattr(getattr(tool_context, "context", None), "request_policy", None),- workflow_yaml=workflow_yaml,+ workflow_yaml=effective_yaml,tool_arguments=tool_arguments or raw_arguments,)trace_data = output_policy_verdict_to_trace_data(@@ -92,59 +95,54 @@ def _workflow_yaml_output_policy_guardrail(data: ToolInputGuardrailData) -> Toolsurface="tool_input",tool_name=getattr(tool_context, "tool_name", None),)- LOG.info("copilot output policy tool guardrail verdict", **trace_data)- if not verdict.allowed:- rebound_yaml = _rebound_credential_yaml(tool_context, workflow_yaml, verdict, tool_arguments)+ if verdict.allowed:if rebound_yaml is not None:- rebound_trace = {**trace_data, "allowed": True, "credential_literals_rebound": True}- LOG.info("copilot output policy rebound scouted credential literals", **rebound_trace)- return ToolGuardrailFunctionOutput.allow(output_info=rebound_trace)- error = format_output_policy_tool_error(verdict)- tool_name = getattr(tool_context, "tool_name", None)- copilot_ctx = getattr(tool_context, "context", None)- if isinstance(tool_name, str) and tool_name:- record_consecutive_tool_result_boundary_for_ctx(- copilot_ctx,- tool_name,- {"ok": False, "error": error},- arguments=tool_arguments,- )- _record_output_policy_guardrail_churn(copilot_ctx, tool_name, workflow_yaml, verdict)- return ToolGuardrailFunctionOutput.reject_content(error, output_info=trace_data)- return ToolGuardrailFunctionOutput.allow(output_info=trace_data)+ trace_data = {**trace_data, "credential_literals_rebound": True}+ LOG.info("copilot output policy rebound scouted credential literals", **trace_data)+ else:+ LOG.info("copilot output policy tool guardrail verdict", **trace_data)+ return ToolGuardrailFunctionOutput.allow(output_info=trace_data)+ LOG.info("copilot output policy tool guardrail verdict", **trace_data)+ error = format_output_policy_tool_error(verdict)+ tool_name = getattr(tool_context, "tool_name", None)+ copilot_ctx = getattr(tool_context, "context", None)+ if isinstance(tool_name, str) and tool_name:+ record_consecutive_tool_result_boundary_for_ctx(+ copilot_ctx,+ tool_name,+ {"ok": False, "error": error},+ arguments=tool_arguments,+ )+ _record_output_policy_guardrail_churn(copilot_ctx, tool_name, effective_yaml, verdict)+ return ToolGuardrailFunctionOutput.reject_content(error, output_info=trace_data)-def _rebound_credential_yaml(- tool_context: Any,- workflow_yaml: str | None,- verdict: OutputPolicyVerdict,- tool_arguments: dict[str, Any],+def _rebind_scouted_credential_literals_in_place(+ tool_context: Any, tool_arguments: dict[str, Any], workflow_yaml: str | None) -> str | None:- """Rebind scouted credential literals so a leak the seam can repair never becomes a reject.-- Returns the rebound YAML only when it independently clears the output policy, so the- raw_secret_leak clamp still fails closed on anything the deterministic rebind cannot fix.- """- if OutputPolicyReason.RAW_SECRET_LEAK not in verdict.reason_codes:- return None+ """Rewrite scouted credential literals to parameter access before the output policy runs. A+ non-deferred function tool (as update_workflow is today) is invoked by the SDK from+ ``tool_context.tool_call.arguments``, so the rebound YAML must be written there and into+ ``tool_arguments``; returns None (leaving the original YAML for the clamp to fail closed on) when+ nothing was rebound, no tool_call is present, or the write-back fails."""ctx = getattr(tool_context, "context", None)if not isinstance(ctx, AgentContext):return Noneresult = rebind_scouted_credential_literals(workflow_yaml, ctx.scout_trajectory)if not result.changed:return None- recheck = evaluate_output_policy(- request_policy=ctx.request_policy,- workflow_yaml=result.workflow_yaml,- tool_arguments={**tool_arguments, "workflow_yaml": result.workflow_yaml},- )- if not recheck.allowed:+ tool_call = getattr(tool_context, "tool_call", None)+ if tool_call is None:+ LOG.warning("copilot rebound credential yaml has no tool_call to persist through; failing closed")return Nonetool_arguments["workflow_yaml"] = result.workflow_yamltry:- tool_context.tool_arguments = json.dumps(tool_arguments)+ rebound_arguments = json.dumps(tool_arguments)+ tool_call.arguments = rebound_arguments+ tool_context.tool_arguments = rebound_argumentsexcept (AttributeError, TypeError, ValueError):LOG.warning("copilot rebound credential yaml could not be written back to tool arguments")+ tool_arguments["workflow_yaml"] = workflow_yamlreturn Nonereturn result.workflow_yaml@@ -154,10 +152,13 @@ def _record_output_policy_guardrail_churn() -> None:if not isinstance(ctx, AgentContext):return+ reason_code_set = frozenset(reason.value for reason in verdict.reason_codes)+ previous_reason_codes = ctx.last_output_policy_reject_reason_codes+ frontier_unchanged = previous_reason_codes is not None and previous_reason_codes == reason_code_setstructural_payload = {"surface": "output_policy_tool_input","tool": tool_name,- "reason_codes": sorted(reason.value for reason in verdict.reason_codes),+ "reason_codes": sorted(reason_code_set),"workflow_yaml_hash": hashlib.sha256((workflow_yaml or "").encode("utf-8")).hexdigest(),}record_build_test_outcome(@@ -168,7 +169,12 @@ def _record_output_policy_guardrail_churn(structural_payload=structural_payload,),)- _record_code_authoring_guardrail_reject(ctx, defer_churn_stop=True)+ _record_code_authoring_guardrail_reject(+ ctx,+ defer_churn_stop=True,+ frontier_unchanged=frontier_unchanged,+ output_policy_reason_codes=reason_code_set,+ )_WORKFLOW_YAML_OUTPUT_POLICY_GUARDRAIL = ToolInputGuardrail(diff --git a/skyvern/forge/sdk/copilot/tools/scouting.py b/skyvern/forge/sdk/copilot/tools/scouting.pyindex 4beceb29c..bf2222aa0 100644--- a/skyvern/forge/sdk/copilot/tools/scouting.py+++ b/skyvern/forge/sdk/copilot/tools/scouting.py@@ -1452,7 +1452,7 @@ async def _auto_act_on_repeat(ctx: AgentContext, result: dict[str, Any], *, url:data = result.get("data")if not isinstance(data, dict):return False- server = getattr(ctx, "discovery_mcp_server", None)+ server = ctx.discovery_mcp_serverif server is None:return Falseselector = target["selector"]diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.pyindex fa0903243..58437d8ed 100644--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py@@ -13325,6 +13325,7 @@ async def _update_workflow(workflow_yaml, ctx)if typed_default_violations:+ _record_code_authoring_guardrail_reject(ctx)return reject(error="\n".join(typed_default_violations),user_facing_summary=_compiled_authoring_user_summary(),@@ -13470,6 +13471,7 @@ async def _update_workflow(metadata_scrubbed_by_imposition = Trueparameter_contract_error = _code_block_parameter_contract_error(workflow_yaml)if parameter_contract_error is not None:+ _record_code_authoring_guardrail_reject(ctx)return reject(error=parameter_contract_error,user_facing_summary=_compiled_authoring_user_summary(),@@ -13559,6 +13561,7 @@ async def _update_workflow(payload=payload,tool_name="update_workflow",)+ _record_code_authoring_guardrail_reject(ctx)return reject(error=str(reject_result["error"]),user_facing_summary=str(@@ -13966,14 +13969,17 @@ async def _update_workflow(prior_yaml = last_yaml if isinstance(last_yaml, str) and last_yaml else ctx.workflow_yamlstale_metadata = _detect_stale_block_metadata(workflow_yaml, prior_yaml)if stale_metadata:+ _record_code_authoring_guardrail_reject(ctx)return reject(error=_stale_block_metadata_message(stale_metadata))wait_block_error = _timing_only_challenge_wait_reject_message(ctx, workflow_yaml)if wait_block_error:+ _record_code_authoring_guardrail_reject(ctx)return reject(error=wait_block_error)challenge_http_error = _challenge_http_request_reject_message(ctx, workflow_yaml, ctx.workflow_yaml)if challenge_http_error:+ _record_code_authoring_guardrail_reject(ctx)return reject(error=challenge_http_error)# Post-emission reject of copilot-v2 writes that introduce a banned@@ -13987,14 +13993,17 @@ async def _update_workflow()if banned_items:_record_banned_block_reject_span("_update_workflow", banned_items)+ _record_code_authoring_guardrail_reject(ctx)return reject(error=_banned_block_reject_message(banned_items, ctx))download_scout_error = _download_scout_required_error(ctx, workflow_yaml)if download_scout_error:+ _record_code_authoring_guardrail_reject(ctx)return reject(error=download_scout_error)download_binding_error = _download_binding_required_error(ctx, workflow_yaml)if download_binding_error:+ _record_code_authoring_guardrail_reject(ctx)return reject(error=download_binding_error)composition_evidence_error = composition_page_evidence_error(ctx, workflow_yaml)@@ -14004,6 +14013,7 @@ async def _update_workflow(workflow_permanent_id=ctx.workflow_permanent_id,target_url=workflow_target_url(workflow_yaml),)+ _record_code_authoring_guardrail_reject(ctx)return reject(error=composition_evidence_error)# New data-write blocks default to surfacing failures rather than swallowing them.@@ -14288,6 +14298,7 @@ async def _update_workflow(ctx.persisted_draft_browser_calls = _workflow_yaml_browser_call_pairs(workflow_yaml)ctx.code_authoring_guardrail_reject_count = 0ctx.last_code_authoring_reject_was_credential_priority = False+ ctx.last_output_policy_reject_reason_codes = Nonectx.metadata_reject_ladder_state = None_clear_code_authoring_repair_context(ctx)_clear_held_churn_signals(ctx)diff --git a/tests/unit/test_copilot_banned_block_policy.py b/tests/unit/test_copilot_banned_block_policy.pyindex 3b6c1eae8..47ab89c46 100644--- a/tests/unit/test_copilot_banned_block_policy.py+++ b/tests/unit/test_copilot_banned_block_policy.py@@ -73,6 +73,8 @@ def _ctx(prior_yaml: str | None = None) -> MagicMock:ctx.workflow_id = "w_test"ctx.workflow_permanent_id = "wpid_test"ctx.organization_id = "o_test"+ ctx.code_authoring_guardrail_reject_count = 0+ ctx.recorded_build_test_outcome_history = []return ctxdiff --git a/tests/unit/test_copilot_hooks.py b/tests/unit/test_copilot_hooks.pyindex 92b711caa..57d036087 100644--- a/tests/unit/test_copilot_hooks.py+++ b/tests/unit/test_copilot_hooks.py@@ -13,6 +13,7 @@ import pytestfrom structlog.testing import capture_logsfrom skyvern.forge.sdk.copilot import hooks as hooks_module+from skyvern.forge.sdk.copilot import tools as tools_modulefrom skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignalfrom skyvern.forge.sdk.copilot.code_block_synthesis import dynamic_row_evidence_fingerprint, synthesize_code_blockfrom skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy@@ -1913,13 +1914,17 @@ class TestClickPostHookReachedDownloadTarget:@staticmethoddef _patch_scouting(monkeypatch: pytest.MonkeyPatch, *, page_evidence: dict[str, Any] | None) -> None:- from skyvern.forge.sdk.copilot.tools import mcp_hooks as mh-- monkeypatch.setattr(mh, "_clear_pending_browser_interaction_observation", lambda *_a, **_k: None)- monkeypatch.setattr(mh, "_consume_scout_source_url", lambda *_a, **_k: "http://localhost:8901/x/")- monkeypatch.setattr(mh, "_mark_pending_browser_interaction_observation", lambda *_a, **_k: None)- monkeypatch.setattr(mh, "_record_scouted_interaction", lambda *_a, **_k: None)- monkeypatch.setattr(mh, "_attach_scout_page_summary", lambda *_a, **_k: None)+ monkeypatch.setattr(+ tools_module.mcp_hooks, "_clear_pending_browser_interaction_observation", lambda *_a, **_k: None+ )+ monkeypatch.setattr(+ tools_module.mcp_hooks, "_consume_scout_source_url", lambda *_a, **_k: "http://localhost:8901/x/"+ )+ monkeypatch.setattr(+ tools_module.mcp_hooks, "_mark_pending_browser_interaction_observation", lambda *_a, **_k: None+ )+ monkeypatch.setattr(tools_module.mcp_hooks, "_record_scouted_interaction", lambda *_a, **_k: None)+ monkeypatch.setattr(tools_module.mcp_hooks, "_attach_scout_page_summary", lambda *_a, **_k: None)async def fake_resolve_url_title(_raw: Any, _ctx: Any) -> tuple[str, str]:return "http://localhost:8901/x/statement", "Statement"@@ -1930,9 +1935,9 @@ class TestClickPostHookReachedDownloadTarget:async def fake_register(*_a: Any, **_k: Any) -> tuple[int | None, dict[str, Any] | None]:return (1, page_evidence)- monkeypatch.setattr(mh, "_resolve_url_title", fake_resolve_url_title)- monkeypatch.setattr(mh, "_resolve_scout_role_name", fake_resolve_role_name)- monkeypatch.setattr(mh, "_register_scout_interaction_observation", fake_register)+ monkeypatch.setattr(tools_module.mcp_hooks, "_resolve_url_title", fake_resolve_url_title)+ monkeypatch.setattr(tools_module.mcp_hooks, "_resolve_scout_role_name", fake_resolve_role_name)+ monkeypatch.setattr(tools_module.mcp_hooks, "_register_scout_interaction_observation", fake_register)@staticmethoddef _ctx(policy: BlockAuthoringPolicy = BlockAuthoringPolicy.CODE_ONLY_BROWSER) -> Any: