Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(SKY-11531): Copilot loaded-result evaluate grounding (#6879)
Andrew Neilsonde75d71feaea
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-user.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-user.j2index c8c538df7..8c8d72a76 100644--- a/skyvern/forge/prompts/skyvern/workflow-copilot-user.j2+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-user.j2@@ -54,6 +54,14 @@ Overall goal (long-term memory):```{% endif %}+{% if loaded_result_context is defined and loaded_result_context %}+LOADED RESULT EXTRACTION TARGETS:++```+{{ loaded_result_context }}+```+{% endif %}+{% if not chat_history and not global_llm_context %}No previous context available.{% endif %}diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex 9485bff2a..bc482ecee 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -74,6 +74,8 @@ from skyvern.forge.sdk.copilot.context import (StructuredContext,TurnNarrativePayload,finalize_discovery_counter_in_global_llm_context,+ render_loaded_result_context_for_prompt,+ sanitize_global_llm_context_for_prompt,)from skyvern.forge.sdk.copilot.data_write_defaults import default_data_write_continue_on_failurefrom skyvern.forge.sdk.copilot.enforcement import (@@ -829,12 +831,15 @@ def _build_user_context(system-level content (the classic code-fence breakout)."""workflow_yaml = redact_raw_secrets_for_prompt(workflow_yaml or "")+ global_llm_context = sanitize_global_llm_context_for_prompt(global_llm_context)+ loaded_result_context = render_loaded_result_context_for_prompt(global_llm_context)return prompt_engine.load_prompt(template="workflow-copilot-user",workflow_yaml=escape_code_fences(workflow_yaml),workflow_summary=escape_code_fences(_build_workflow_summary(workflow_yaml)),chat_history=escape_code_fences(redact_raw_secrets_for_prompt(chat_history_text)),global_llm_context=escape_code_fences(redact_raw_secrets_for_prompt(global_llm_context)),+ loaded_result_context=escape_code_fences(redact_raw_secrets_for_prompt(loaded_result_context)),debug_run_info=escape_code_fences(redact_raw_secrets_for_prompt(debug_run_info_text)),request_policy_summary=escape_code_fences(redact_raw_secrets_for_prompt(request_policy_summary)),user_message=escape_code_fences(redact_raw_secrets_for_prompt(user_message)),@@ -3550,7 +3555,9 @@ async def _run_copilot_turn_impl(chat_history_text = _format_chat_history(chat_history)safe_chat_history_text = redact_raw_secrets_for_prompt(chat_history_text)safe_workflow_yaml = redact_raw_secrets_for_prompt(chat_request.workflow_yaml or "")- safe_global_llm_context = redact_raw_secrets_for_prompt(global_llm_context or "")+ safe_global_llm_context = sanitize_global_llm_context_for_prompt(+ redact_raw_secrets_for_prompt(global_llm_context or "")+ )previous_user_messages = [msg.content for msg in chat_history if msg.sender == "user"]previous_user_message = previous_user_messages[-1] if previous_user_messages else Nonediff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.pyindex d6fefb547..e991fad6a 100644--- a/skyvern/forge/sdk/copilot/context.py+++ b/skyvern/forge/sdk/copilot/context.py@@ -2,8 +2,10 @@from __future__ import annotations+import jsonimport reimport uuid+from collections.abc import Mappingfrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, Any, Literal, get_args@@ -12,6 +14,10 @@ from typing_extensions import NotRequired, TypedDictfrom skyvern.forge.sdk.copilot.build_phase import BuildPhasefrom skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy, CopilotConfig+from skyvern.forge.sdk.copilot.result_evidence import (+ LoadedResultCompositionEvidence,+ loaded_result_target_structure_signature,+)from skyvern.forge.sdk.copilot.runtime import AgentContextfrom skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerificationEvidencefrom skyvern.forge.sdk.workflow.models.workflow import Workflow@@ -134,6 +140,14 @@ class ObservedPage(BaseModel):reached_via: str = ""+class LoadedResultTargetContext(BaseModel):+ selector: str = ""+ is_table: bool = False+ row_selector: str = ""+ row_count: int | None = None+ structure_signature: str = ""++class CodeAuthoringRepairContext(BaseModel):block_label: strreason_code: str@@ -176,9 +190,14 @@ class StructuredContext(BaseModel):discovery_calls_made: int = 0page_inspection_calls_made: int = 0observed_acted_pages: list[ObservedPage] = Field(default_factory=list)+ loaded_result_targets: list[LoadedResultTargetContext] = Field(default_factory=list)def to_json_str(self) -> str:- return self.model_dump_json(indent=2)+ payload = self.model_dump(mode="json")+ payload["loaded_result_targets"] = [+ _sanitized_loaded_result_target_payload(target) for target in self.loaded_result_targets+ ]+ return json.dumps(payload, indent=2)@classmethoddef from_json_str(cls, raw: str | None) -> StructuredContext:@@ -263,6 +282,65 @@ class StructuredContext(BaseModel):self.credentials_checked = self.credentials_checked[-40:]+def _sanitized_loaded_result_target_payload(+ target: LoadedResultTargetContext,+) -> dict[str, object]:+ structure_signature = loaded_result_target_structure_signature(+ is_table=target.is_table,+ row_count=target.row_count,+ )+ return {+ "is_table": target.is_table,+ "row_count": target.row_count,+ "structure_signature": structure_signature,+ }+++def sanitize_global_llm_context_for_prompt(global_llm_context: str | None) -> str:+ raw = global_llm_context or ""+ if not raw:+ return ""+ try:+ payload = json.loads(raw)+ except json.JSONDecodeError:+ return raw+ if not isinstance(payload, dict):+ return raw+ targets = payload.get("loaded_result_targets")+ if not isinstance(targets, list):+ return raw++ sanitized_targets: list[dict[str, object]] = []+ for target in targets:+ if not isinstance(target, Mapping):+ continue+ try:+ target_context = LoadedResultTargetContext.model_validate(target)+ except Exception:+ continue+ sanitized_targets.append(_sanitized_loaded_result_target_payload(target_context))+ payload["loaded_result_targets"] = sanitized_targets+ return json.dumps(payload, indent=2)+++def render_loaded_result_context_for_prompt(global_llm_context: str) -> str:+ structured = StructuredContext.from_json_str(global_llm_context)+ if not structured.loaded_result_targets:+ return ""+ lines = [+ "Author an extraction or validation block from these loaded-result targets.",+ "Do not call evaluate just to re-read the same loaded results.",+ ]+ for index, target in enumerate(structured.loaded_result_targets, start=1):+ lines.append(f"- target {index}:")+ lines.append(f" table: {str(target.is_table).lower()}")+ if target.row_count is not None:+ lines.append(f" row_count: {target.row_count}")+ if target.structure_signature:+ lines.append(f" structure_signature: {target.structure_signature}")+ return "\n".join(lines)++_MAX_OBSERVED_ACTED_PAGES = 20@@ -290,6 +368,21 @@ def _merge_observed_acted_pages(prior: list[ObservedPage], flow_evidence: list[dreturn list(by_url.values())[-_MAX_OBSERVED_ACTED_PAGES:]+def _loaded_result_targets_from_steer(+ steer: LoadedResultCompositionEvidence | None,+) -> list[LoadedResultTargetContext]:+ if steer is None:+ return []+ return [+ LoadedResultTargetContext(+ is_table=target.is_table,+ row_count=target.row_count,+ structure_signature=target.structure_signature,+ )+ for target in steer.targets+ ]++def finalize_discovery_counter_in_global_llm_context(ctx: Any, raw_context: str | None) -> str | None:"""Fold the per-chat discovery counter into the outgoing global_llm_context.@@ -307,12 +400,23 @@ def finalize_discovery_counter_in_global_llm_context(ctx: Any, raw_context: strprior_inspections = int(getattr(ctx, "prior_page_inspection_calls_made", 0) or 0)inspections_this_turn = int(getattr(ctx, "page_inspection_calls_this_turn", 0) or 0)flow_evidence = getattr(ctx, "flow_evidence", None) or []- if not raw_context and this_turn == 0 and inspections_this_turn == 0 and not flow_evidence:+ loaded_result_targets = _loaded_result_targets_from_steer(+ getattr(ctx, "latest_evaluate_result_composition_steer", None)+ )+ if (+ not raw_context+ and this_turn == 0+ and inspections_this_turn == 0+ and not flow_evidence+ and not loaded_result_targets+ ):return Nonesc = StructuredContext.from_json_str(raw_context)sc.discovery_calls_made = prior + this_turnsc.page_inspection_calls_made = prior_inspections + inspections_this_turnsc.observed_acted_pages = _merge_observed_acted_pages(sc.observed_acted_pages, flow_evidence)+ # Replace with this turn's targets so stale extraction hints do not persist.+ sc.loaded_result_targets = loaded_result_targetsreturn sc.to_json_str()diff --git a/skyvern/forge/sdk/copilot/request_policy.py b/skyvern/forge/sdk/copilot/request_policy.pyindex af84f8cd8..8837fa2d5 100644--- a/skyvern/forge/sdk/copilot/request_policy.py+++ b/skyvern/forge/sdk/copilot/request_policy.py@@ -14,7 +14,7 @@ from skyvern.config import settingsfrom skyvern.forge import appfrom skyvern.forge.prompts import prompt_enginefrom skyvern.forge.sdk.copilot.config import CopilotConfig-from skyvern.forge.sdk.copilot.context import StructuredContext+from skyvern.forge.sdk.copilot.context import StructuredContext, sanitize_global_llm_context_for_promptfrom skyvern.forge.sdk.copilot.llm_errors import is_retriable_llm_errorfrom skyvern.forge.sdk.copilot.output_utils import parse_final_responsefrom skyvern.forge.sdk.copilot.secret_redaction import (@@ -1243,6 +1243,7 @@ async def _classify_request(# can distinguish unsafe secret use from redacted draft/spec conversion.# Timeout and exception fallbacks remain conservative blocks below.safe_user_message = redact_raw_secrets_for_prompt(user_message) if raw_secret_present else user_message+ safe_global_llm_context = sanitize_global_llm_context_for_prompt(global_llm_context)transcript = build_transcript_context(chat_history, safe_user_message)prompt = prompt_engine.load_prompt(template=PROMPT_NAME,@@ -1253,7 +1254,7 @@ async def _classify_request(latest_prior_user_turn=transcript.latest_prior_user_turn,latest_assistant_turn=transcript.latest_assistant_turn,retained_history=transcript.retained_history,- global_llm_context=escape_code_fences(redact_raw_secrets_for_prompt(global_llm_context)[:2048]),+ global_llm_context=escape_code_fences(redact_raw_secrets_for_prompt(safe_global_llm_context)[:2048]),active_completion_criteria=escape_code_fences(_render_active_criteria_for_prompt(active_criteria)),)raw, failure_kind, retry_count = await _run_request_policy_classifier(handler, prompt)diff --git a/skyvern/forge/sdk/copilot/result_evidence.py b/skyvern/forge/sdk/copilot/result_evidence.pyindex c0c23dbaf..9e87acefc 100644--- a/skyvern/forge/sdk/copilot/result_evidence.py+++ b/skyvern/forge/sdk/copilot/result_evidence.py@@ -2,8 +2,11 @@from __future__ import annotations+import hashlib+import jsonimport refrom collections.abc import Mapping+from copy import deepcopyfrom dataclasses import dataclassfrom typing import Any@@ -55,12 +58,33 @@ _TRANSIENT_RESULT_TEXT_PATTERNS = (),)_MAX_MEANINGFUL_DATA_DEPTH = 10+_MAX_LOADED_RESULT_TARGETS = 3+_MAX_SAMPLE_ROWS = 3+_MAX_SAMPLE_ROW_CHARS = 160+_MAX_TEXT_EXCERPT_CHARS = 240+_MAX_SELECTOR_CHARS = 240+_COMPOSITION_TARGET_SUMMARY_CHAR_BUDGET = 900+++@dataclass(frozen=True)+class LoadedResultCompositionTarget:+ selector: str = ""+ is_table: bool = False+ row_selector: str = ""+ row_count: int | None = None+ sample_rows: tuple[str, ...] = ()+ text_excerpt: str = ""+ structure_signature: str = ""+ evidence_source: str = ""+ observation_id: str = ""@dataclass(frozen=True)class LoadedResultCompositionEvidence:result_container_count: inttable_result_container_count: int+ targets: tuple[LoadedResultCompositionTarget, ...] = ()+ structure_signature: str = ""def _is_meaningful_data(value: Any, *, _depth: int = 0) -> bool:@@ -115,6 +139,191 @@ def _result_container_is_table(container: Mapping[str, Any]) -> bool:)+def _bounded_text(value: object, max_chars: int) -> str:+ text = str(value).strip()+ if len(text) <= max_chars:+ return text+ return text[: max_chars - 3].rstrip() + "..."+++def _bounded_optional_text(value: object, max_chars: int) -> str:+ return _bounded_text(value, max_chars) if isinstance(value, str) else ""+++def _sample_row_text(value: object) -> str:+ if isinstance(value, Mapping):+ try:+ return json.dumps(value, sort_keys=True, default=str)+ except Exception:+ return str(value)+ return str(value)+++def _bounded_sample_rows(container: Mapping[str, Any]) -> tuple[str, ...]:+ for key in ("sample_rows", "rows", "items"):+ raw_rows = container.get(key)+ if not isinstance(raw_rows, list):+ continue+ rows = tuple(+ _bounded_text(_sample_row_text(row), _MAX_SAMPLE_ROW_CHARS)+ for row in raw_rows[:_MAX_SAMPLE_ROWS]+ if _is_meaningful_data(row)+ )+ if rows:+ return rows+ return ()+++def _safe_row_count(value: object) -> int | None:+ if isinstance(value, int) and value >= 0:+ return value+ return None+++def _target_signature_payload(target: LoadedResultCompositionTarget) -> dict[str, object]:+ return {+ "is_table": target.is_table,+ "row_count": target.row_count,+ }+++def _structure_signature(payload: object) -> str:+ canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str)+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()+++def loaded_result_target_structure_signature(*, is_table: bool, row_count: int | None) -> str:+ return _structure_signature(+ {+ "is_table": is_table,+ "row_count": row_count,+ }+ )+++def _loaded_result_composition_target(container: Mapping[str, Any]) -> LoadedResultCompositionTarget:+ target = LoadedResultCompositionTarget(+ selector=_bounded_optional_text(container.get("selector"), _MAX_SELECTOR_CHARS),+ is_table=_result_container_is_table(container),+ row_selector=_bounded_optional_text(container.get("row_selector"), _MAX_SELECTOR_CHARS),+ row_count=_safe_row_count(container.get("row_count")),+ sample_rows=_bounded_sample_rows(container),+ text_excerpt=_bounded_optional_text(+ container.get("content_excerpt")+ or container.get("sample_text")+ or container.get("text")+ or container.get("text_excerpt")+ or container.get("visible_results_evidence"),+ _MAX_TEXT_EXCERPT_CHARS,+ ),+ evidence_source=_bounded_optional_text(container.get("evidence_source"), _MAX_SELECTOR_CHARS),+ observation_id=_bounded_optional_text(container.get("observation_id"), _MAX_SELECTOR_CHARS),+ )+ return LoadedResultCompositionTarget(+ selector=target.selector,+ is_table=target.is_table,+ row_selector=target.row_selector,+ row_count=target.row_count,+ sample_rows=target.sample_rows,+ text_excerpt=target.text_excerpt,+ structure_signature=loaded_result_target_structure_signature(+ is_table=target.is_table,+ row_count=target.row_count,+ ),+ evidence_source=target.evidence_source,+ observation_id=target.observation_id,+ )+++def _target_summary(target: LoadedResultCompositionTarget, *, include_samples: bool = True) -> dict[str, object]:+ summary: dict[str, object] = {+ "selector": target.selector,+ "is_table": target.is_table,+ }+ if target.row_selector:+ summary["row_selector"] = target.row_selector+ if target.row_count is not None:+ summary["row_count"] = target.row_count+ if include_samples and target.sample_rows:+ summary["sample_rows"] = list(target.sample_rows)+ if include_samples and target.text_excerpt:+ summary["text_excerpt"] = target.text_excerpt+ summary["structure_signature"] = target.structure_signature+ if target.evidence_source:+ summary["evidence_source"] = target.evidence_source+ if target.observation_id:+ summary["observation_id"] = target.observation_id+ return summary+++def _summary_with_targets(+ evidence: LoadedResultCompositionEvidence, targets: list[dict[str, object]]+) -> dict[str, object]:+ return {+ "result_container_count": evidence.result_container_count,+ "table_result_container_count": evidence.table_result_container_count,+ "targets": targets,+ "structure_signature": evidence.structure_signature,+ }+++def _summary_over_budget(summary: dict[str, object]) -> bool:+ return len(json.dumps(summary, default=str, separators=(",", ":"))) > _COMPOSITION_TARGET_SUMMARY_CHAR_BUDGET+++def _summary_len(summary: dict[str, object]) -> int:+ return len(json.dumps(summary, default=str, separators=(",", ":")))+++def _truncate_target_text_field_to_budget(+ summary: dict[str, object], target: dict[str, object], field_name: str+) -> None:+ value = target.get(field_name)+ if not isinstance(value, str) or not value:+ return+ while _summary_over_budget(summary) and len(value) > 8:+ overage = _summary_len(summary) - _COMPOSITION_TARGET_SUMMARY_CHAR_BUDGET+ trim_by = max(overage + 3, max(len(value) // 4, 1))+ next_len = max(8, len(value) - trim_by)+ value = value[:next_len].rstrip()+ target[field_name] = value + "..."+++def _cap_loaded_result_composition_summary(summary: dict[str, object]) -> dict[str, object]:+ capped = deepcopy(summary)+ if not _summary_over_budget(capped):+ return capped+ targets = capped.get("targets")+ if not isinstance(targets, list):+ return capped+ for target in targets:+ if isinstance(target, dict):+ target.pop("text_excerpt", None)+ if not _summary_over_budget(capped):+ return capped+ for target in targets:+ if isinstance(target, dict):+ target.pop("sample_rows", None)+ if not _summary_over_budget(capped):+ return capped+ for target in targets:+ if isinstance(target, dict):+ target.pop("evidence_source", None)+ target.pop("observation_id", None)+ if not _summary_over_budget(capped):+ return capped+ while len(targets) > 1 and _summary_over_budget(capped):+ targets.pop()+ if not targets or not isinstance(targets[0], dict) or not _summary_over_budget(capped):+ return capped+ first_target = targets[0]+ first_target.pop("row_selector", None)+ if not _summary_over_budget(capped):+ return capped+ _truncate_target_text_field_to_budget(capped, first_target, "selector")+ return capped++def loaded_result_composition_evidence_from_page(evidence: Mapping[str, Any],) -> LoadedResultCompositionEvidence | None:@@ -125,14 +334,17 @@ def loaded_result_composition_evidence_from_page(meaningful = [container for container in containers if _result_container_has_content(container)]if not meaningful:return None+ targets = tuple(+ _loaded_result_composition_target(container) for container in meaningful[:_MAX_LOADED_RESULT_TARGETS]+ )return LoadedResultCompositionEvidence(result_container_count=len(meaningful),table_result_container_count=sum(1 for container in meaningful if _result_container_is_table(container)),+ targets=targets,+ structure_signature=_structure_signature([_target_signature_payload(target) for target in targets]),)-def loaded_result_composition_target_summary(evidence: LoadedResultCompositionEvidence) -> dict[str, int]:- return {- "result_container_count": evidence.result_container_count,- "table_result_container_count": evidence.table_result_container_count,- }+def loaded_result_composition_target_summary(evidence: LoadedResultCompositionEvidence) -> dict[str, object]:+ summary = _summary_with_targets(evidence, [_target_summary(target) for target in evidence.targets])+ return _cap_loaded_result_composition_summary(summary)diff --git a/skyvern/forge/sdk/copilot/turn_intent.py b/skyvern/forge/sdk/copilot/turn_intent.pyindex 3640ed359..e6eb7a607 100644--- a/skyvern/forge/sdk/copilot/turn_intent.py+++ b/skyvern/forge/sdk/copilot/turn_intent.py@@ -14,7 +14,7 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validafrom skyvern.config import settingsfrom skyvern.forge.prompts import prompt_enginefrom skyvern.forge.sdk.api.llm.api_handler import LLMAPIHandler-from skyvern.forge.sdk.copilot.context import StructuredContext+from skyvern.forge.sdk.copilot.context import StructuredContext, sanitize_global_llm_context_for_promptfrom skyvern.forge.sdk.copilot.output_utils import parse_final_responsefrom skyvern.forge.sdk.copilot.request_policy import (RequestPolicy,@@ -579,6 +579,7 @@ async def classify_turn_intent(return TurnIntentClassifierResult.failure(TurnIntentClassifierFailureKind.MISSING_HANDLER)safe_user_message = redact_raw_secrets_for_prompt(user_message)+ safe_global_llm_context = sanitize_global_llm_context_for_prompt(global_llm_context)transcript = build_transcript_context(chat_history, safe_user_message)try:prompt = prompt_engine.load_prompt(@@ -597,7 +598,7 @@ async def classify_turn_intent(latest_assistant_turn=transcript.latest_assistant_turn,retained_history=transcript.retained_history,global_llm_context=escape_code_fences(- redact_raw_secrets_for_prompt(global_llm_context)[:_GLOBAL_CONTEXT_PROMPT_MAX_CHARS]+ redact_raw_secrets_for_prompt(safe_global_llm_context)[:_GLOBAL_CONTEXT_PROMPT_MAX_CHARS]),)except Exception as exc:diff --git a/skyvern/forge/sdk/routes/workflow_copilot.py b/skyvern/forge/sdk/routes/workflow_copilot.pyindex 03fcea93f..9d44a237e 100644--- a/skyvern/forge/sdk/routes/workflow_copilot.py+++ b/skyvern/forge/sdk/routes/workflow_copilot.py@@ -37,7 +37,13 @@ from skyvern.forge.sdk.copilot.completion_criteria_store import (plan_persistence,)from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy, CopilotConfig, normalize_block_authoring_policy-from skyvern.forge.sdk.copilot.context import AgentResult, ProposalDisposition, TurnNarrativePayload+from skyvern.forge.sdk.copilot.context import (+ AgentResult,+ ProposalDisposition,+ TurnNarrativePayload,+ render_loaded_result_context_for_prompt,+ sanitize_global_llm_context_for_prompt,+)from skyvern.forge.sdk.copilot.data_write_defaults import default_data_write_continue_on_failurefrom skyvern.forge.sdk.copilot.llm_config import resolve_main_copilot_handlerfrom skyvern.forge.sdk.copilot.output_utils import truncate_output@@ -1107,12 +1113,15 @@ async def copilot_call_llm(# Render user prompt (untrusted content, each variable in code fences)# Escape triple backticks to prevent code fence breakout+ prompt_global_llm_context = sanitize_global_llm_context_for_prompt(global_llm_context)+ loaded_result_context = render_loaded_result_context_for_prompt(prompt_global_llm_context)user_prompt = prompt_engine.load_prompt(template="workflow-copilot-user",workflow_yaml=escape_code_fences(chat_request.workflow_yaml or ""),user_message=escape_code_fences(chat_request.message),chat_history=escape_code_fences(chat_history_text),- global_llm_context=escape_code_fences(global_llm_context or ""),+ global_llm_context=escape_code_fences(prompt_global_llm_context),+ loaded_result_context=escape_code_fences(loaded_result_context),debug_run_info=escape_code_fences(debug_run_info_text),)@@ -1174,7 +1183,7 @@ async def copilot_call_llm(global_llm_context = action_data.get("global_llm_context")if global_llm_context is not None:- global_llm_context = str(global_llm_context)+ global_llm_context = sanitize_global_llm_context_for_prompt(str(global_llm_context))if action_type == "REPLACE_WORKFLOW":llm_workflow_yaml = default_data_write_continue_on_failure(@@ -1262,12 +1271,15 @@ async def _auto_correct_workflow_yaml(security_rules=security_rules,)+ prompt_global_llm_context = sanitize_global_llm_context_for_prompt(global_llm_context)+ loaded_result_context = render_loaded_result_context_for_prompt(prompt_global_llm_context)user_prompt = prompt_engine.load_prompt(template="workflow-copilot-user",workflow_yaml=escape_code_fences(workflow_yaml),user_message=escape_code_fences(f"Workflow YAML parsing failed, please fix it: {failure_reason}"),chat_history=escape_code_fences(_format_chat_history(new_chat_history)),- global_llm_context=escape_code_fences(global_llm_context or ""),+ global_llm_context=escape_code_fences(prompt_global_llm_context),+ loaded_result_context=escape_code_fences(loaded_result_context),debug_run_info=escape_code_fences(debug_run_info_text),)diff --git a/tests/unit/test_copilot_context.py b/tests/unit/test_copilot_context.pyindex de91cd093..ab3243a86 100644--- a/tests/unit/test_copilot_context.py+++ b/tests/unit/test_copilot_context.py@@ -2,9 +2,23 @@from __future__ import annotations+import json+from types import SimpleNamespacefrom unittest.mock import MagicMock-from skyvern.forge.sdk.copilot.context import ObservedPage, StructuredContext, _merge_observed_acted_pages+from skyvern.forge.sdk.copilot.context import (+ LoadedResultTargetContext,+ ObservedPage,+ StructuredContext,+ _merge_observed_acted_pages,+ finalize_discovery_counter_in_global_llm_context,+ render_loaded_result_context_for_prompt,+ sanitize_global_llm_context_for_prompt,+)+from skyvern.forge.sdk.copilot.result_evidence import (+ loaded_result_composition_evidence_from_page,+ loaded_result_target_structure_signature,+)def test_merge_turn_summary_caps_urls_visited() -> None:@@ -71,6 +85,205 @@ def test_resolved_credential_ids_survive_context_roundtrip() -> None:assert [check.credential_id for check in rehydrated.credentials_checked] == ["cred_amazon"]+def test_loaded_result_targets_roundtrip_without_selector_fields_or_legacy_signature() -> None:+ expected_signature = loaded_result_target_structure_signature(is_table=True, row_count=2)+ ctx = StructuredContext(+ loaded_result_targets=[+ LoadedResultTargetContext(+ selector="#results",+ is_table=True,+ row_selector="tr.statement",+ row_count=2,+ structure_signature="legacy-selector-derived-sig",+ )+ ]+ )++ raw = ctx.to_json_str()+ rehydrated = StructuredContext.from_json_str(ctx.to_json_str())++ assert "#results" not in raw+ assert "tr.statement" not in raw+ assert "legacy-selector-derived-sig" not in raw+ assert rehydrated.loaded_result_targets == [+ LoadedResultTargetContext(+ is_table=True,+ row_count=2,+ structure_signature=expected_signature,+ )+ ]+++def test_sanitize_global_llm_context_strips_loaded_result_selectors_and_recomputes_legacy_signature() -> None:+ expected_signature = loaded_result_target_structure_signature(is_table=True, row_count=2)+ raw = json.dumps(+ {+ "user_goal": "extract loaded results",+ "loaded_result_targets": [+ {+ "selector": '#account-123456-JaneCustomer-results[data-customer="Jane Customer"]',+ "is_table": True,+ "row_selector": 'tr[data-account="987654321"]',+ "row_count": 2,+ "sample_rows": ["Jane Customer account 123456"],+ "structure_signature": "legacy-selector-derived-sig",+ }+ ],+ }+ )++ sanitized = sanitize_global_llm_context_for_prompt(raw)++ assert "Jane" not in sanitized+ assert "Customer" not in sanitized+ assert "123456" not in sanitized+ assert "987654321" not in sanitized+ assert "legacy-selector-derived-sig" not in sanitized+ payload = json.loads(sanitized)+ assert payload["loaded_result_targets"] == [+ {+ "is_table": True,+ "row_count": 2,+ "structure_signature": expected_signature,+ }+ ]+++def test_sanitize_global_llm_context_recomputes_legacy_signature_without_selector_keys() -> None:+ expected_signature = loaded_result_target_structure_signature(is_table=True, row_count=2)+ raw = json.dumps(+ {+ "user_goal": "extract loaded results",+ "loaded_result_targets": [+ {+ "is_table": True,+ "row_count": 2,+ "structure_signature": "legacy-selector-derived-sig",+ }+ ],+ }+ )++ sanitized = sanitize_global_llm_context_for_prompt(raw)++ assert "legacy-selector-derived-sig" not in sanitized+ payload = json.loads(sanitized)+ assert payload["loaded_result_targets"] == [+ {+ "is_table": True,+ "row_count": 2,+ "structure_signature": expected_signature,+ }+ ]+++def test_finalize_context_persists_latest_loaded_result_targets_sanitizes_selectors() -> None:+ selector = '#account-123456-JaneCustomer-results[data-customer="Jane Customer"]'+ row_selector = 'tr[data-account="987654321"]'+ pii_steer = loaded_result_composition_evidence_from_page(+ {+ "result_containers": [+ {+ "tag": "table",+ "selector": selector,+ "row_selector": row_selector,+ "row_count": 2,+ "sample_rows": ["May 2026 $42.00"],+ "text": "Statement results",+ "evidence_source": "evaluate",+ "observation_id": "obs-1",+ }+ ]+ }+ )+ generic_steer = loaded_result_composition_evidence_from_page(+ {+ "result_containers": [+ {+ "tag": "table",+ "selector": "#results",+ "row_selector": "tr.statement",+ "row_count": 2,+ "sample_rows": ["May 2026 $42.00"],+ "text": "Statement results",+ "evidence_source": "evaluate",+ "observation_id": "obs-1",+ }+ ]+ }+ )+ assert pii_steer is not None+ assert generic_steer is not None+ assert pii_steer.structure_signature == generic_steer.structure_signature+ assert pii_steer.targets[0].structure_signature == generic_steer.targets[0].structure_signature++ ctx = SimpleNamespace(+ prior_discovery_calls_made=0,+ discovery_calls_this_turn=0,+ prior_page_inspection_calls_made=0,+ page_inspection_calls_this_turn=0,+ flow_evidence=[],+ latest_evaluate_result_composition_steer=pii_steer,+ )++ raw = finalize_discovery_counter_in_global_llm_context(ctx, None)++ assert raw is not None+ assert selector not in raw+ assert row_selector not in raw+ assert "Jane" not in raw+ assert "Customer" not in raw+ assert "123456" not in raw+ assert "987654321" not in raw+ assert "May 2026 $42.00" not in raw+ assert "Statement results" not in raw+ assert "evaluate" not in raw+ assert "obs-1" not in raw+ persisted_target = json.loads(raw)["loaded_result_targets"][0]+ assert persisted_target == {+ "is_table": True,+ "row_count": 2,+ "structure_signature": generic_steer.targets[0].structure_signature,+ }+ structured = StructuredContext.from_json_str(raw)+ assert structured.loaded_result_targets == [+ LoadedResultTargetContext(+ is_table=True,+ row_count=2,+ structure_signature=generic_steer.targets[0].structure_signature,+ )+ ]+++def test_finalize_context_clears_stale_loaded_result_targets_when_no_current_steer() -> None:+ stale_context = StructuredContext(+ user_goal="extract loaded results",+ loaded_result_targets=[+ LoadedResultTargetContext(+ is_table=True,+ row_count=2,+ structure_signature=loaded_result_target_structure_signature(is_table=True, row_count=2),+ )+ ],+ )+ ctx = SimpleNamespace(+ prior_discovery_calls_made=1,+ discovery_calls_this_turn=0,+ prior_page_inspection_calls_made=0,+ page_inspection_calls_this_turn=0,+ flow_evidence=[],+ latest_evaluate_result_composition_steer=None,+ )++ raw = finalize_discovery_counter_in_global_llm_context(ctx, stale_context.to_json_str())++ assert raw is not None+ payload = json.loads(raw)+ assert payload["loaded_result_targets"] == []+ assert StructuredContext.from_json_str(raw).loaded_result_targets == []+ assert render_loaded_result_context_for_prompt(raw) == ""++def test_merge_turn_summary_falls_back_to_summary_without_structured_credentials() -> None:ctx = StructuredContext()ctx.merge_turn_summary([{"tool": "list_credentials", "summary": "Found 0 credential(s)"}])diff --git a/tests/unit/test_copilot_request_policy_prompt.py b/tests/unit/test_copilot_request_policy_prompt.pyindex 0771a1de9..b755739bc 100644--- a/tests/unit/test_copilot_request_policy_prompt.py+++ b/tests/unit/test_copilot_request_policy_prompt.py@@ -1,5 +1,6 @@from __future__ import annotations+import jsonfrom datetime import datetime, timezonefrom pathlib import Path@@ -400,6 +401,44 @@ class TestActiveCriteriaPromptAnchor:assert "ACTIVE COMPLETION CRITERIA (canonical phrasing for the current goal):" not in captured["prompt"]+class TestLoadedResultContextPromptSanitization:+ @pytest.mark.asyncio+ async def test_request_policy_classifier_sanitizes_loaded_result_context_before_prompt(self) -> None:+ captured: dict[str, str] = {}+ raw_context = json.dumps(+ {+ "loaded_result_targets": [+ {+ "selector": '#account-123456-JaneCustomer-results[data-customer="Jane Customer"]',+ "is_table": True,+ "row_selector": 'tr[data-account="987654321"]',+ "row_count": 2,+ "structure_signature": "legacy-selector-derived-sig",+ }+ ]+ }+ )++ await _classify_request(+ user_message="build from the loaded results",+ workflow_yaml="",+ chat_history=[],+ global_llm_context=raw_context,+ handler=_capture_handler(captured),+ )++ prompt = captured["prompt"]+ for value in (+ "Jane",+ "Customer",+ "123456",+ "987654321",+ "legacy-selector-derived-sig",+ ):+ assert value not in prompt+ assert '"row_count": 2' in prompt++class TestClassifierFallbackCompletionCriteria:@pytest.mark.parametrize(("user_message", "expected_status", "expected_output_paths"),diff --git a/tests/unit/test_copilot_result_evidence.py b/tests/unit/test_copilot_result_evidence.pyindex 911f9e938..16b004c6a 100644--- a/tests/unit/test_copilot_result_evidence.py+++ b/tests/unit/test_copilot_result_evidence.py@@ -1,6 +1,12 @@from __future__ import annotations-from skyvern.forge.sdk.copilot.result_evidence import loaded_result_composition_evidence_from_page+import json++from skyvern.forge.sdk.copilot.result_evidence import (+ _COMPOSITION_TARGET_SUMMARY_CHAR_BUDGET,+ loaded_result_composition_evidence_from_page,+ loaded_result_composition_target_summary,+)def test_loaded_result_evidence_counts_populated_tables() -> None:@@ -16,6 +22,297 @@ def test_loaded_result_evidence_counts_populated_tables() -> None:assert evidence is not Noneassert evidence.result_container_count == 2assert evidence.table_result_container_count == 1+ assert loaded_result_composition_target_summary(evidence)["targets"] == [+ {+ "selector": "#results",+ "is_table": True,+ "row_count": 2,+ "structure_signature": evidence.targets[0].structure_signature,+ },+ {+ "selector": "#cards",+ "is_table": False,+ "sample_rows": ["May 2026 statement available"],+ "structure_signature": evidence.targets[1].structure_signature,+ },+ ]+++def test_loaded_result_target_summary_includes_bounded_table_rows() -> None:+ evidence = loaded_result_composition_evidence_from_page(+ {+ "result_containers": [+ {+ "tag": "table",+ "selector": "#results",+ "row_selector": "tr.statement",+ "row_count": 12,+ "sample_rows": [+ {"period": "May 2026", "amount": "$42.00", "download": "available"},+ {"period": "April 2026", "amount": "$39.00", "download": "available"},+ {"period": "March 2026", "amount": "$37.00", "download": "available"},+ {"period": "February 2026", "amount": "$34.00", "download": "available"},+ ],+ "observation_id": "obs-1",+ "evidence_source": "evaluate",+ }+ ],+ }+ )++ assert evidence is not None+ summary = loaded_result_composition_target_summary(evidence)+ assert summary["targets"] == [+ {+ "selector": "#results",+ "is_table": True,+ "row_selector": "tr.statement",+ "row_count": 12,+ "sample_rows": [+ '{"amount": "$42.00", "download": "available", "period": "May 2026"}',+ '{"amount": "$39.00", "download": "available", "period": "April 2026"}',+ '{"amount": "$37.00", "download": "available", "period": "March 2026"}',+ ],+ "structure_signature": evidence.targets[0].structure_signature,+ "evidence_source": "evaluate",+ "observation_id": "obs-1",+ }+ ]+++def test_loaded_result_target_summary_includes_bounded_non_table_text() -> None:+ evidence = loaded_result_composition_evidence_from_page(+ {+ "result_containers": [+ {+ "selector": "#cards",+ "text": "May 2026 statement available. Download link ready." * 20,+ "row_count": 1,+ }+ ],+ }+ )++ assert evidence is not None+ target = loaded_result_composition_target_summary(evidence)["targets"][0]+ assert target["selector"] == "#cards"+ assert target["is_table"] is False+ assert target["row_count"] == 1+ assert target["text_excerpt"].startswith("May 2026 statement available")+ assert len(target["text_excerpt"]) <= 240+++def test_loaded_result_structure_signature_ignores_selector_presence_and_text() -> None:+ variants = [+ loaded_result_composition_evidence_from_page(+ {"result_containers": [{"tag": "table", "row_count": 1, "sample_rows": ["May 2026"]}]}+ ),+ loaded_result_composition_evidence_from_page(+ {+ "result_containers": [+ {+ "tag": "table",+ "selector": "#results",+ "row_count": 1,+ "sample_rows": ["May 2026"],+ }+ ]+ }+ ),+ loaded_result_composition_evidence_from_page(+ {+ "result_containers": [+ {+ "tag": "table",+ "row_selector": "tr.statement",+ "row_count": 1,+ "sample_rows": ["May 2026"],+ }+ ]+ }+ ),+ loaded_result_composition_evidence_from_page(+ {+ "result_containers": [+ {+ "tag": "table",+ "selector": '#account-123456-JaneCustomer-results[data-customer="Jane Customer"]',+ "row_selector": 'tr[data-account="987654321"][data-customer="Jane Customer"]',+ "row_count": 1,+ "sample_rows": ["May 2026"],+ }+ ]+ }+ ),+ ]++ assert all(variant is not None for variant in variants)+ root_signatures = {variant.structure_signature for variant in variants if variant is not None}+ target_signatures = {variant.targets[0].structure_signature for variant in variants if variant is not None}+ assert len(root_signatures) == 1+ assert len(target_signatures) == 1+++def test_loaded_result_structure_signature_ignores_row_selector_text_changes() -> None:+ base = loaded_result_composition_evidence_from_page(+ {+ "result_containers": [+ {+ "selector": "#results",+ "row_selector": "tr.statement",+ "row_count": 1,+ "sample_rows": ["May 2026"],+ }+ ]+ }+ )+ row_selector_changed = loaded_result_composition_evidence_from_page(+ {+ "result_containers": [+ {+ "selector": "#results",+ "row_selector": 'tr[data-account="987654321"][data-customer="Jane Customer"]',+ "row_count": 1,+ "sample_rows": ["May 2026"],+ }+ ]+ }+ )++ assert base is not None+ assert row_selector_changed is not None+ assert base.structure_signature == row_selector_changed.structure_signature+ assert base.targets[0].structure_signature == row_selector_changed.targets[0].structure_signature+++def test_loaded_result_structure_signature_changes_for_structural_metadata() -> None:+ base = loaded_result_composition_evidence_from_page(+ {"result_containers": [{"selector": "#results", "row_count": 1, "sample_rows": ["May 2026"]}]}+ )+ row_count_changed = loaded_result_composition_evidence_from_page(+ {"result_containers": [{"selector": "#results", "row_count": 2, "sample_rows": ["May 2026"]}]}+ )+ table_shape_changed = loaded_result_composition_evidence_from_page(+ {+ "result_containers": [+ {+ "tag": "table",+ "selector": "#results",+ "row_count": 1,+ "sample_rows": ["May 2026"],+ }+ ]+ }+ )++ assert base is not None+ assert row_count_changed is not None+ assert table_shape_changed is not None+ assert base.structure_signature != row_count_changed.structure_signature+ assert base.targets[0].structure_signature != row_count_changed.targets[0].structure_signature+ assert base.structure_signature != table_shape_changed.structure_signature+ assert base.targets[0].structure_signature != table_shape_changed.targets[0].structure_signature+++def test_loaded_result_target_signature_ignores_sample_rows_and_text() -> None:+ first = loaded_result_composition_evidence_from_page(+ {+ "result_containers": [+ {+ "selector": "#results",+ "row_selector": "tr",+ "row_count": 1,+ "sample_rows": ["Jane Customer account 123"],+ "text": "Jane Customer balance due",+ }+ ]+ }+ )+ second = loaded_result_composition_evidence_from_page(+ {+ "result_containers": [+ {+ "selector": "#results",+ "row_selector": "tr",+ "row_count": 1,+ "sample_rows": ["Different Customer account 999"],+ "text": "Different Customer balance due",+ }+ ]+ }+ )++ assert first is not None+ assert second is not None+ assert first.targets[0].structure_signature == second.targets[0].structure_signature+++def test_loaded_result_target_signature_ignores_evidence_identity() -> None:+ first = loaded_result_composition_evidence_from_page(+ {+ "result_containers": [+ {+ "selector": "#results",+ "row_selector": "tr",+ "row_count": 1,+ "sample_rows": ["May 2026"],+ "evidence_source": "evaluate",+ "observation_id": "obs-1",+ }+ ]+ }+ )+ second = loaded_result_composition_evidence_from_page(+ {+ "result_containers": [+ {+ "selector": "#results",+ "row_selector": "tr",+ "row_count": 1,+ "sample_rows": ["May 2026"],+ "evidence_source": "inspect_page",+ "observation_id": "obs-2",+ }+ ]+ }+ )++ assert first is not None+ assert second is not None+ assert first.targets[0].structure_signature == second.targets[0].structure_signature+++def test_loaded_result_target_summary_enforces_internal_budget_for_max_structural_target() -> None:+ evidence = loaded_result_composition_evidence_from_page(+ {+ "result_containers": [+ {+ "tag": "table",+ "selector": "#results-" + ("s" * 240),+ "row_selector": "tr.statement-" + ("r" * 240),+ "row_count": 12,+ "sample_rows": ["Jane Customer account 123 " * 20],+ "text": "Jane Customer statement ready " * 20,+ "evidence_source": "evaluate-" + ("e" * 240),+ "observation_id": "obs-" + ("o" * 240),+ }+ ],+ }+ )++ assert evidence is not None+ summary = loaded_result_composition_target_summary(evidence)+ target = summary["targets"][0]+ assert len(json.dumps(summary, default=str, separators=(",", ":"))) <= _COMPOSITION_TARGET_SUMMARY_CHAR_BUDGET+ assert target["selector"].startswith("#results-")+ assert target["is_table"] is True+ assert target["row_count"] == 12+ assert target["structure_signature"]+ assert summary["structure_signature"]+ assert "sample_rows" not in target+ assert "text_excerpt" not in target+ assert "evidence_source" not in target+ assert "observation_id" not in targetdef test_caption_only_result_container_is_not_composition_evidence() -> None:diff --git a/tests/unit/test_copilot_turn_intent.py b/tests/unit/test_copilot_turn_intent.pyindex 063b4f907..c7af1a772 100644--- a/tests/unit/test_copilot_turn_intent.py+++ b/tests/unit/test_copilot_turn_intent.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+import jsonfrom datetime import datetime, timezonefrom types import SimpleNamespacefrom unittest.mock import MagicMock@@ -847,6 +848,48 @@ async def test_classify_turn_intent_escapes_code_fences_in_untrusted_inputs() ->assert f"```{sentinel}" not in prompt+async def test_classify_turn_intent_sanitizes_loaded_result_context_before_prompt() -> None:+ prompts: list[str] = []+ raw_context = json.dumps(+ {+ "loaded_result_targets": [+ {+ "selector": '#account-123456-JaneCustomer-results[data-customer="Jane Customer"]',+ "is_table": True,+ "row_selector": 'tr[data-account="987654321"]',+ "row_count": 2,+ "structure_signature": "legacy-selector-derived-sig",+ }+ ]+ }+ )++ async def handler(prompt: str, prompt_name: str, **_: object) -> dict[str, object]:+ prompts.append(prompt)+ return {"mode": "build", "expected_output": "workflow_draft", "reason_codes": []}++ await classify_turn_intent(+ user_message="build from the loaded results",+ workflow_yaml="",+ chat_history=[],+ global_llm_context=raw_context,+ request_policy=RequestPolicy(),+ handler=handler,+ )++ prompt = prompts[0]+ for value in (+ "Jane",+ "Customer",+ "123456",+ "987654321",+ "legacy-selector-derived-sig",+ ):+ assert value not in prompt+ assert '"row_count": 2' in prompt++@pytest.mark.asyncioasync def test_classify_turn_intent_reports_missing_handler_and_empty_message() -> None:async def handler(prompt: str, prompt_name: str, **_: object) -> dict[str, object]:diff --git a/tests/unit/test_evaluate_actionable_target.py b/tests/unit/test_evaluate_actionable_target.pyindex 8e02cf2e7..7d7275234 100644--- a/tests/unit/test_evaluate_actionable_target.py+++ b/tests/unit/test_evaluate_actionable_target.py@@ -63,6 +63,48 @@ def _row_result_packet() -> dict:}+def _max_loaded_result_packet() -> dict:+ large_text = "Jane Customer account 123 statement ready " * 40+ return {+ "forms": [],+ "navigation_targets": [{"selector": "#details", "text": "Details", "href": "/details"}],+ "result_containers": [+ {+ "tag": "table",+ "selector": f"#results-{index}-" + ("x" * 220),+ "row_selector": f"tr.statement-{index}-" + ("y" * 220),+ "text": large_text,+ "row_count": 100 + index,+ "sample_rows": [+ {"name": f"Jane Customer {index}", "account": "1234567890", "amount": "$999.99"},+ {"name": f"John Customer {index}", "account": "0987654321", "amount": "$888.88"},+ {"name": f"Pat Customer {index}", "account": "1111111111", "amount": "$777.77"},+ ],+ }+ for index in range(8)+ ],+ }+++def _single_max_structural_loaded_result_packet() -> dict:+ return {+ "forms": [],+ "navigation_targets": [],+ "result_containers": [+ {+ "tag": "table",+ "selector": "#single-result-" + ("s" * 240),+ "row_selector": "tr.single-row-" + ("r" * 240),+ "row_count": 1,+ "sample_rows": [{"name": "Jane Customer", "account": "1234567890", "amount": "$999.99"}],+ "text": "Jane Customer account 123 statement ready " * 30,+ "evidence_source": "evaluate-" + ("e" * 240),+ "observation_id": "obs-" + ("o" * 240),+ }+ ],+ }++def _ctx() -> AgentContext:return AgentContext.__new__(AgentContext)@@ -153,8 +195,20 @@ async def test_first_loaded_result_table_steers_to_composition_not_click_even_wiassert result["data"]["composition_targets"] == {"result_container_count": 1,"table_result_container_count": 1,+ "targets": [+ {+ "selector": "#results",+ "is_table": True,+ "row_count": 2,+ "sample_rows": ["Result A May 2026 $42.00", "Result B May 2026 $51.00"],+ "text_excerpt": "Results",+ "structure_signature": ctx.latest_evaluate_result_composition_steer.targets[0].structure_signature,+ }+ ],+ "structure_signature": ctx.latest_evaluate_result_composition_steer.structure_signature,}assert ctx.latest_evaluate_result_composition_steer.result_container_count == 1+ assert ctx.latest_evaluate_result_composition_steer.targets[0].selector == "#results"assert ctx.last_evaluate_actionable_signature is Noneassert ctx.last_evaluate_actionable_url is None@@ -176,6 +230,16 @@ async def test_first_loaded_result_rows_without_table_marker_steers_to_compositiassert result["data"]["composition_targets"] == {"result_container_count": 1,"table_result_container_count": 0,+ "targets": [+ {+ "selector": "#results",+ "is_table": False,+ "row_count": 1,+ "sample_rows": ["May 2026 statement available"],+ "structure_signature": ctx.latest_evaluate_result_composition_steer.targets[0].structure_signature,+ }+ ],+ "structure_signature": ctx.latest_evaluate_result_composition_steer.structure_signature,}@@ -287,6 +351,91 @@ async def test_first_loaded_result_table_sheds_large_payload_but_keeps_compositiassert "compose_extraction" in serialized+async def test_loaded_result_composition_targets_are_cap_aware_for_max_shaped_evaluate(monkeypatch) -> None:+ ctx = _ctx()+ ctx.last_evaluate_actionable_signature = None+ ctx.last_evaluate_actionable_url = None+ url = "https://app.example.com/results"++ async def fake(c, *, url):+ return _max_loaded_result_packet()++ monkeypatch.setattr(scouting, "_scout_act_observe_page_evidence", fake)+ big = "z" * 10000+ result = {+ "ok": True,+ "data": {+ "url": url,+ "title": "Loaded results",+ "result": {"html": big, "text": big},+ },+ }++ await scouting._maybe_steer_evaluate_to_action(ctx, result, url=url)++ serialized = json.dumps(result, default=str)+ composition_targets = result["data"]["composition_targets"]+ target = composition_targets["targets"][0]+ assert len(serialized) <= scouting._RECENT_TOOL_OUTPUT_CHAR_CAP+ assert result["data"]["next_action"] == "compose_extraction"+ assert composition_targets["result_container_count"] == 8+ assert composition_targets["table_result_container_count"] == 8+ assert len(composition_targets["targets"]) == 1+ assert target["selector"].startswith("#results-0-")+ assert target["is_table"] is True+ assert target["row_selector"].startswith("tr.statement-0-")+ assert target["row_count"] == 100+ assert target["structure_signature"]+ assert composition_targets["structure_signature"]+ assert "sample_rows" not in target+ assert "text_excerpt" not in target+ assert "Jane Customer" not in serialized+++async def test_single_loaded_result_structural_target_fits_evaluate_cap_with_url_title(monkeypatch) -> None:+ ctx = _ctx()+ ctx.last_evaluate_actionable_signature = None+ ctx.last_evaluate_actionable_url = None+ url = "https://app.example.com/results?" + ("query=value&" * 20)++ async def fake(c, *, url):+ return _single_max_structural_loaded_result_packet()++ monkeypatch.setattr(scouting, "_scout_act_observe_page_evidence", fake)+ big = "z" * 10000+ result = {+ "ok": True,+ "data": {+ "url": url,+ "title": "Loaded result " + ("summary " * 20),+ "result": {"html": big, "text": big},+ },+ }++ await scouting._maybe_steer_evaluate_to_action(ctx, result, url=url)++ serialized = json.dumps(result, default=str)+ composition_targets = result["data"]["composition_targets"]+ target = composition_targets["targets"][0]+ assert len(serialized) <= scouting._RECENT_TOOL_OUTPUT_CHAR_CAP+ assert result["data"]["next_action"] == "compose_extraction"+ assert composition_targets["result_container_count"] == 1+ assert composition_targets["table_result_container_count"] == 1+ assert len(composition_targets["targets"]) == 1+ assert target["selector"].startswith("#single-result-")+ assert target["is_table"] is True+ assert target["row_count"] == 1+ assert target["structure_signature"]+ assert composition_targets["structure_signature"]+ assert "sample_rows" not in target+ assert "text_excerpt" not in target+ assert "evidence_source" not in target+ assert "observation_id" not in target+ assert "Jane Customer" not in serialized++@pytest.mark.asyncioasync def test_repeat_nested_result_sheds_under_cap(monkeypatch) -> None:ctx = _ctx()diff --git a/tests/unit/test_workflow_copilot_prompt_injection.py b/tests/unit/test_workflow_copilot_prompt_injection.pyindex 87ee7c9e2..3efd4cc08 100644--- a/tests/unit/test_workflow_copilot_prompt_injection.py+++ b/tests/unit/test_workflow_copilot_prompt_injection.py@@ -7,13 +7,23 @@ Both sets of tests remain live while ENABLE_WORKFLOW_COPILOT_V2 is gatingthe dispatch."""+import jsonfrom unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom skyvern.forge.prompts import prompt_engine-from skyvern.forge.sdk.copilot.agent import _build_system_prompt, _build_user_context, _build_workflow_summary-from skyvern.forge.sdk.routes.workflow_copilot import copilot_call_llm+from skyvern.forge.sdk.copilot.agent import (+ _build_system_prompt,+ _build_user_context,+ _build_workflow_summary,+)+from skyvern.forge.sdk.copilot.context import (+ LoadedResultTargetContext,+ StructuredContext,+)+from skyvern.forge.sdk.copilot.result_evidence import loaded_result_target_structure_signature+from skyvern.forge.sdk.routes.workflow_copilot import _auto_correct_workflow_yaml, copilot_call_llmfrom skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotChatRequestfrom skyvern.utils.strings import escape_code_fences@@ -248,6 +258,138 @@ class TestCopilotCallLLMWiring:prompt_value = call_kwargs.kwargs.get("prompt") or call_kwargs.args[0]assert "SECURITY RULES:" not in prompt_value, "user prompt must not contain system instructions"+ @pytest.mark.asyncio+ async def test_copilot_call_llm_sanitizes_loaded_result_context_in_legacy_prompt_and_return(self) -> None:+ expected_signature = loaded_result_target_structure_signature(is_table=True, row_count=2)+ raw_context = json.dumps(+ {+ "loaded_result_targets": [+ {+ "selector": '#account-123456-JaneCustomer-results[data-customer="Jane Customer"]',+ "is_table": True,+ "row_selector": 'tr[data-account="987654321"]',+ "row_count": 2,+ "sample_rows": ["Jane Customer account 123456"],+ "text": "Jane Customer statement results",+ "structure_signature": "legacy-selector-derived-sig",+ }+ ]+ }+ )+ mock_handler = AsyncMock(+ return_value={+ "type": "REPLY",+ "user_response": "ok",+ "global_llm_context": raw_context,+ }+ )+ mock_stream = MagicMock()+ mock_stream.is_disconnected = AsyncMock(return_value=False)++ chat_request = WorkflowCopilotChatRequest(+ workflow_permanent_id="wpid_test",+ workflow_id="w_test",+ message="hello",+ workflow_yaml="title: Test\nworkflow_definition:\n blocks: []",+ )++ mock_agent_fn = MagicMock()+ mock_agent_fn.get_copilot_security_rules.return_value = "SECURITY RULES:\n- Test rule"++ with (+ patch(+ "skyvern.forge.sdk.routes.workflow_copilot.resolve_main_copilot_handler",+ return_value=mock_handler,+ ),+ patch("skyvern.forge.sdk.routes.workflow_copilot.app") as mock_app,+ ):+ mock_app.AGENT_FUNCTION = mock_agent_fn+ _user_response, _updated_workflow, returned_context, _workflow_yaml = await copilot_call_llm(+ stream=mock_stream,+ organization_id="o_test",+ chat_request=chat_request,+ chat_history=[],+ global_llm_context=raw_context,+ debug_run_info_text="",+ )++ prompt_value = mock_handler.call_args.kwargs["prompt"]+ assert returned_context is not None+ assert "LOADED RESULT EXTRACTION TARGETS" in prompt_value+ assert "Author an extraction or validation block from these loaded-result targets" in prompt_value+ assert "Do not call evaluate just to re-read the same loaded results" in prompt_value+ assert "table: true" in prompt_value+ assert "row_count: 2" in prompt_value+ assert f"structure_signature: {expected_signature}" in prompt_value+ for value in (+ "Jane",+ "Customer",+ "123456",+ "987654321",+ "sample_rows",+ "statement results",+ "legacy-selector-derived-sig",+ ):+ assert value not in prompt_value+ assert value not in returned_context+ assert '"row_count": 2' in prompt_value+ assert '"row_count": 2' in returned_context+ assert expected_signature in returned_context++ @pytest.mark.asyncio+ async def test_auto_correct_workflow_yaml_sanitizes_loaded_result_context_in_legacy_prompt(self) -> None:+ expected_signature = loaded_result_target_structure_signature(is_table=True, row_count=2)+ raw_context = json.dumps(+ {+ "loaded_result_targets": [+ {+ "selector": '#account-123456-JaneCustomer-results[data-customer="Jane Customer"]',+ "is_table": True,+ "row_selector": 'tr[data-account="987654321"]',+ "row_count": 2,+ "sample_rows": ["Jane Customer account 123456"],+ "text": "Jane Customer statement results",+ "structure_signature": "legacy-selector-derived-sig",+ }+ ]+ }+ )+ mock_handler = AsyncMock(return_value={"type": "REPLACE_WORKFLOW", "workflow_yaml": "title: Fixed"})+ mock_agent_fn = MagicMock()+ mock_agent_fn.get_copilot_security_rules.return_value = "SECURITY RULES:\n- Test rule"++ with patch("skyvern.forge.sdk.routes.workflow_copilot.app") as mock_app:+ mock_app.AGENT_FUNCTION = mock_agent_fn+ corrected_yaml = await _auto_correct_workflow_yaml(+ llm_api_handler=mock_handler,+ organization_id="o_test",+ user_response="drafted",+ workflow_yaml="title: Broken",+ chat_history=[],+ global_llm_context=raw_context,+ debug_run_info_text="",+ error=ValueError("bad yaml"),+ )++ assert corrected_yaml == "title: Fixed"+ prompt_value = mock_handler.call_args.kwargs["prompt"]+ assert "LOADED RESULT EXTRACTION TARGETS" in prompt_value+ assert "Author an extraction or validation block from these loaded-result targets" in prompt_value+ assert "Do not call evaluate just to re-read the same loaded results" in prompt_value+ assert "table: true" in prompt_value+ assert "row_count: 2" in prompt_value+ assert f"structure_signature: {expected_signature}" in prompt_value+ for value in (+ "Jane",+ "Customer",+ "123456",+ "987654321",+ "sample_rows",+ "statement results",+ "legacy-selector-derived-sig",+ ):+ assert value not in prompt_value+class TestAgentTemplateSecurity:"""Verify the agent template renders security rules correctly."""@@ -437,6 +579,68 @@ class TestBuildUserContext:)assert "``` injected ```" not in rendered+ def test_loaded_result_targets_render_authoring_instruction(self) -> None:+ expected_signature = loaded_result_target_structure_signature(is_table=True, row_count=2)+ context = StructuredContext(+ loaded_result_targets=[+ LoadedResultTargetContext(+ is_table=True,+ row_count=2,+ structure_signature="sig-1",+ )+ ]+ )++ rendered = _build_user_context(+ workflow_yaml="",+ chat_history_text="",+ global_llm_context=context.to_json_str(),+ debug_run_info_text="",+ user_message="build it",+ )++ assert "LOADED RESULT EXTRACTION TARGETS" in rendered+ assert "Author an extraction or validation block from these loaded-result targets" in rendered+ assert "Do not call evaluate just to re-read the same loaded results" in rendered+ assert "selector: #results" not in rendered+ assert "row_selector: tr.statement" not in rendered+ assert "table: true" in rendered+ assert "row_count: 2" in rendered+ assert f"structure_signature: {expected_signature}" in rendered++ def test_loaded_result_prompt_does_not_render_persisted_selectors_or_legacy_signature(self) -> None:+ context = StructuredContext(+ loaded_result_targets=[+ LoadedResultTargetContext(+ selector='#account-123456-JaneCustomer-results[data-customer="Jane Customer"]',+ is_table=True,+ row_selector='tr[data-account="987654321"]',+ row_count=2,+ structure_signature="legacy-selector-derived-sig",+ )+ ]+ )+ raw_context = json.dumps(context.model_dump(mode="json"))++ rendered = _build_user_context(+ workflow_yaml="",+ chat_history_text="",+ global_llm_context=raw_context or "",+ debug_run_info_text="",+ user_message="build it",+ )++ assert "LOADED RESULT EXTRACTION TARGETS" in rendered+ assert "table: true" in rendered+ assert "row_count: 2" in rendered+ assert "legacy-selector-derived-sig" not in rendered+ assert '#account-123456-JaneCustomer-results[data-customer="Jane Customer"]' not in rendered+ assert 'tr[data-account="987654321"]' not in rendered+ assert "Jane" not in rendered+ assert "Customer" not in rendered+ assert "123456" not in rendered+ assert "987654321" not in rendered+def test_workflow_summary_indexes_block_labels_and_error_mappings(self) -> None:workflow_yaml = """title: Invoice workflow