Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat(SKY-9938): typed workflow-change section in copilot turn context (#6095)
Andrew Neilson298e49c881f3
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2index 505a8f5e7..48f7a286d 100644--- a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2@@ -139,6 +139,9 @@ When the user reports a problem with workflow output (duplicates, missing data,4. Fix: Modify the workflow to address the root cause, then call update_workflow or update_and_run_blocks as required by the workflow submission/testing rules.5. Explain: Tell the user what you found and what you changed.+USER WORKFLOW CHANGES SINCE LAST COPILOT TURN:+When the user message carries a `USER WORKFLOW CHANGES SINCE LAST COPILOT TURN` slot reading `user_modified_since_last_turn`, the user edited the workflow YAML between turns and the current workflow YAML above already reflects that edit. Do NOT ask the user to describe their changes — read the modified YAML and act on it (assess it if they asked for review, or build on top of it if their message implies more work). When the slot reads `structural diff unavailable`, the edit landed but a precise summary could not be computed — read the current YAML directly to identify what changed.+IMPORTANT WORKFLOW RULES:* Always generate valid YAML that conforms to the Skyvern workflow schema.* NEVER emit "task" or "task_v2" blocks. They are not supported by the workflow copilot and will be rejected at schema lookup. Decompose the work into specific block types instead:diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-user.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-user.j2index b4b4fe131..e0e72fe6c 100644--- a/skyvern/forge/prompts/skyvern/workflow-copilot-user.j2+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-user.j2@@ -20,6 +20,14 @@ Workflow block summary:Use this summary as a block-label index, then inspect the full workflow definition above for exact block details.{% endif %}+{% if user_workflow_change_summary is defined and user_workflow_change_summary %}+USER WORKFLOW CHANGES SINCE LAST COPILOT TURN:++```+{{ user_workflow_change_summary }}+```+{% endif %}+PREVIOUS CONTEXT:{% if chat_history %}diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex 4536c4694..9db6e5e9d 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -330,6 +330,7 @@ def _store_turn_context_packet_on_context(chat_request: WorkflowCopilotChatRequest,chat_history: list[WorkflowCopilotChatHistoryMessage],debug_run_info_text: str,+ prior_copilot_workflow_yaml: str | None,) -> None:if not isinstance(ctx.turn_intent, TurnIntent):return@@ -339,6 +340,7 @@ def _store_turn_context_packet_on_context(request_policy=request_policy,user_message=chat_request.message,workflow_yaml=chat_request.workflow_yaml or "",+ prior_workflow_yaml=prior_copilot_workflow_yaml or "",chat_history=chat_history,debug_run_info_text=debug_run_info_text,)@@ -407,6 +409,7 @@ def _build_user_context(debug_run_info_text: str,user_message: str,request_policy_summary: str = "",+ user_workflow_change_summary: str = "",) -> str:"""Render untrusted context into the user message with code fencing.@@ -428,6 +431,7 @@ def _build_user_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)),+ user_workflow_change_summary=escape_code_fences(user_workflow_change_summary or ""),)@@ -1494,6 +1498,7 @@ async def run_copilot_agent(security_rules: str = "",config: CopilotConfig | None = None,turn_index: int | None = None,+ prior_copilot_workflow_yaml: str | None = None,) -> AgentResult:# Initialize tracing before opening the turn span so Logfire's OTel provider# is installed; otherwise the very first turn lands the parent span on@@ -1515,6 +1520,7 @@ async def run_copilot_agent(api_key=api_key,security_rules=security_rules,config=config,+ prior_copilot_workflow_yaml=prior_copilot_workflow_yaml,)@@ -1530,6 +1536,7 @@ async def _run_copilot_turn_impl(api_key: str | None,security_rules: str,config: CopilotConfig | None,+ prior_copilot_workflow_yaml: str | None = None,) -> AgentResult:copilot_config = config or CopilotConfig(security_rules=security_rules)chat_history_text = _format_chat_history(chat_history)@@ -1613,6 +1620,7 @@ async def _run_copilot_turn_impl(chat_request=chat_request,chat_history=chat_history,debug_run_info_text=debug_run_info_text,+ prior_copilot_workflow_yaml=prior_copilot_workflow_yaml,)if request_policy is not None and request_policy_guardrail_result.output.tripwire_triggered:return _build_request_policy_clarification_result(@@ -1692,12 +1700,20 @@ async def _run_copilot_turn_impl(config=copilot_config,)+ user_workflow_change_summary = ""+ if (+ isinstance(ctx.turn_context_packet, TurnContextPacket)+ and ctx.turn_context_packet.workflow_change_context is not None+ ):+ user_workflow_change_summary = ctx.turn_context_packet.workflow_change_context.rendered_summary+user_message = _build_user_context(workflow_yaml=safe_workflow_yaml,chat_history_text=safe_chat_history_text,global_llm_context=safe_global_llm_context,debug_run_info_text=redact_raw_secrets_for_prompt(debug_run_info_text),user_message=agent_user_message,+ user_workflow_change_summary=user_workflow_change_summary,)LOG.info(diff --git a/skyvern/forge/sdk/copilot/turn_context.py b/skyvern/forge/sdk/copilot/turn_context.pyindex d4fadc4ec..90bc99a8e 100644--- a/skyvern/forge/sdk/copilot/turn_context.py+++ b/skyvern/forge/sdk/copilot/turn_context.py@@ -11,6 +11,7 @@ from skyvern.forge.sdk.copilot.request_policy import (redact_raw_secrets_for_prompt,)from skyvern.forge.sdk.copilot.turn_intent import RequiredContextKey, TurnIntent, TurnIntentMode+from skyvern.forge.sdk.copilot.workflow_change_summary import WorkflowChangeKind, summarize_user_workflow_changefrom skyvern.forge.sdk.schemas.credentials import Credentialfrom skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotChatHistoryMessage, WorkflowCopilotChatSender@@ -46,6 +47,12 @@ class ProposalContext(BaseModel):truncated: bool = False+class WorkflowChangeContext(BaseModel):+ kind: str+ rendered_summary: str+ structural_diff_unavailable: bool = False++class TranscriptContext(BaseModel):earliest_user_turn: strlatest_prior_user_turn: str@@ -85,6 +92,7 @@ class TurnContextPacket(BaseModel):turn_intent_summary: dict[str, Any]workflow_context: WorkflowContext | None = Noneproposal_context: ProposalContext | None = None+ workflow_change_context: WorkflowChangeContext | None = Nonetranscript_context: TranscriptContextrun_context: RunContext | None = Nonecredential_context: CredentialContext | None = None@@ -92,7 +100,14 @@ class TurnContextPacket(BaseModel):omissions: list[TurnContextOmission] = Field(default_factory=list)def to_trace_data(self) -> dict[str, Any]:- section_fields = ("workflow_context", "proposal_context", "run_context", "credential_context", "docs_context")+ section_fields = (+ "workflow_context",+ "proposal_context",+ "workflow_change_context",+ "run_context",+ "credential_context",+ "docs_context",+ )return {"mode": self.turn_intent_summary.get("mode"),"sections": [field for field in section_fields if getattr(self, field) is not None],@@ -101,6 +116,7 @@ class TurnContextPacket(BaseModel):"workflow_truncated": bool(self.workflow_context and self.workflow_context.truncated),"proposal_truncated": bool(self.proposal_context and self.proposal_context.truncated),"run_truncated": bool(self.run_context and self.run_context.truncated),+ "workflow_change_kind": self.workflow_change_context.kind if self.workflow_change_context else None,}@@ -111,6 +127,7 @@ class TurnContextInputs(BaseModel):request_policy: RequestPolicyuser_message: str = ""workflow_yaml: str = ""+ prior_workflow_yaml: str = ""chat_history: list[WorkflowCopilotChatHistoryMessage] = Field(default_factory=list)debug_run_info_text: str = ""@@ -176,6 +193,7 @@ class TurnContextAssembler:workflow_context: WorkflowContext | None = Noneproposal_context: ProposalContext | None = None+ workflow_change_context: WorkflowChangeContext | None = Nonerun_context: RunContext | None = Nonecredential_context: CredentialContext | None = Nonedocs_context: DocsContext | None = None@@ -231,6 +249,20 @@ class TurnContextAssembler:))+ if RequiredContextKey.WORKFLOW_CHANGE in required and inputs.prior_workflow_yaml.strip():+ change_summary = summarize_user_workflow_change(+ prior_yaml=inputs.prior_workflow_yaml,+ current_yaml=inputs.workflow_yaml,+ )+ # Only surface the section when the user actually edited the workflow.+ # An unchanged or first-turn baseline carries no signal the agent acts on.+ if change_summary.kind is WorkflowChangeKind.USER_MODIFIED_SINCE_LAST_TURN:+ workflow_change_context = WorkflowChangeContext(+ kind=change_summary.kind.value,+ rendered_summary=change_summary.render_prompt_block(),+ structural_diff_unavailable=change_summary.structural_diff_unavailable,+ )+if self._should_include_run_context(inputs.turn_intent, required):if inputs.debug_run_info_text.strip():summary, original_chars, truncated = _bounded_text(inputs.debug_run_info_text, self.run_char_budget)@@ -268,6 +300,7 @@ class TurnContextAssembler:turn_intent_summary=inputs.turn_intent.to_trace_data(),workflow_context=workflow_context,proposal_context=proposal_context,+ workflow_change_context=workflow_change_context,transcript_context=transcript_context,run_context=run_context,credential_context=credential_context,diff --git a/skyvern/forge/sdk/copilot/turn_intent.py b/skyvern/forge/sdk/copilot/turn_intent.pyindex 21a38758f..a4c16f925 100644--- a/skyvern/forge/sdk/copilot/turn_intent.py+++ b/skyvern/forge/sdk/copilot/turn_intent.py@@ -43,6 +43,7 @@ class RequiredContextKey(StrEnum):CURRENT_WORKFLOW = "current_workflow"PROPOSED_WORKFLOW = "proposed_workflow"LATEST_ASSISTANT_PROPOSAL = "latest_assistant_proposal"+ WORKFLOW_CHANGE = "workflow_change"LATEST_RUN_RESULT = "latest_run_result"CREDENTIAL_METADATA = "credential_metadata"DOCS_CONTEXT = "docs_context"@@ -382,6 +383,7 @@ def build_turn_intent(reason_codes.append(TurnIntentReasonCode.WORKFLOW_CONTEXT_PRESENT)if _has_latest_assistant_turn(chat_history):required_context.append(RequiredContextKey.LATEST_ASSISTANT_PROPOSAL)+ required_context.append(RequiredContextKey.WORKFLOW_CHANGE)reason_codes.append(TurnIntentReasonCode.CHAT_HISTORY_PRESENT)if workflow_run_id:required_context.append(RequiredContextKey.LATEST_RUN_RESULT)diff --git a/skyvern/forge/sdk/copilot/workflow_change_summary.py b/skyvern/forge/sdk/copilot/workflow_change_summary.pynew file mode 100644index 000000000..d267c6875--- /dev/null+++ b/skyvern/forge/sdk/copilot/workflow_change_summary.py@@ -0,0 +1,217 @@+"""Typed signal: did the user change the workflow YAML between copilot turns?"""++from __future__ import annotations++from dataclasses import dataclass, field+from enum import Enum+from typing import Any++from skyvern.utils.yaml_loader import safe_load_no_dates++_MAX_LIST_ITEMS = 8+_MAX_LABEL_LEN = 60+++class WorkflowChangeKind(str, Enum):+ FIRST_TURN_NO_PRIOR_STATE = "first_turn_no_prior_state"+ UNCHANGED_SINCE_LAST_TURN = "unchanged_since_last_turn"+ USER_MODIFIED_SINCE_LAST_TURN = "user_modified_since_last_turn"+++@dataclass(frozen=True)+class WorkflowChangeSummary:+ kind: WorkflowChangeKind+ added_block_labels: tuple[str, ...] = field(default_factory=tuple)+ removed_block_labels: tuple[str, ...] = field(default_factory=tuple)+ modified_block_labels: tuple[str, ...] = field(default_factory=tuple)+ added_parameter_keys: tuple[str, ...] = field(default_factory=tuple)+ removed_parameter_keys: tuple[str, ...] = field(default_factory=tuple)+ modified_parameter_keys: tuple[str, ...] = field(default_factory=tuple)+ other_top_level_changes: tuple[str, ...] = field(default_factory=tuple)+ structural_diff_unavailable: bool = False++ def render_prompt_block(self) -> str:+ if self.kind is WorkflowChangeKind.FIRST_TURN_NO_PRIOR_STATE:+ return (+ "first_turn_no_prior_state: no prior copilot workflow baseline is available"+ " (first turn of this chat, or the previous turn ended without a workflow proposal)."+ )+ if self.kind is WorkflowChangeKind.UNCHANGED_SINCE_LAST_TURN:+ return (+ "unchanged_since_last_turn: the current workflow YAML matches what the copilot"+ " last persisted at the end of the previous turn."+ )++ sections: list[str] = ["user_modified_since_last_turn: the user changed the workflow YAML between turns."]+ if self.added_block_labels:+ sections.append(f"added blocks: {_format_list(self.added_block_labels)}")+ if self.removed_block_labels:+ sections.append(f"removed blocks: {_format_list(self.removed_block_labels)}")+ if self.modified_block_labels:+ sections.append(f"modified blocks: {_format_list(self.modified_block_labels)}")+ if self.added_parameter_keys:+ sections.append(f"added parameters: {_format_list(self.added_parameter_keys)}")+ if self.removed_parameter_keys:+ sections.append(f"removed parameters: {_format_list(self.removed_parameter_keys)}")+ if self.modified_parameter_keys:+ sections.append(f"modified parameters: {_format_list(self.modified_parameter_keys)}")+ if self.other_top_level_changes:+ sections.append(f"other changes: {_format_list(self.other_top_level_changes)}")+ if len(sections) == 1:+ if self.structural_diff_unavailable:+ sections.append("structural diff unavailable — YAML parse failed on one or both sides.")+ else:+ sections.append("no structural diff — block bodies or settings were changed in place.")+ return "\n".join(sections)+++def summarize_user_workflow_change(+ prior_yaml: str | None,+ current_yaml: str | None,+) -> WorkflowChangeSummary:+ if not _has_content(prior_yaml):+ return WorkflowChangeSummary(kind=WorkflowChangeKind.FIRST_TURN_NO_PRIOR_STATE)+ if (current_yaml or "").strip() == (prior_yaml or "").strip():+ return WorkflowChangeSummary(kind=WorkflowChangeKind.UNCHANGED_SINCE_LAST_TURN)++ prior = _parse(prior_yaml)+ current = _parse(current_yaml)+ if prior is None or current is None:+ return WorkflowChangeSummary(+ kind=WorkflowChangeKind.USER_MODIFIED_SINCE_LAST_TURN,+ structural_diff_unavailable=True,+ )++ prior_blocks, prior_duplicates = _index_blocks(prior)+ current_blocks, current_duplicates = _index_blocks(current)+ if prior_duplicates or current_duplicates:+ return WorkflowChangeSummary(+ kind=WorkflowChangeKind.USER_MODIFIED_SINCE_LAST_TURN,+ structural_diff_unavailable=True,+ )+ prior_params = _index_parameters(prior)+ current_params = _index_parameters(current)++ added = tuple(label for label in current_blocks if label not in prior_blocks)+ removed = tuple(label for label in prior_blocks if label not in current_blocks)+ modified = tuple(+ label for label, body in current_blocks.items() if label in prior_blocks and prior_blocks[label] != body+ )+ added_params = tuple(key for key in current_params if key not in prior_params)+ removed_params = tuple(key for key in prior_params if key not in current_params)+ modified_params = tuple(+ key for key, body in current_params.items() if key in prior_params and prior_params[key] != body+ )+ other = _top_level_change_keys(prior, current)++ return WorkflowChangeSummary(+ kind=WorkflowChangeKind.USER_MODIFIED_SINCE_LAST_TURN,+ added_block_labels=added,+ removed_block_labels=removed,+ modified_block_labels=modified,+ added_parameter_keys=added_params,+ removed_parameter_keys=removed_params,+ modified_parameter_keys=modified_params,+ other_top_level_changes=other,+ )+++def _has_content(value: str | None) -> bool:+ return bool(value and value.strip())+++def _parse(yaml_text: str | None) -> dict[str, Any] | None:+ if not _has_content(yaml_text):+ return None+ try:+ parsed = safe_load_no_dates(yaml_text)+ except Exception:+ return None+ return parsed if isinstance(parsed, dict) else None+++def _index_blocks(parsed: dict[str, Any]) -> tuple[dict[str, Any], bool]:+ """Return ``(label -> block-body, duplicates_seen)``.++ ``duplicates_seen`` is True when two blocks at the same scope share a+ label — schema permits this and dedup-by-overwrite would silently mask+ add/remove edits, so the caller short-circuits to+ ``structural_diff_unavailable`` instead of returning a misleading diff."""+ definition = parsed.get("workflow_definition")+ if not isinstance(definition, dict):+ return {}, False+ blocks = definition.get("blocks")+ if not isinstance(blocks, list):+ return {}, False+ indexed: dict[str, Any] = {}+ duplicates = _collect_blocks_recursive(blocks, indexed, parent_label_prefix="")+ return indexed, duplicates+++def _collect_blocks_recursive(+ blocks: list[Any],+ indexed: dict[str, Any],+ *,+ parent_label_prefix: str,+) -> bool:+ seen_at_this_scope: set[str] = set()+ duplicates_seen = False+ for position, block in enumerate(blocks):+ if not isinstance(block, dict):+ continue+ raw_label = block.get("label")+ if isinstance(raw_label, str) and raw_label:+ local_label = raw_label+ else:+ local_label = f"<unlabeled_{position}>"+ if local_label in seen_at_this_scope:+ duplicates_seen = True+ continue+ seen_at_this_scope.add(local_label)+ qualified = f"{parent_label_prefix}{local_label}" if parent_label_prefix else local_label+ indexed[qualified] = block+ nested = block.get("loop_blocks")+ if isinstance(nested, list) and nested:+ duplicates_seen = (+ _collect_blocks_recursive(nested, indexed, parent_label_prefix=f"{qualified}/") or duplicates_seen+ )+ return duplicates_seen+++def _index_parameters(parsed: dict[str, Any]) -> dict[str, Any]:+ definition = parsed.get("workflow_definition")+ if not isinstance(definition, dict):+ return {}+ parameters = definition.get("parameters")+ if not isinstance(parameters, list):+ return {}+ indexed: dict[str, Any] = {}+ fallback = 0+ for parameter in parameters:+ if not isinstance(parameter, dict):+ continue+ key = parameter.get("key")+ if not isinstance(key, str) or not key:+ key = f"<unkeyed_{fallback}>"+ fallback += 1+ indexed[key] = parameter+ return indexed+++def _top_level_change_keys(prior: dict[str, Any], current: dict[str, Any]) -> tuple[str, ...]:+ keys = {key for key in (set(prior) | set(current)) if key != "workflow_definition"}+ changed = tuple(sorted(key for key in keys if prior.get(key) != current.get(key)))+ return changed+++def _format_list(items: tuple[str, ...]) -> str:+ truncated = [_clip(item) for item in items[:_MAX_LIST_ITEMS]]+ if len(items) > _MAX_LIST_ITEMS:+ truncated.append(f"…(+{len(items) - _MAX_LIST_ITEMS} more)")+ return ", ".join(truncated)+++def _clip(value: str) -> str:+ if len(value) <= _MAX_LABEL_LEN:+ return value+ return value[: _MAX_LABEL_LEN - 1] + "…"diff --git a/skyvern/forge/sdk/routes/workflow_copilot.py b/skyvern/forge/sdk/routes/workflow_copilot.pyindex 8f144d55d..a08c90a75 100644--- a/skyvern/forge/sdk/routes/workflow_copilot.py+++ b/skyvern/forge/sdk/routes/workflow_copilot.py@@ -1120,6 +1120,41 @@ def _process_workflow_yaml()+def _blockless_submission_fallback(+ *,+ proposed_workflow: dict[str, Any] | None,+ submitted_workflow_yaml: str | None,+) -> str | None:+ """Return a hydration YAML when the frontend submitted nothing usable. Only+ fires for truly empty submissions (``None`` or empty string); a non-empty+ YAML with ``blocks: []`` is treated as an explicit user deletion."""+ if submitted_workflow_yaml is not None and submitted_workflow_yaml.strip() != "":+ return None+ if not isinstance(proposed_workflow, dict):+ return None+ candidate = proposed_workflow.get("_copilot_yaml")+ if not isinstance(candidate, str) or _workflow_yaml_block_count(candidate) == 0:+ return None+ return candidate+++def _prior_copilot_workflow_yaml(+ *,+ proposed_workflow: dict[str, Any] | None,+ persisted_workflow_yaml: str | None,+) -> str | None:+ """Return the YAML the copilot last saw — the basis for the user-modified+ diff. Preference: the persisted proposal (`_copilot_yaml`) → the on-disk+ workflow. Returns ``None`` only when neither carries usable blocks."""+ if isinstance(proposed_workflow, dict):+ candidate = proposed_workflow.get("_copilot_yaml")+ if isinstance(candidate, str) and _workflow_yaml_block_count(candidate) > 0:+ return candidate+ if persisted_workflow_yaml and _workflow_yaml_block_count(persisted_workflow_yaml) > 0:+ return persisted_workflow_yaml+ return None++def _workflow_yaml_block_count(workflow_yaml: str | None) -> int:if not workflow_yaml:return 0@@ -1210,14 +1245,20 @@ def _workflow_to_copilot_yaml(workflow: Workflow) -> str:return yaml.safe_dump(yaml_data, sort_keys=False)-def _ensure_copilot_workflow_yaml(chat_request: WorkflowCopilotChatRequest, original_workflow: Workflow) -> None:+def _ensure_copilot_workflow_yaml(+ chat_request: WorkflowCopilotChatRequest,+ original_workflow: Workflow,+ *,+ persisted_workflow_yaml: str | None = None,+) -> None:if _workflow_yaml_block_count(chat_request.workflow_yaml) > 0:returnworkflow_definition = original_workflow.workflow_definitionif workflow_definition is None or not workflow_definition.blocks:return- persisted_workflow_yaml = _workflow_to_copilot_yaml(original_workflow)+ if persisted_workflow_yaml is None:+ persisted_workflow_yaml = _workflow_to_copilot_yaml(original_workflow)if not persisted_workflow_yaml:return@@ -1304,8 +1345,12 @@ async def _new_copilot_chat_post(global_llm_context = message.global_llm_contextbreak- if chat.proposed_workflow and chat.proposed_workflow.get("_copilot_yaml"):- chat_request.workflow_yaml = chat.proposed_workflow["_copilot_yaml"]+ blockless_fallback = _blockless_submission_fallback(+ proposed_workflow=chat.proposed_workflow,+ submitted_workflow_yaml=chat_request.workflow_yaml,+ )+ if blockless_fallback is not None:+ chat_request.workflow_yaml = blockless_fallbackblock_infos, debug_html = await _get_new_copilot_block_infos(organization.organization_id, chat_request.workflow_run_id@@ -1346,7 +1391,21 @@ async def _new_copilot_chat_post(raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Workflow not found")chat_request.workflow_id = original_workflow.workflow_id- _ensure_copilot_workflow_yaml(chat_request, original_workflow)+ persisted_workflow_yaml: str | None = None+ persisted_definition = original_workflow.workflow_definition+ if persisted_definition is not None and persisted_definition.blocks:+ persisted_workflow_yaml = _workflow_to_copilot_yaml(original_workflow)++ _ensure_copilot_workflow_yaml(+ chat_request,+ original_workflow,+ persisted_workflow_yaml=persisted_workflow_yaml,+ )++ prior_copilot_workflow_yaml = _prior_copilot_workflow_yaml(+ proposed_workflow=chat.proposed_workflow,+ persisted_workflow_yaml=persisted_workflow_yaml,+ )llm_api_handler = await _resolve_copilot_agent_handler(chat_request.workflow_permanent_id, organization.organization_id@@ -1408,6 +1467,7 @@ async def _new_copilot_chat_post(api_key=api_key,config=copilot_config,turn_index=turn_index,+ prior_copilot_workflow_yaml=prior_copilot_workflow_yaml,)if getattr(agent_result, "cancelled", False):diff --git a/tests/unit/test_copilot_route_prior_yaml_resolution.py b/tests/unit/test_copilot_route_prior_yaml_resolution.pynew file mode 100644index 000000000..c9aabf244--- /dev/null+++ b/tests/unit/test_copilot_route_prior_yaml_resolution.py@@ -0,0 +1,165 @@+"""Tests for `_blockless_submission_fallback` and `_prior_copilot_workflow_yaml`."""++from __future__ import annotations++import textwrap++from skyvern.forge.sdk.routes.workflow_copilot import (+ _blockless_submission_fallback,+ _prior_copilot_workflow_yaml,+)++_PROPOSED_YAML = textwrap.dedent(+ """\+ title: t+ workflow_definition:+ parameters: []+ blocks:+ - block_type: goto_url+ label: open_site+ url: https://example.com+ """+)++_PERSISTED_YAML = textwrap.dedent(+ """\+ title: t+ workflow_definition:+ parameters: []+ blocks:+ - block_type: goto_url+ label: open_site+ url: https://example.com+ - block_type: navigation+ label: do_thing+ navigation_goal: Click the primary action.+ """+)++_USER_MODIFIED_YAML = _PROPOSED_YAML + (+ " - block_type: text_prompt\n label: summarize_result\n llm_key: x\n prompt: ok\n"+)+++_BLOCKLESS_EXPLICIT_YAML = "title: t\nworkflow_definition:\n parameters: []\n blocks: []\n"+++class TestBlocklessSubmissionFallback:+ def test_none_submission_with_prior_proposal_returns_fallback(self) -> None:+ assert (+ _blockless_submission_fallback(+ proposed_workflow={"_copilot_yaml": _PROPOSED_YAML},+ submitted_workflow_yaml=None,+ )+ == _PROPOSED_YAML+ )++ def test_empty_string_submission_with_prior_proposal_returns_fallback(self) -> None:+ assert (+ _blockless_submission_fallback(+ proposed_workflow={"_copilot_yaml": _PROPOSED_YAML},+ submitted_workflow_yaml="",+ )+ == _PROPOSED_YAML+ )++ def test_whitespace_only_submission_returns_fallback(self) -> None:+ assert (+ _blockless_submission_fallback(+ proposed_workflow={"_copilot_yaml": _PROPOSED_YAML},+ submitted_workflow_yaml=" \n",+ )+ == _PROPOSED_YAML+ )++ def test_explicit_blocks_empty_submission_is_NOT_overwritten(self) -> None:+ assert (+ _blockless_submission_fallback(+ proposed_workflow={"_copilot_yaml": _PROPOSED_YAML},+ submitted_workflow_yaml=_BLOCKLESS_EXPLICIT_YAML,+ )+ is None+ )++ def test_populated_submission_preserves_user_edit(self) -> None:+ assert (+ _blockless_submission_fallback(+ proposed_workflow={"_copilot_yaml": _PROPOSED_YAML},+ submitted_workflow_yaml=_USER_MODIFIED_YAML,+ )+ is None+ )++ def test_no_proposal_returns_none(self) -> None:+ assert _blockless_submission_fallback(proposed_workflow=None, submitted_workflow_yaml="") is None++ def test_empty_dict_proposal_returns_none(self) -> None:+ assert _blockless_submission_fallback(proposed_workflow={}, submitted_workflow_yaml="") is None++ def test_non_string_copilot_yaml_returns_none(self) -> None:+ assert (+ _blockless_submission_fallback(+ proposed_workflow={"_copilot_yaml": None},+ submitted_workflow_yaml="",+ )+ is None+ )++ def test_malformed_blockless_copilot_yaml_returns_none(self) -> None:+ assert (+ _blockless_submission_fallback(+ proposed_workflow={"_copilot_yaml": _BLOCKLESS_EXPLICIT_YAML},+ submitted_workflow_yaml="",+ )+ is None+ )+++class TestPriorCopilotWorkflowYaml:+ def test_uses_proposal_when_present(self) -> None:+ assert (+ _prior_copilot_workflow_yaml(+ proposed_workflow={"_copilot_yaml": _PROPOSED_YAML},+ persisted_workflow_yaml=_PERSISTED_YAML,+ )+ == _PROPOSED_YAML+ )++ def test_falls_back_to_persisted_when_no_proposal(self) -> None:+ assert (+ _prior_copilot_workflow_yaml(+ proposed_workflow=None,+ persisted_workflow_yaml=_PERSISTED_YAML,+ )+ == _PERSISTED_YAML+ )++ def test_falls_back_to_persisted_when_proposal_has_no_copilot_yaml(self) -> None:+ assert (+ _prior_copilot_workflow_yaml(+ proposed_workflow={"some_other_field": "x"},+ persisted_workflow_yaml=_PERSISTED_YAML,+ )+ == _PERSISTED_YAML+ )++ def test_falls_back_to_persisted_when_copilot_yaml_is_blockless(self) -> None:+ assert (+ _prior_copilot_workflow_yaml(+ proposed_workflow={"_copilot_yaml": _BLOCKLESS_EXPLICIT_YAML},+ persisted_workflow_yaml=_PERSISTED_YAML,+ )+ == _PERSISTED_YAML+ )++ def test_returns_none_when_neither_has_blocks(self) -> None:+ assert (+ _prior_copilot_workflow_yaml(+ proposed_workflow={"_copilot_yaml": _BLOCKLESS_EXPLICIT_YAML},+ persisted_workflow_yaml=_BLOCKLESS_EXPLICIT_YAML,+ )+ is None+ )++ def test_returns_none_when_no_inputs(self) -> None:+ assert _prior_copilot_workflow_yaml(proposed_workflow=None, persisted_workflow_yaml=None) is Nonediff --git a/tests/unit/test_copilot_turn_context.py b/tests/unit/test_copilot_turn_context.pyindex d4cb78590..a58ee1ca4 100644--- a/tests/unit/test_copilot_turn_context.py+++ b/tests/unit/test_copilot_turn_context.py@@ -212,6 +212,87 @@ def test_credential_context_contains_safe_metadata_only() -> None:assert "Click SSO" not in dumped+_WORKFLOW_V1 = (+ "title: t\nworkflow_definition:\n parameters: []\n blocks:\n"+ " - block_type: goto_url\n label: open_site\n url: https://example.com\n"+)+_WORKFLOW_V2 = _WORKFLOW_V1 + (+ " - block_type: text_prompt\n label: summarize_result\n llm_key: x\n prompt: ok\n"+)+++def _change_intent() -> TurnIntent:+ return TurnIntent(+ mode=TurnIntentMode.EDIT,+ required_context=[RequiredContextKey.CURRENT_WORKFLOW, RequiredContextKey.WORKFLOW_CHANGE],+ authority=TurnIntentAuthority(may_update_workflow=True),+ )+++def test_workflow_change_context_reports_user_edit() -> None:+ packet = TurnContextAssembler().assemble(+ TurnContextInputs(+ turn_intent=_change_intent(),+ request_policy=RequestPolicy(),+ user_message="I added a block, does this look right?",+ workflow_yaml=_WORKFLOW_V2,+ prior_workflow_yaml=_WORKFLOW_V1,+ )+ )++ assert packet.workflow_change_context is not None+ assert packet.workflow_change_context.kind == "user_modified_since_last_turn"+ assert "summarize_result" in packet.workflow_change_context.rendered_summary+ assert packet.to_trace_data()["workflow_change_kind"] == "user_modified_since_last_turn"+++def test_workflow_change_context_omitted_when_unchanged() -> None:+ packet = TurnContextAssembler().assemble(+ TurnContextInputs(+ turn_intent=_change_intent(),+ request_policy=RequestPolicy(),+ user_message="Still broken, fix it",+ workflow_yaml=_WORKFLOW_V1,+ prior_workflow_yaml=_WORKFLOW_V1,+ )+ )++ assert packet.workflow_change_context is None+ assert packet.to_trace_data()["workflow_change_kind"] is None+++def test_workflow_change_context_omitted_on_first_turn() -> None:+ packet = TurnContextAssembler().assemble(+ TurnContextInputs(+ turn_intent=_change_intent(),+ request_policy=RequestPolicy(),+ user_message="Build me a workflow",+ workflow_yaml=_WORKFLOW_V1,+ prior_workflow_yaml="",+ )+ )++ assert packet.workflow_change_context is None+ assert packet.to_trace_data()["workflow_change_kind"] is None+++def test_workflow_change_context_skipped_when_not_required() -> None:+ packet = TurnContextAssembler().assemble(+ TurnContextInputs(+ turn_intent=TurnIntent(+ mode=TurnIntentMode.EDIT,+ required_context=[RequiredContextKey.CURRENT_WORKFLOW],+ ),+ request_policy=RequestPolicy(),+ user_message="Update it",+ workflow_yaml=_WORKFLOW_V2,+ prior_workflow_yaml=_WORKFLOW_V1,+ )+ )++ assert packet.workflow_change_context is None++def test_shadow_attachment_stores_packet_on_copilot_context() -> None:ctx = CopilotContext(organization_id="org-1",@@ -235,6 +316,7 @@ def test_shadow_attachment_stores_packet_on_copilot_context() -> None:),chat_history=[],debug_run_info_text="",+ prior_copilot_workflow_yaml=None,)assert ctx.turn_context_packet is not Nonediff --git a/tests/unit/test_copilot_turn_intent.py b/tests/unit/test_copilot_turn_intent.pyindex 8bf20907d..8c6928292 100644--- a/tests/unit/test_copilot_turn_intent.py+++ b/tests/unit/test_copilot_turn_intent.py@@ -379,6 +379,35 @@ def test_docs_answer_turn_directive_renders_only_for_docs_answer_mode() -> None:assert _docs_answer_turn_directive(None) == ""+def test_build_turn_intent_requests_workflow_change_when_prior_assistant_turn_exists() -> None:+ ai_turn = WorkflowCopilotChatHistoryMessage(+ sender=WorkflowCopilotChatSender.AI,+ content="Drafted v1",+ created_at=datetime.now(timezone.utc),+ )+ intent = build_turn_intent(+ user_message="I did it myself, does this look right?",+ workflow_yaml="blocks: []",+ chat_history=[_user_message("Build a workflow"), ai_turn],+ global_llm_context="",+ request_policy=RequestPolicy(),+ )++ assert RequiredContextKey.WORKFLOW_CHANGE in intent.required_context+++def test_build_turn_intent_omits_workflow_change_on_first_turn() -> None:+ intent = build_turn_intent(+ user_message="Build a workflow",+ workflow_yaml="",+ chat_history=[],+ global_llm_context="",+ request_policy=RequestPolicy(),+ )++ assert RequiredContextKey.WORKFLOW_CHANGE not in intent.required_context++def test_store_request_policy_attaches_turn_intent_to_context() -> None:ctx = CopilotContext(organization_id="org-1",diff --git a/tests/unit/test_copilot_workflow_change_summary.py b/tests/unit/test_copilot_workflow_change_summary.pynew file mode 100644index 000000000..c4a8d5362--- /dev/null+++ b/tests/unit/test_copilot_workflow_change_summary.py@@ -0,0 +1,271 @@+"""Tests for ``skyvern.forge.sdk.copilot.workflow_change_summary``."""++from __future__ import annotations++import copy+from typing import Any++import yaml++from skyvern.forge.sdk.copilot.workflow_change_summary import (+ WorkflowChangeKind,+ summarize_user_workflow_change,+)+++def _baseline_dict() -> dict[str, Any]:+ return {+ "title": "t",+ "workflow_definition": {+ "parameters": [+ {+ "parameter_type": "workflow",+ "key": "applicant_name",+ "workflow_parameter_type": "string",+ }+ ],+ "blocks": [+ {"block_type": "goto_url", "label": "open_site", "url": "https://example.com"},+ {+ "block_type": "navigation",+ "label": "fill_form",+ "navigation_goal": "Fill out the form with the applicant's name.",+ },+ ],+ },+ }+++def _dump(workflow: dict[str, Any]) -> str:+ return yaml.safe_dump(workflow, sort_keys=False)+++def _with_blocks(extra_blocks: list[dict[str, Any]]) -> dict[str, Any]:+ workflow = _baseline_dict()+ workflow["workflow_definition"]["blocks"].extend(extra_blocks)+ return workflow+++def test_first_turn_when_prior_yaml_missing() -> None:+ summary = summarize_user_workflow_change(prior_yaml=None, current_yaml=_dump(_baseline_dict()))+ assert summary.kind is WorkflowChangeKind.FIRST_TURN_NO_PRIOR_STATE+++def test_first_turn_when_prior_yaml_blank() -> None:+ summary = summarize_user_workflow_change(prior_yaml=" \n", current_yaml=_dump(_baseline_dict()))+ assert summary.kind is WorkflowChangeKind.FIRST_TURN_NO_PRIOR_STATE+++def test_unchanged_when_strings_match() -> None:+ baseline = _dump(_baseline_dict())+ summary = summarize_user_workflow_change(prior_yaml=baseline, current_yaml=baseline)+ assert summary.kind is WorkflowChangeKind.UNCHANGED_SINCE_LAST_TURN+++def test_unchanged_when_only_whitespace_differs() -> None:+ baseline = _dump(_baseline_dict())+ summary = summarize_user_workflow_change(prior_yaml=baseline, current_yaml=baseline + "\n\n")+ assert summary.kind is WorkflowChangeKind.UNCHANGED_SINCE_LAST_TURN+++def test_user_added_block() -> None:+ appended = _with_blocks(+ [+ {+ "block_type": "text_prompt",+ "label": "summarize_result",+ "llm_key": "OPENAI_GPT5_MINI",+ "prompt": "Summarise success/failure.",+ }+ ]+ )+ summary = summarize_user_workflow_change(+ prior_yaml=_dump(_baseline_dict()),+ current_yaml=_dump(appended),+ )+ assert summary.kind is WorkflowChangeKind.USER_MODIFIED_SINCE_LAST_TURN+ assert summary.added_block_labels == ("summarize_result",)+ assert summary.removed_block_labels == ()+ assert summary.modified_block_labels == ()+++def test_user_removed_block() -> None:+ trimmed = _baseline_dict()+ trimmed["workflow_definition"]["blocks"] = [+ block for block in trimmed["workflow_definition"]["blocks"] if block["label"] != "fill_form"+ ]+ summary = summarize_user_workflow_change(+ prior_yaml=_dump(_baseline_dict()),+ current_yaml=_dump(trimmed),+ )+ assert summary.kind is WorkflowChangeKind.USER_MODIFIED_SINCE_LAST_TURN+ assert summary.removed_block_labels == ("fill_form",)+++def test_user_modified_block_in_place() -> None:+ edited = _baseline_dict()+ edited["workflow_definition"]["blocks"][1]["navigation_goal"] = "Fill out the form and click Submit."+ summary = summarize_user_workflow_change(+ prior_yaml=_dump(_baseline_dict()),+ current_yaml=_dump(edited),+ )+ assert summary.kind is WorkflowChangeKind.USER_MODIFIED_SINCE_LAST_TURN+ assert summary.modified_block_labels == ("fill_form",)+ assert summary.added_block_labels == ()+ assert summary.removed_block_labels == ()+++def test_user_added_parameter() -> None:+ expanded = _baseline_dict()+ expanded["workflow_definition"]["parameters"].append(+ {"parameter_type": "workflow", "key": "company", "workflow_parameter_type": "string"}+ )+ summary = summarize_user_workflow_change(+ prior_yaml=_dump(_baseline_dict()),+ current_yaml=_dump(expanded),+ )+ assert summary.kind is WorkflowChangeKind.USER_MODIFIED_SINCE_LAST_TURN+ assert summary.added_parameter_keys == ("company",)+++def test_user_modified_parameter_default_in_place() -> None:+ edited = _baseline_dict()+ edited["workflow_definition"]["parameters"][0]["default_value"] = "Jane Roe"+ summary = summarize_user_workflow_change(+ prior_yaml=_dump(_baseline_dict()),+ current_yaml=_dump(edited),+ )+ assert summary.kind is WorkflowChangeKind.USER_MODIFIED_SINCE_LAST_TURN+ assert summary.modified_parameter_keys == ("applicant_name",)+ assert summary.added_parameter_keys == ()+ assert summary.removed_parameter_keys == ()+ assert "modified parameters: applicant_name" in summary.render_prompt_block()+++def test_top_level_change_recorded() -> None:+ renamed = _baseline_dict()+ renamed["title"] = "renamed-workflow"+ summary = summarize_user_workflow_change(+ prior_yaml=_dump(_baseline_dict()),+ current_yaml=_dump(renamed),+ )+ assert summary.kind is WorkflowChangeKind.USER_MODIFIED_SINCE_LAST_TURN+ assert "title" in summary.other_top_level_changes+++def test_unparseable_current_yaml_falls_back_to_modified() -> None:+ summary = summarize_user_workflow_change(+ prior_yaml=_dump(_baseline_dict()),+ current_yaml=":\n: not yaml",+ )+ assert summary.kind is WorkflowChangeKind.USER_MODIFIED_SINCE_LAST_TURN+ assert summary.added_block_labels == ()+ assert summary.structural_diff_unavailable is True+ assert "structural diff unavailable" in summary.render_prompt_block()+++def test_prompt_block_first_turn() -> None:+ rendered = summarize_user_workflow_change(prior_yaml=None, current_yaml="").render_prompt_block()+ assert "first_turn_no_prior_state" in rendered+++def test_prompt_block_unchanged() -> None:+ baseline = _dump(_baseline_dict())+ rendered = summarize_user_workflow_change(prior_yaml=baseline, current_yaml=baseline).render_prompt_block()+ assert "unchanged_since_last_turn" in rendered+++def test_prompt_block_modified_lists_blocks() -> None:+ appended = _with_blocks(+ [{"block_type": "text_prompt", "label": "summarize_result", "llm_key": "x", "prompt": "ok"}]+ )+ rendered = summarize_user_workflow_change(+ prior_yaml=_dump(_baseline_dict()),+ current_yaml=_dump(appended),+ ).render_prompt_block()+ assert "user_modified_since_last_turn" in rendered+ assert "summarize_result" in rendered+++def test_user_modified_block_inside_for_loop() -> None:+ base = _baseline_dict()+ base["workflow_definition"]["blocks"].append(+ {+ "block_type": "for_loop",+ "label": "for_each_row",+ "loop_over_parameter_key": "rows",+ "loop_blocks": [+ {+ "block_type": "navigation",+ "label": "process_row",+ "navigation_goal": "Click the row's primary action.",+ }+ ],+ }+ )+ edited = copy.deepcopy(base)+ edited["workflow_definition"]["blocks"][2]["loop_blocks"][0]["navigation_goal"] = (+ "Click the row's secondary action."+ )+ summary = summarize_user_workflow_change(prior_yaml=_dump(base), current_yaml=_dump(edited))+ assert summary.kind is WorkflowChangeKind.USER_MODIFIED_SINCE_LAST_TURN+ assert "for_each_row" in summary.modified_block_labels+ assert "for_each_row/process_row" in summary.modified_block_labels+++def test_user_added_block_inside_for_loop() -> None:+ base = _baseline_dict()+ base["workflow_definition"]["blocks"].append(+ {+ "block_type": "for_loop",+ "label": "for_each_row",+ "loop_over_parameter_key": "rows",+ "loop_blocks": [+ {+ "block_type": "navigation",+ "label": "process_row",+ "navigation_goal": "Click the primary action.",+ }+ ],+ }+ )+ expanded = copy.deepcopy(base)+ expanded["workflow_definition"]["blocks"][2]["loop_blocks"].append(+ {+ "block_type": "extraction",+ "label": "extract_row_value",+ "data_extraction_goal": "Read the row's value.",+ }+ )+ summary = summarize_user_workflow_change(prior_yaml=_dump(base), current_yaml=_dump(expanded))+ assert summary.kind is WorkflowChangeKind.USER_MODIFIED_SINCE_LAST_TURN+ assert "for_each_row/extract_row_value" in summary.added_block_labels+ assert "for_each_row" in summary.modified_block_labels+++def test_duplicate_block_labels_emit_structural_diff_unavailable() -> None:+ base = _baseline_dict()+ base["workflow_definition"]["blocks"].append(+ {"block_type": "extraction", "label": "open_site", "data_extraction_goal": "Read the heading."}+ )+ edited = copy.deepcopy(base)+ edited["workflow_definition"]["blocks"][0]["url"] = "https://example.com/other"+ summary = summarize_user_workflow_change(prior_yaml=_dump(base), current_yaml=_dump(edited))+ assert summary.kind is WorkflowChangeKind.USER_MODIFIED_SINCE_LAST_TURN+ assert summary.structural_diff_unavailable is True+ assert summary.added_block_labels == ()+ assert summary.modified_block_labels == ()+++def test_added_block_truncates_long_list() -> None:+ extras = [+ {"block_type": "goto_url", "label": f"extra_block_{i}", "url": f"https://example.com/{i}"} for i in range(12)+ ]+ expanded = _with_blocks(copy.deepcopy(extras))+ summary = summarize_user_workflow_change(+ prior_yaml=_dump(_baseline_dict()),+ current_yaml=_dump(expanded),+ )+ rendered = summary.render_prompt_block()+ assert "extra_block_0" in rendered+ assert "(+4 more)" in rendereddiff --git a/tests/unit/test_workflow_copilot_prompt_injection.py b/tests/unit/test_workflow_copilot_prompt_injection.pyindex 054f5d8c1..1164c7453 100644--- a/tests/unit/test_workflow_copilot_prompt_injection.py+++ b/tests/unit/test_workflow_copilot_prompt_injection.py@@ -378,6 +378,32 @@ class TestBuildUserContext:# must be escaped by escape_code_fences().assert "``` injected ```" not in rendered+ def test_workflow_change_summary_slot_renders_when_present(self) -> None:+ rendered = _build_user_context(+ workflow_yaml="title: t",+ chat_history_text="",+ global_llm_context="",+ debug_run_info_text="",+ user_message="hello",+ user_workflow_change_summary=(+ "user_modified_since_last_turn: the user changed the workflow YAML between turns.\n"+ "added blocks: summarize_result"+ ),+ )+ assert "USER WORKFLOW CHANGES SINCE LAST COPILOT TURN" in rendered+ assert "user_modified_since_last_turn" in rendered+ assert "added blocks: summarize_result" in rendered++ def test_workflow_change_summary_slot_omitted_when_empty(self) -> None:+ rendered = _build_user_context(+ workflow_yaml="title: t",+ chat_history_text="",+ global_llm_context="",+ debug_run_info_text="",+ user_message="hello",+ )+ assert "USER WORKFLOW CHANGES SINCE LAST COPILOT TURN" not in rendered+def test_workflow_summary_indexes_block_labels_and_error_mappings(self) -> None:workflow_yaml = """title: Invoice workflow