Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-10912 Promote scouted typed values into workflow inputs (#6586)
Andrew Neilson6d46bf71513e
diff --git a/skyvern/forge/sdk/copilot/code_block_synthesis.py b/skyvern/forge/sdk/copilot/code_block_synthesis.pyindex 0bdcc7ac5..12af9db4c 100644--- a/skyvern/forge/sdk/copilot/code_block_synthesis.py+++ b/skyvern/forge/sdk/copilot/code_block_synthesis.py@@ -286,6 +286,18 @@ def _param_key(interaction: Mapping[str, Any], used: set[str]) -> str:return _unique_key(_safe_param_base(name or role or "value"), used)+def _typed_value_identity(interaction: Mapping[str, Any]) -> tuple[str, str, str, str] | None:+ typed_value = str(interaction.get("typed_value") or "").strip()+ if not typed_value:+ return None+ return (+ typed_value,+ str(interaction.get("selector") or "").strip(),+ str(interaction.get("role") or "").strip(),+ str(interaction.get("accessible_name") or "").strip(),+ )++def _credential_param_key(interaction: Mapping[str, Any], used: set[str]) -> str:name = str(interaction.get("credential_name") or "").strip()return _unique_key(_safe_param_base(name or "credential"), used)@@ -303,6 +315,7 @@ def synthesize_code_block(parameters: list[dict[str, str]] = []diagnostics = SynthesisDiagnostics()used_param_keys: set[str] = set()+ typed_param_keys: dict[tuple[str, str, str, str], str] = {}credential_param_keys: dict[str, str] = {}entry_url = ""@@ -378,8 +391,17 @@ def synthesize_code_block(lines.append(f"{_INDENT}await {locator}.click()")lines.append(f'{_INDENT}await page.wait_for_load_state("load")')elif tool_name == "type_text":- param_key = _param_key(interaction, used_param_keys)- parameters.append({"key": param_key})+ typed_identity = _typed_value_identity(interaction)+ param_key = typed_param_keys.get(typed_identity) if typed_identity is not None else None+ if param_key is None:+ param_key = _param_key(interaction, used_param_keys)+ parameter = {"key": param_key}+ typed_value = str(interaction.get("typed_value") or "").strip()+ if typed_value:+ parameter["default_value"] = typed_value+ parameters.append(parameter)+ if typed_identity is not None:+ typed_param_keys[typed_identity] = param_keylines.append(f"{_INDENT}await {locator}.fill(str({param_key}))")elif tool_name == CREDENTIAL_FILL_TOOL_NAME:credential_id = str(interaction.get("credential_id") or "").strip()@@ -537,7 +559,16 @@ def render_synthesized_offer_text("```",]if param_keys:- parts.append("Workflow parameters referenced (bind these): " + ", ".join(param_keys) + ".")+ default_keys = [+ str(p.get("key") or "")+ for p in synthesized.parameters+ if p.get("key") and not p.get("credential_id") and p.get("default_value")+ ]+ line = "Workflow parameters referenced (bind these): " + ", ".join(param_keys) + "."+ line += " Bind each as `workflow_parameter_type: string`."+ if default_keys:+ line += " Server-side `default_value` is available for: " + ", ".join(default_keys) + "."+ parts.append(line)if credential_parameters:bindings = ", ".join(f"`{p['key']}` -> `{p['credential_id']}`" for p in credential_parameters)parts.append(diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.pyindex db6a1031f..931d3f1c1 100644--- a/skyvern/forge/sdk/copilot/runtime.py+++ b/skyvern/forge/sdk/copilot/runtime.py@@ -119,6 +119,7 @@ class ScoutedInteraction(TypedDict):selector: NotRequired[str]source_url: NotRequired[str]value: NotRequired[str]+ typed_value: NotRequired[str]key: NotRequired[str]typed_length: NotRequired[int]role: NotRequired[str]@@ -267,6 +268,7 @@ class AgentContext:synthesized_block_offered: bool = False# Source page of an in-flight scout action, captured before it may navigate away.pending_scout_source_url: str | None = None+ pending_scout_typed_value: str | None = None# Exact secret strings filled into the live browser this turn (passwords,# call-time-minted OTP codes). Page-readback tool results are exact-string# scrubbed against this set before being recorded or returned to the model.diff --git a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py b/skyvern/forge/sdk/copilot/tools/mcp_hooks.pyindex 3e3647236..b8eb3e1bd 100644--- a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py+++ b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py@@ -16,6 +16,7 @@ from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicyfrom skyvern.forge.sdk.copilot.context import CopilotContextfrom skyvern.forge.sdk.copilot.mcp_adapter import SchemaOverlayfrom skyvern.forge.sdk.copilot.runtime import AgentContext+from skyvern.forge.sdk.copilot.typed_value_policy import safe_typed_default_value, should_reject_type_text_valuefrom ._shared import _DISCOVERY_PER_CALL_TIMEOUT_SECONDSfrom .banned_blocks import (@@ -262,7 +263,27 @@ async def _type_text_pre_hook(ctx: AgentContext,) -> dict[str, Any] | None:await _capture_scout_source_url(ctx)- return _strip_intent_for_code_only_selector_action(params, ctx, tool_name="type_text")+ ctx.pending_scout_typed_value = None+ text = params.get("text")+ selector = str(params.get("selector") or "")+ intent = str(params.get("intent") or "")+ if should_reject_type_text_value(value=text, selector=selector, intent=intent):+ return {+ "ok": False,+ "error": (+ "type_text cannot type raw credentials, secrets, OTP/TOTP codes, API keys, tokens, or "+ "password-like values. Use the saved credential flow instead of inline secret text."+ ),+ }+ if isinstance(text, str) and text:+ ctx.pending_scout_typed_value = text+ result = _strip_intent_for_code_only_selector_action(params, ctx, tool_name="type_text")+ if result is not None:+ # Non-None means the deterministic targeting guard is rejecting the+ # tool call before browser execution; there will be no post-hook to+ # consume this value.+ ctx.pending_scout_typed_value = None+ return resultasync def _select_option_pre_hook(@@ -427,6 +448,8 @@ async def _type_text_post_hook() -> dict[str, Any]:_clear_pending_browser_interaction_observation(ctx)source_url = _consume_scout_source_url(ctx)+ pending_typed_value = ctx.pending_scout_typed_value+ ctx.pending_scout_typed_value = Noneif result.get("ok") and result.get("data"):data = result["data"]selector = data.get("selector", "")@@ -442,12 +465,26 @@ async def _type_text_post_hook(return landing_failure_mark_pending_browser_interaction_observation(ctx, tool_name="type_text", url=url)role, accessible_name = await _resolve_scout_role_name(ctx, selector)+ typed_value = (+ safe_typed_default_value(+ pending_typed_value,+ selector=selector,+ role=role,+ accessible_name=accessible_name,+ )+ if isinstance(typed_length, int)+ and typed_length > 0+ and isinstance(pending_typed_value, str)+ and len(pending_typed_value) == typed_length+ else None+ )_record_scouted_interaction(ctx,tool_name="type_text",selector=selector,source_url=source_url,typed_length=typed_length,+ typed_value=typed_value or "",role=role,accessible_name=accessible_name,)diff --git a/skyvern/forge/sdk/copilot/tools/scouting.py b/skyvern/forge/sdk/copilot/tools/scouting.pyindex ab17d9f25..294d53270 100644--- a/skyvern/forge/sdk/copilot/tools/scouting.py+++ b/skyvern/forge/sdk/copilot/tools/scouting.py@@ -195,6 +195,7 @@ def _record_scouted_interaction(selector: str = "",source_url: str | None = None,value: str = "",+ typed_value: str = "",key: str = "",typed_length: int = 0,role: str = "",@@ -215,6 +216,8 @@ def _record_scouted_interaction(artifact["source_url"] = source_url.strip()if value:artifact["value"] = value+ if typed_value:+ artifact["typed_value"] = typed_valueif key:artifact["key"] = keyif typed_length:diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.pyindex fac8d2aee..8d8c12a1b 100644--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py@@ -50,6 +50,7 @@ from skyvern.forge.sdk.copilot.workflow_credential_utils import credential_paramfrom skyvern.forge.sdk.routes.workflow_copilot import _process_workflow_yamlfrom skyvern.forge.sdk.workflow.exceptions import BaseWorkflowHTTPException, InsecureCodeDetectedfrom skyvern.forge.sdk.workflow.models.block import CodeBlock+from skyvern.forge.sdk.workflow.models.parameter import RESERVED_PARAMETER_KEYS, is_sensitive_workflow_parameterfrom skyvern.forge.sdk.workflow.models.workflow import Workflowfrom skyvern.schemas.proxy_location import ProxyLocationfrom skyvern.schemas.workflows import BlockType@@ -868,6 +869,251 @@ def _safe_singleton_literal_for_parameter(return literal, None+def _ast_column_offsets_are_utf8_bytes() -> bool:+ probe_code = 'await page.locator("#café-search").fill("x")'+ tree = _wrapped_code_ast(probe_code)+ if tree is None:+ LOG.debug("copilot_ast_column_offset_probe_fallback", reason="parse_failed")+ return True+ literal = next(+ (+ node.args[0]+ for node in ast.walk(tree)+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "fill"+ and node.args+ and isinstance(node.args[0], ast.Constant)+ and node.args[0].value == "x"+ ),+ None,+ )+ if literal is None:+ LOG.debug("copilot_ast_column_offset_probe_fallback", reason="literal_not_found")+ return True+ prefix = 'await page.locator("#café-search").fill('+ return literal.col_offset == 4 + len(prefix.encode("utf-8"))+++_AST_COLUMN_OFFSETS_ARE_UTF8_BYTES = _ast_column_offsets_are_utf8_bytes()+++def _wrapped_position_to_original_offset(code: str, lineno: int, col_offset: int) -> int | None:+ lines = code.splitlines(keepends=True)+ line_index = lineno - 2+ if line_index < 0 or line_index >= len(lines):+ return None+ column_offset = max(col_offset - 4, 0)+ if _AST_COLUMN_OFFSETS_ARE_UTF8_BYTES:+ # CPython reports AST column offsets as UTF-8 byte offsets in the+ # parsed source on our supported runtime, even when ast.parse receives+ # a str. Convert back to a Python string index after removing the+ # wrapper indent.+ column_chars = len(lines[line_index].encode("utf-8")[:column_offset].decode("utf-8", errors="ignore"))+ else:+ column_chars = column_offset+ return sum(len(line) for line in lines[:line_index]) + column_chars+++def _rewrite_direct_literal_fills(code: str, value_to_key: Mapping[str, str]) -> tuple[str, list[str]]:+ tree = _wrapped_code_ast(code)+ if tree is None:+ return code, []+ replacements: list[tuple[int, int, str, str]] = []+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call):+ continue+ func = node.func+ if not isinstance(func, ast.Attribute) or func.attr not in _SUBMITTED_LITERAL_METHODS:+ continue+ if not _is_page_locator_expression(func.value) or not node.args:+ continue+ first_arg = node.args[0]+ if not isinstance(first_arg, ast.Constant) or not isinstance(first_arg.value, str):+ continue+ key = value_to_key.get(first_arg.value)+ if key is None or first_arg.end_lineno is None or first_arg.end_col_offset is None:+ continue+ start = _wrapped_position_to_original_offset(code, first_arg.lineno, first_arg.col_offset)+ end = _wrapped_position_to_original_offset(code, first_arg.end_lineno, first_arg.end_col_offset)+ if start is None or end is None:+ continue+ replacements.append((start, end, f"str({key})", key))+ if not replacements:+ return code, []+ rewritten = code+ used_keys: list[str] = []+ for start, end, replacement, key in sorted(replacements, key=lambda item: item[0], reverse=True):+ rewritten = rewritten[:start] + replacement + rewritten[end:]+ if key not in used_keys:+ used_keys.append(key)+ return rewritten, list(reversed(used_keys))+++def _string_parameter_row(default_value: str, key: str) -> dict[str, Any]:+ return {+ "parameter_type": "workflow",+ "workflow_parameter_type": "string",+ "key": key,+ "default_value": default_value,+ }+++def _workflow_output_parameter_keys(parsed: dict[str, Any]) -> set[str]:+ return {+ f"{str(block.get('label') or '').strip()}_output"+ for block in workflow_blocks(parsed)+ if str(block.get("label") or "").strip()+ }+++def _plain_parameter_conflicts(parameter: Mapping[str, Any], default_value: str) -> bool:+ if is_sensitive_workflow_parameter(dict(parameter)):+ return True+ parameter_type = str(parameter.get("parameter_type") or "").lower()+ workflow_parameter_type = str(parameter.get("workflow_parameter_type") or "").lower()+ if parameter_type and parameter_type != "workflow":+ return True+ if workflow_parameter_type and workflow_parameter_type != "string":+ return True+ existing_default = parameter.get("default_value")+ return isinstance(existing_default, str) and existing_default not in {"", default_value}+++def _normalize_plain_parameter_row(parameter: dict[str, Any], default_value: str) -> None:+ if not isinstance(parameter.get("default_value"), str) or parameter.get("default_value") == "":+ parameter["default_value"] = default_value+ parameter["parameter_type"] = "workflow"+ parameter["workflow_parameter_type"] = "string"+++def _allocate_promoted_parameter_key(+ *,+ base_key: str,+ default_value: str,+ parameters: list[Any],+ reserved_keys: set[str],+) -> tuple[str, bool]:+ existing_by_key = {+ str(param.get("key")): param for param in parameters if isinstance(param, dict) and param.get("key")+ }+ base = base_key if base_key and base_key.isidentifier() else "typed_value"+ candidate = base+ suffix = 2+ while candidate in reserved_keys:+ candidate = f"{base}_{suffix}"+ suffix += 1+ # Termination is guaranteed because `existing_by_key` and `reserved_keys`+ # are finite while `suffix` increases monotonically.+ while True:+ existing = existing_by_key.get(candidate)+ if existing is None:+ return candidate, True+ if not _plain_parameter_conflicts(existing, default_value):+ return candidate, False+ candidate = f"{base}_{suffix}"+ suffix += 1+ while candidate in reserved_keys:+ candidate = f"{base}_{suffix}"+ suffix += 1+++def _apply_scouted_typed_default_promotions(workflow_yaml: str, ctx: AgentContext) -> tuple[str, list[str]]:+ if not getattr(ctx, "impose_synthesized_code_block", False):+ return workflow_yaml, []+ if _copilot_block_authoring_policy(ctx) != BlockAuthoringPolicy.CODE_ONLY_BROWSER:+ return workflow_yaml, []+ scout_trajectory = ctx.scout_trajectory+ if not isinstance(scout_trajectory, list) or not scout_trajectory:+ return workflow_yaml, []+ synthesized = synthesize_code_block(scout_trajectory)+ if synthesized is None:+ return workflow_yaml, []++ defaults_by_value: dict[str, list[str]] = {}+ for parameter in synthesized.parameters:+ if parameter.get("credential_id"):+ continue+ key = str(parameter.get("key") or "").strip()+ default_value = str(parameter.get("default_value") or "").strip()+ if key and default_value and not _SECRET_LIKE_LITERAL_RE.search(default_value):+ defaults_by_value.setdefault(default_value, []).append(key)+ ambiguous_key_sets = [sorted(set(keys)) for keys in defaults_by_value.values() if len(set(keys)) > 1]+ if ambiguous_key_sets:+ LOG.debug(+ "copilot_scouted_typed_default_promotion_ambiguous_values_skipped",+ ambiguous_value_count=len(ambiguous_key_sets),+ candidate_key_sets=ambiguous_key_sets,+ )+ value_to_key = {value: keys[0] for value, keys in defaults_by_value.items() if len(set(keys)) == 1}+ if not value_to_key:+ return workflow_yaml, []++ parsed = parse_workflow_yaml(workflow_yaml)+ if not isinstance(parsed, dict):+ return workflow_yaml, []+ workflow_definition = parsed.get("workflow_definition")+ if not isinstance(workflow_definition, dict):+ return workflow_yaml, []+ parameters = workflow_definition.get("parameters")+ if parameters is None:+ parameters = []+ workflow_definition["parameters"] = parameters+ if not isinstance(parameters, list):+ return workflow_yaml, ["Unable to bind typed workflow inputs: workflow_definition.parameters must be a list."]++ reserved_keys = set(RESERVED_PARAMETER_KEYS) | _workflow_output_parameter_keys(parsed)+ allocated_value_to_key: dict[str, str] = {}+ default_by_allocated_key: dict[str, str] = {}+ should_create_by_allocated_key: dict[str, bool] = {}+ for value, base_key in value_to_key.items():+ key, should_create = _allocate_promoted_parameter_key(+ base_key=base_key,+ default_value=value,+ parameters=parameters,+ reserved_keys=reserved_keys,+ )+ allocated_value_to_key[value] = key+ default_by_allocated_key[key] = value+ should_create_by_allocated_key[key] = should_create+ reserved_keys.add(key)++ any_rewrite = False+ used_promoted_keys: set[str] = set()+ for block in _workflow_code_blocks(parsed):+ code = str(block.get("code") or "")+ rewritten, used_keys = _rewrite_direct_literal_fills(code, allocated_value_to_key)+ if not used_keys:+ continue+ block["code"] = rewritten+ existing_keys = block.get("parameter_keys")+ merged_keys = (+ [str(key) for key in existing_keys if isinstance(key, str)] if isinstance(existing_keys, list) else []+ )+ for key in used_keys:+ if key not in merged_keys:+ merged_keys.append(key)+ used_promoted_keys.add(key)+ block["parameter_keys"] = merged_keys+ any_rewrite = True++ if not any_rewrite:+ return workflow_yaml, []++ existing_by_key = {+ str(param.get("key")): param for param in parameters if isinstance(param, dict) and param.get("key")+ }+ for key in sorted(used_promoted_keys):+ default_value = default_by_allocated_key.get(key, "")+ if should_create_by_allocated_key.get(key):+ parameters.append(_string_parameter_row(default_value, key))+ continue+ existing = existing_by_key.get(key)+ if isinstance(existing, dict):+ _normalize_plain_parameter_row(existing, default_value)+ return yaml.safe_dump(parsed, sort_keys=False), []++def _is_credential_parameter(parameter: Mapping[str, Any]) -> bool:parameter_type = str(parameter.get("parameter_type") or "").lower()workflow_parameter_type = str(parameter.get("workflow_parameter_type") or "").lower()@@ -992,6 +1238,19 @@ def _reconcile_synthesized_parameters()continue+ synthesized_default = str(synthesized_param.get("default_value") or "").strip()+ if synthesized_default:+ # Narrow defense-in-depth backstop for synthesized rows; values+ # captured from live type_text scouting are fully screened by+ # safe_typed_default_value before they enter the scout trajectory.+ if _SECRET_LIKE_LITERAL_RE.search(synthesized_default):+ violations.append(+ f"Unable to bind synthesized parameter `{key}`: synthesized default looks credential-like."+ )+ continue+ parameters.append(_string_parameter_row(synthesized_default, key))+ continue+typed_length = typed_lengths[0] if len(typed_lengths) == 1 else Nonesubmitted_parameter, error = _submitted_string_parameter_default(parameters,@@ -1571,6 +1830,13 @@ async def _update_workflow("user_facing_summary": _compiled_authoring_user_summary(),}workflow_yaml = imposition.workflow_yaml+ workflow_yaml, typed_default_violations = _apply_scouted_typed_default_promotions(workflow_yaml, ctx)+ if typed_default_violations:+ return {+ "ok": False,+ "error": "\n".join(typed_default_violations),+ "user_facing_summary": _compiled_authoring_user_summary(),+ }params["workflow_yaml"] = workflow_yamlscout_trajectory = getattr(ctx, "scout_trajectory", None)normalization = _normalize_code_artifact_metadata_detailed(diff --git a/skyvern/forge/sdk/copilot/typed_value_policy.py b/skyvern/forge/sdk/copilot/typed_value_policy.pynew file mode 100644index 000000000..18c56a597--- /dev/null+++ b/skyvern/forge/sdk/copilot/typed_value_policy.py@@ -0,0 +1,57 @@+from __future__ import annotations++import re++from skyvern.forge.sdk.copilot.request_policy import RAW_SECRET_PATTERNS, contains_email_password_pair++_SECRET_WORDS = r"password|passwd|passcode|token|secret|api[_ -]?key|credential|bearer|authorization|otp|totp|mfa|2fa"+_SECRET_WORD_VALUE_RE = re.compile(rf"^(?:{_SECRET_WORDS})$", re.I)+_SENSITIVE_TARGET_RE = re.compile(rf"(?:{_SECRET_WORDS}|current-password|one-time-code)", re.I)+_DEFAULT_TOKEN_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{2,63}$")+# Positive allow-list: only obvious reusable lookup/search fields may persist typed text as a default.+_DEFAULT_FIELD_ALLOW_RE = re.compile(r"(?:search|query|sku|entity|product|part|item|model|coupon|promo)", re.I)+_DEFAULT_FIELD_DENY_RE = re.compile(+ r"(?:email|phone|address|dob|birth|ssn|social|account|card|routing|username|password|secret|token|auth)",+ re.I,+)+++def typed_text_looks_secret(value: str) -> bool:+ text = value.strip()+ if not text:+ return False+ return (+ contains_email_password_pair(text)+ or _SECRET_WORD_VALUE_RE.fullmatch(text) is not None+ or any(pattern.search(text) for pattern in RAW_SECRET_PATTERNS)+ )+++def should_reject_type_text_value(*, value: object, selector: str = "", intent: str = "") -> bool:+ return (+ isinstance(value, str)+ and bool(value)+ and (typed_text_looks_secret(value) or _SENSITIVE_TARGET_RE.search(f"{selector} {intent}") is not None)+ )+++def safe_typed_default_value(+ value: object,+ *,+ selector: str = "",+ role: str = "",+ accessible_name: str = "",+) -> str | None:+ if not isinstance(value, str):+ return None+ text = value.strip()+ field_context = f"{selector} {role} {accessible_name}"+ if (+ not text+ or typed_text_looks_secret(text)+ or not _DEFAULT_TOKEN_RE.fullmatch(text)+ or _DEFAULT_FIELD_DENY_RE.search(field_context)+ or not _DEFAULT_FIELD_ALLOW_RE.search(field_context)+ ):+ return None+ return textdiff --git a/tests/unit/test_copilot_code_block_persist_seam.py b/tests/unit/test_copilot_code_block_persist_seam.pyindex 6e4da46f1..6b86ac6d1 100644--- a/tests/unit/test_copilot_code_block_persist_seam.py+++ b/tests/unit/test_copilot_code_block_persist_seam.py@@ -5,6 +5,7 @@ OSS-synced: only example.* / RFC-2606 placeholder targets and synthetic labels.from __future__ import annotations+import astimport textwrapfrom types import SimpleNamespace@@ -156,6 +157,36 @@ _SUBMITTED_MIXED_LITERAL_YAML = _yaml(""")+_SUBMITTED_TYPED_LITERAL_REWRITE_YAML = _yaml(+ """+ title: Product lookup+ workflow_definition:+ parameters:+ - {parameter_type: workflow, workflow_parameter_type: string, key: existing_filter, default_value: active}+ blocks:+ - block_type: code+ label: search_catalog+ parameter_keys: [existing_filter]+ code: |+ await page.locator("#café-search").fill("example_sku_123")+ - block_type: code+ label: select_result+ code: |+ await page.get_by_role("textbox", name="Search").type("example_sku_123")+ - block_type: loop+ label: retry_search+ loop_blocks:+ - block_type: code+ label: nested_search+ code: |+ await page.locator("#search").fill("example_sku_123")+ - block_type: code+ label: verify_cart+ code: |+ assert "example_sku_123" in await page.locator("#cart").inner_text()+ """+)+def _code_only_ctx() -> CopilotContext:ctx = CopilotContext(@@ -480,6 +511,23 @@ class TestCompiledAuthoringImposition:]return ctx+ def _typed_default_ctx(self) -> CopilotContext:+ ctx = _code_only_ctx()+ _enable_imposition(ctx)+ ctx.scout_trajectory = [+ {+ "tool_name": "type_text",+ "selector": "#search",+ "source_url": "https://example.com/catalog",+ "typed_length": 15,+ "typed_value": "example_sku_123",+ "role": "textbox",+ "accessible_name": "Search",+ "trajectory_index": 0,+ }+ ]+ return ctx+@pytest.mark.asyncioasync def test_imposes_strict_scout_selector_and_lifts_singleton_literal(self, monkeypatch: pytest.MonkeyPatch@@ -566,6 +614,19 @@ class TestCompiledAuthoringImposition:assert "imposed_substitutions" not in result["data"]assert ctx.workflow_yaml == _SUBMITTED_LITERAL_YAML+ @pytest.mark.asyncio+ async def test_flag_off_code_only_mode_does_not_promote_scouted_typed_defaults(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _stub_successful_update(monkeypatch)+ ctx = self._typed_default_ctx()+ ctx.impose_synthesized_code_block = False++ result = await _update_workflow({"workflow_yaml": _SUBMITTED_TYPED_LITERAL_REWRITE_YAML}, ctx)++ assert result["ok"] is True+ assert ctx.workflow_yaml == _SUBMITTED_TYPED_LITERAL_REWRITE_YAML+@pytest.mark.asyncioasync def test_unbound_synthesized_parameter_rejects_before_persist(self, monkeypatch: pytest.MonkeyPatch) -> None:_stub_successful_update(monkeypatch)@@ -641,6 +702,111 @@ class TestCompiledAuthoringImposition:assert "exactly one direct browser-locator string literal fill/type call" in result["error"]assert ctx.workflow_yaml == ""+ @pytest.mark.asyncio+ async def test_promotes_scouted_typed_literal_across_multiple_and_nested_code_blocks(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _stub_successful_update(monkeypatch)+ ctx = self._typed_default_ctx()++ result = await _update_workflow({"workflow_yaml": _SUBMITTED_TYPED_LITERAL_REWRITE_YAML}, ctx)++ assert result["ok"] is True+ parsed = parse_workflow_yaml(ctx.workflow_yaml)+ assert isinstance(parsed, dict)+ blocks = {str(block.get("label")): block for block in workflow_blocks(parsed)}+ assert "fill(str(search))" in blocks["search_catalog"]["code"]+ assert "type(str(search))" in blocks["select_result"]["code"]+ assert "fill(str(search))" in blocks["nested_search"]["code"]+ assert '"example_sku_123"' in blocks["verify_cart"]["code"]+ assert blocks["search_catalog"]["parameter_keys"] == ["existing_filter", "search"]+ assert blocks["select_result"]["parameter_keys"] == ["search"]+ assert blocks["nested_search"]["parameter_keys"] == ["search"]+ assert parsed["workflow_definition"]["parameters"] == [+ {+ "parameter_type": "workflow",+ "workflow_parameter_type": "string",+ "key": "existing_filter",+ "default_value": "active",+ },+ {+ "parameter_type": "workflow",+ "workflow_parameter_type": "string",+ "key": "search",+ "default_value": "example_sku_123",+ },+ ]++ @pytest.mark.asyncio+ async def test_scouted_typed_default_without_literal_rewrite_does_not_create_orphan_input(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _stub_successful_update(monkeypatch)+ ctx = self._typed_default_ctx()+ submitted_yaml = _SUBMITTED_TYPED_LITERAL_REWRITE_YAML.replace("example_sku_123", "other_sku_456")++ result = await _update_workflow({"workflow_yaml": submitted_yaml}, ctx)++ assert result["ok"] is True+ parsed = parse_workflow_yaml(ctx.workflow_yaml)+ assert isinstance(parsed, dict)+ assert parsed["workflow_definition"]["parameters"] == [+ {+ "parameter_type": "workflow",+ "workflow_parameter_type": "string",+ "key": "existing_filter",+ "default_value": "active",+ }+ ]+ for block in workflow_blocks(parsed):+ if str(block.get("block_type") or "").lower() == "code":+ assert "other_sku_456" in str(block.get("code") or "")+ assert "str(search)" not in str(block.get("code") or "")+++def test_direct_literal_rewrite_preserves_unicode_prefix_offsets() -> None:+ code = textwrap.dedent(+ """+ await page.locator("#café-search-résumé").fill("example_sku_123")+ await page.locator("#naïve-search").type("example_sku_123")+ """+ ).strip()++ rewritten, used_keys = workflow_update_module._rewrite_direct_literal_fills(code, {"example_sku_123": "search"})++ assert used_keys == ["search"]+ assert (+ rewritten+ == textwrap.dedent(+ """+ await page.locator("#café-search-résumé").fill(str(search))+ await page.locator("#naïve-search").type(str(search))+ """+ ).strip()+ )+++def test_python_ast_offsets_are_utf8_byte_offsets_for_unicode_source() -> None:+ code = 'await page.locator("#café-search-résumé").fill("example_sku_123")'+ tree = workflow_update_module._wrapped_code_ast(code)+ assert tree is not None+ fill_call = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "fill"+ and node.args+ )+ literal = fill_call.args[0]+ assert isinstance(literal, ast.Constant)+ assert literal.value == "example_sku_123"++ prefix = 'await page.locator("#café-search-résumé").fill('+ assert literal.col_offset == 4 + len(prefix.encode("utf-8"))+ assert literal.col_offset != 4 + len(prefix)+ assert workflow_update_module._AST_COLUMN_OFFSETS_ARE_UTF8_BYTES is True+class TestSeamSalvageIntoContext:@pytest.mark.asynciodiff --git a/tests/unit/test_copilot_code_block_synthesis.py b/tests/unit/test_copilot_code_block_synthesis.pyindex 970ae7cb3..c6b8533d7 100644--- a/tests/unit/test_copilot_code_block_synthesis.py+++ b/tests/unit/test_copilot_code_block_synthesis.py@@ -159,6 +159,43 @@ class TestActionSynthesis:# Raw typed value is never captured.assert "value" not in result.code+ def test_type_text_defaults_are_private_reused_only_for_same_field_identity(self) -> None:+ def typed(selector: str, name: str, url: str = "https://example.com/") -> dict[str, Any]:+ return _interaction(+ "type_text",+ selector=selector,+ source_url=url,+ typed_length=15,+ typed_value="example_sku_123",+ role="textbox",+ accessible_name=name,+ )++ safe = synthesize_code_block([typed('role=textbox[name="Search"]', "Search")])+ assert safe is not None+ assert 'await page.get_by_role("textbox", name="Search").fill(str(search))' in safe.code+ assert "example_sku_123" not in safe.code+ assert safe.parameters == [{"key": "search", "default_value": "example_sku_123"}]++ offer_text = render_synthesized_offer_text(safe)+ assert "workflow_parameter_type: string" in offer_text+ assert "default_value" in offer_text+ assert "example_sku_123" not in offer_text++ reused = synthesize_code_block(+ [typed("#search", "Search"), typed("#search", "Search", "https://example.com/results")]+ )+ assert reused is not None+ assert reused.parameters == [{"key": "search", "default_value": "example_sku_123"}]+ assert reused.code.count("fill(str(search))") == 2++ distinct = synthesize_code_block([typed("#part-number", "Part Number"), typed("#coupon", "Coupon Code")])+ assert distinct is not None+ assert distinct.parameters == [+ {"key": "part_number", "default_value": "example_sku_123"},+ {"key": "coupon_code", "default_value": "example_sku_123"},+ ]+def test_goto_entry_url_and_load_state(self) -> None:result = synthesize_code_block([_interaction("click", selector="#go", source_url="https://example.com/start")])assert result is not Nonediff --git a/tests/unit/test_copilot_hooks.py b/tests/unit/test_copilot_hooks.pyindex 86e6fbe7b..55747cf21 100644--- a/tests/unit/test_copilot_hooks.py+++ b/tests/unit/test_copilot_hooks.py@@ -839,6 +839,7 @@ class TestBrowserInteractionObservationHooks:ctx = SimpleNamespace(pending_browser_interaction_observation=None,+ pending_scout_typed_value=None,discovery_mcp_server=None,scouted_interactions=[],scout_trajectory=[],@@ -869,6 +870,7 @@ class TestBrowserInteractionObservationHooks:tool_name="click",url="https://example.com/results",),+ pending_scout_typed_value=None,discovery_mcp_server=None,scouted_interactions=[],scout_trajectory=[],@@ -897,6 +899,7 @@ class TestBrowserInteractionObservationHooks:monkeypatch.setattr(tools_module.mcp_hooks, "_verify_scout_type_landed", fake_verify)ctx = SimpleNamespace(pending_browser_interaction_observation=None,+ pending_scout_typed_value=None,discovery_mcp_server=None,scouted_interactions=[],scout_trajectory=[],@@ -920,6 +923,7 @@ class TestScoutedInteractionCapture:def _ctx(self, *, policy: object = None, source_url: str | None = None) -> SimpleNamespace:ns = SimpleNamespace(pending_browser_interaction_observation=None,+ pending_scout_typed_value=None,discovery_mcp_server=None,scouted_interactions=[],scout_trajectory=[],diff --git a/tests/unit/test_copilot_scout_act_observe.py b/tests/unit/test_copilot_scout_act_observe.pyindex 2eade1c79..32b36be8d 100644--- a/tests/unit/test_copilot_scout_act_observe.py+++ b/tests/unit/test_copilot_scout_act_observe.py@@ -67,6 +67,7 @@ def _bounded_extractor_payload() -> dict[str, Any]:def _ctx(*, server: Any = None, source_url: str | None = _SOURCE_URL) -> SimpleNamespace:return SimpleNamespace(pending_browser_interaction_observation=None,+ pending_scout_typed_value=None,discovery_mcp_server=server,scouted_interactions=[],scout_trajectory=[],diff --git a/tests/unit/test_copilot_typed_value_policy.py b/tests/unit/test_copilot_typed_value_policy.pynew file mode 100644index 000000000..3b8237b18--- /dev/null+++ b/tests/unit/test_copilot_typed_value_policy.py@@ -0,0 +1,73 @@+from __future__ import annotations++from types import SimpleNamespace++import pytest++from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy+from skyvern.forge.sdk.copilot.tools.mcp_hooks import _type_text_pre_hook+from skyvern.forge.sdk.copilot.typed_value_policy import safe_typed_default_value, should_reject_type_text_value+++async def test_type_text_policy_rejects_sensitive_targets_and_stashes_safe_defaults() -> None:+ ctx = SimpleNamespace(+ organization_id="o",+ browser_session_id=None,+ pending_scout_source_url=None,+ pending_scout_typed_value=None,+ block_authoring_policy=BlockAuthoringPolicy.CODE_ONLY_BROWSER,+ )++ rejected = await _type_text_pre_hook({"selector": "input[type=password]", "text": "hunter2"}, ctx)+ assert rejected is not None+ assert rejected["ok"] is False+ assert "hunter2" not in rejected["error"]+ assert ctx.pending_scout_typed_value is None++ allowed = await _type_text_pre_hook({"selector": "#search", "text": "example_sku_123"}, ctx)+ assert allowed is None+ assert ctx.pending_scout_typed_value == "example_sku_123"+++async def test_type_text_pre_hook_clears_stashed_default_only_on_guard_short_circuit() -> None:+ ctx = SimpleNamespace(+ organization_id="o",+ browser_session_id=None,+ pending_scout_source_url=None,+ pending_scout_typed_value=None,+ block_authoring_policy=BlockAuthoringPolicy.CODE_ONLY_BROWSER,+ workflow_persisted=True,+ last_full_workflow_test_ok=True,+ )++ params = {"selector": "#search", "intent": "search catalog", "text": "example_sku_123"}+ allowed = await _type_text_pre_hook(params, ctx)++ assert allowed is None+ assert params["intent"] is None+ assert ctx.pending_scout_typed_value == "example_sku_123"++ rejected = await _type_text_pre_hook({"intent": "search catalog", "text": "example_sku_123"}, ctx)++ assert rejected is not None+ assert rejected["ok"] is False+ assert ctx.pending_scout_typed_value is None+++def test_safe_typed_default_policy_allows_search_tokens_not_pii_like_values() -> None:+ def default(value: str, selector: str, name: str) -> str | None:+ return safe_typed_default_value(value, selector=selector, role="textbox", accessible_name=name)++ assert default("example_sku_123", "#search", "Search") == "example_sku_123"+ assert default("Jane Doe", "#search", "Search") is None+ assert default("[email protected]", "#search", "Search") is None+ assert default("example_sku_123", "#email", "Email") is None+++def test_type_text_rejection_allows_benign_secret_word_search_phrases() -> None:+ assert should_reject_type_text_value(value="password manager", selector="#search", intent="search catalog") is False+ assert should_reject_type_text_value(value="2fa setup", selector="#search", intent="search help") is False+ assert should_reject_type_text_value(value="password", selector="#search", intent="search catalog") is True+ assert should_reject_type_text_value(value="password manager", selector="input[type=password]", intent="") is True