Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(SKY-9650): hydrate Copilot workflow state (#5889)
Andrew Neilsonf94c6cf8dc1d
diff --git a/docs/cloud/building-workflows/add-parameters.mdx b/docs/cloud/building-workflows/add-parameters.mdxindex e1ef62a18..7dcd9b79c 100644--- a/docs/cloud/building-workflows/add-parameters.mdx+++ b/docs/cloud/building-workflows/add-parameters.mdx@@ -131,7 +131,7 @@ These variable names are built-in and cannot be used as parameter keys:|----------|-------------|-------------|| `current_value` | Loop blocks | The current item being iterated || `current_item` | Loop blocks | Alias for `current_value` |-| `current_index` | Loop blocks | Zero-based index of the current iteration |+| `current_index` | Loop and While Loop blocks | Zero-based index of the current iteration || `workflow_run_id` | All blocks | Unique ID of the current run || `workflow_id` | All blocks | The workflow's ID || `workflow_permanent_id` | All blocks | The workflow's permanent ID |diff --git a/docs/cloud/building-workflows/build-a-workflow.mdx b/docs/cloud/building-workflows/build-a-workflow.mdxindex 5095a7c84..f9b5b12c5 100644--- a/docs/cloud/building-workflows/build-a-workflow.mdx+++ b/docs/cloud/building-workflows/build-a-workflow.mdx@@ -47,7 +47,7 @@ For example, an Extraction block labeled `scrape_listings` produces output that|----------|-------------|----------|| **Browser Automation** | Interact with web pages using AI | Browser Task, Browser Action, Extraction, Login, Go to URL, Print Page || **Data and Extraction** | Transform data without a browser | Text Prompt, File Parser |-| **Control Flow** | Branch, loop, validate, or pause | Loop, Conditional, AI Validation, Code, Wait |+| **Control Flow** | Branch, loop, validate, or pause | Loop, While Loop, Conditional, AI Validation, Code, Wait || **Files** | Download and upload files | File Download, Cloud Storage Upload || **Communication** | Send data to external services or humans | Send Email, HTTP Request, Human Interaction |@@ -264,7 +264,7 @@ Blocks auto-connect when you insert them via the **+** button. They execute top**Conditional blocks** create branches. Each branch connects to a different sequence of blocks and merges back at a common point.-**Loop blocks** contain child blocks that repeat for each item in the loop's list.+**Loop blocks** contain child blocks that repeat for each item in the loop's list. **While Loop blocks** contain child blocks that repeat while their condition remains true.To reorder blocks, delete the block you want to move and re-add it at the desired position using the **+** button.diff --git a/docs/cloud/building-workflows/configure-blocks.mdx b/docs/cloud/building-workflows/configure-blocks.mdxindex 8caa83ba6..2d623ae26 100644--- a/docs/cloud/building-workflows/configure-blocks.mdx+++ b/docs/cloud/building-workflows/configure-blocks.mdx@@ -1,13 +1,14 @@---title: Block Types and Configurationsubtitle: Reference for every block available in the workflow editor-description: Reference guide for every workflow block type in the Skyvern Cloud UI, including Browser Task, Extraction, Login, Loop, Conditional, Code, HTTP Request, and more.+description: Reference guide for every workflow block type in the Skyvern Cloud UI, including Browser Task, Extraction, Login, Loop, While Loop, Conditional, Code, HTTP Request, and more.slug: cloud/configure-blockskeywords:- navigation block- action block- extract block- loop block+ - while loop block- code block- HTTP request block- text prompt block@@ -31,7 +32,7 @@ If you're writing automations in code instead, the equivalent operations are Pag|----------|--------|| [Browser Automation](#browser-automation) | Browser Task, Browser Action, Extraction, Login, Go to URL, Print Page || [Data and Extraction](#data-and-extraction) | Text Prompt, File Parser |-| [Control Flow](#control-flow) | Loop, Conditional, AI Validation, Code, Wait |+| [Control Flow](#control-flow) | Loop, While Loop, Conditional, AI Validation, Code, Wait || [Files](#files) | File Download, Cloud Storage Upload || [Communication](#communication) | Send Email, HTTP Request, Human Interaction |@@ -246,6 +247,21 @@ Inside loop blocks, use these [reserved variables](/cloud/building-workflows/add<img width="400" src="/images/cloud/block-loop-config.png" alt="Loop block configuration" /></Frame>+Use Loop when the item list is already known before the loop starts, such as rows extracted from a table, files uploaded by a user, or URLs passed as workflow parameters.++### While Loop++Repeat a sequence of blocks while a condition remains true. Child blocks are placed inside the loop on the canvas.++| Field | Type | Description |+|-------|------|-------------|+| **Condition** | expression | Jinja2 template or natural-language prompt evaluated before each iteration |++Inside while-loop blocks, use these [reserved variables](/cloud/building-workflows/add-parameters#reserved-variables):+- `{{ current_index }}`: the iteration number (0-based)++Use While Loop for flows where the number of iterations is discovered during the run, such as pagination, polling, or retrying until a recoverable page state clears. For pagination, a common pattern is to extract a `has_next_page` boolean inside the loop, click Next, and let the next condition check decide whether to continue.+### ConditionalBranch the workflow based on conditions. The UI shows branches as tabs (A, B, C, etc.). Each branch has an expression that determines when it executes. Expressions can be Jinja2 templates or natural language prompts.diff --git a/docs/developers/going-to-production/reliability-tips.mdx b/docs/developers/going-to-production/reliability-tips.mdxindex 1cc3564e5..0e0f23d82 100644--- a/docs/developers/going-to-production/reliability-tips.mdx+++ b/docs/developers/going-to-production/reliability-tips.mdx@@ -211,10 +211,12 @@ if result.output["submitted_email"] != expected_email:----## ForLoop reliability+## Loop reliabilityLoops are especially prone to cascading failures: when one iteration fails, it can leave the browser in an unexpected state that breaks subsequent iterations. For example, if iteration 3 navigates to an error page and fails, iteration 4 starts from that error page instead of the expected list view, causing it to fail too. One bad item can take down your entire loop.+Use a For Loop when you have a known list of items before the loop begins. Use a While Loop when the workflow should keep running until page state changes, such as paginating while a Next button is enabled or polling until a status changes. While loops need an especially clear exit condition because the number of iterations is discovered at run time.+### Always set `continue_on_failure````yaml@@ -243,6 +245,34 @@ loop_blocks:navigation_goal: "Find and process: {{ process_item.current_value }}"```+For While Loop pagination, each pass should leave the page ready for the next condition check. Extract the state that controls the loop, then advance the page:++```yaml+- block_type: while_loop+ label: paginate_results+ condition:+ criteria_type: jinja2_template+ expression: "{{ current_index == 0 or extract_page.has_next_page }}"+ loop_blocks:+ - block_type: extraction+ label: extract_page+ data_extraction_goal: Extract rows on this page and whether the Next button is enabled+ data_schema:+ type: object+ properties:+ rows:+ type: array+ items:+ type: object+ has_next_page:+ type: boolean+ - block_type: action+ label: click_next+ navigation_goal: "Click Next if it is enabled. COMPLETE after one click or if Next is disabled."+```++The first condition check uses `current_index == 0` to enter the loop before `extract_page` exists. Later checks use the previous extraction output so the loop exits naturally when no next page is available.+### Include termination criteria per iteration```yamldiff --git a/docs/skill.md b/docs/skill.mdindex a68698e3d..3804ee692 100644--- a/docs/skill.md+++ b/docs/skill.md@@ -98,7 +98,9 @@ result = await client.run_task(Chain task blocks, loops, conditionals, data extraction, and file operations into reusable automations.-**Block types:** NavigationBlock, ActionBlock, ExtractBlock, LoopBlock, TextPromptBlock, LoginBlock, FileDownloadBlock, FileParseBlock, UploadBlock, EmailBlock, WebhookBlock, ValidationBlock, WaitBlock, CodeBlock, ForLoopBlock, FileURLParsingBlock, DownloadToS3Block, SendEmailBlock.+**Block types:** NavigationBlock, ActionBlock, ExtractBlock, LoopBlock, TextPromptBlock, LoginBlock, FileDownloadBlock, FileParseBlock, UploadBlock, EmailBlock, WebhookBlock, ValidationBlock, WaitBlock, CodeBlock, ForLoopBlock, WhileLoopBlock, FileURLParsingBlock, DownloadToS3Block, SendEmailBlock.++Use a `ForLoopBlock` when the workflow already has a fixed list to iterate over, such as extracted rows, uploaded files, or user-provided URLs. Use a `WhileLoopBlock` when the workflow should keep repeating until a condition changes, such as paginating while a Next button remains enabled, polling until a status is complete, or retrying while a recoverable page state is visible.```pythonworkflow = await client.create_workflow(diff --git a/docs/snippets/core-concepts-content.mdx b/docs/snippets/core-concepts-content.mdxindex b8ce9086a..c9d1b7738 100644--- a/docs/snippets/core-concepts-content.mdx+++ b/docs/snippets/core-concepts-content.mdx@@ -145,7 +145,7 @@ Blocks are the building units of workflows. Each block performs one operation.**Data and files:** Extract (pull structured data into JSON), File Download, File Upload, File Parser (PDFs, CSVs, Excel), and PDF Parser (specialized text extraction).-**Logic and control flow:** Conditional (if/else branching), For Loop (repeat over a list), Validation (assert conditions, halt on failure), and Code (custom Python/Playwright scripts).+**Logic and control flow:** Conditional (if/else branching), For Loop (repeat over a list), While Loop (repeat while a condition remains true), Validation (assert conditions, halt on failure), and Code (custom Python/Playwright scripts).**Communication:** HTTP Request (external API calls), Text Prompt (text-only LLM prompt, no browser), and Send Email.diff --git a/skyvern/cli/skills/skyvern/references/block-types.md b/skyvern/cli/skills/skyvern/references/block-types.mdindex 3601d8123..c0f158fb9 100644--- a/skyvern/cli/skills/skyvern/references/block-types.md+++ b/skyvern/cli/skills/skyvern/references/block-types.md@@ -41,6 +41,14 @@ Keep conditions narrow and testable.## `for_loop`-Use for repeated structures such as paginated rows or item cards.+Use when the workflow already has a concrete list to iterate over, such as extracted rows, item cards, uploaded files, or user-provided URLs.Avoid nested loops unless absolutely necessary; they increase run variance.++## `while_loop`++Use when the workflow should repeat until a condition changes. Good fits include pagination with an enabled Next button, polling until a status is complete, and retry-until flows where each pass can make progress.++Prefer a Jinja2 condition when a prior block extracts a boolean such as `has_next_page`. Use a prompt condition only when the decision depends on visual page state that is hard to express from structured outputs.++Keep a bounded exit path in mind. The runtime enforces a maximum iteration limit, but workflows are more reliable when the condition is expected to become false through normal page progress.diff --git a/skyvern/forge/failure_classifier.py b/skyvern/forge/failure_classifier.pyindex c4b6030fa..c0fdbdc68 100644--- a/skyvern/forge/failure_classifier.py+++ b/skyvern/forge/failure_classifier.py@@ -123,7 +123,16 @@ def classify_from_failure_reason()# Credential error- if "Bitwarden" in exc_name or any(kw in reason for kw in ["credential not found", "missing credential"]):+ if "Bitwarden" in exc_name or any(+ kw in reason+ for kw in [+ "credential not found",+ "missing credential",+ "username not found by key",+ "password not found by key",+ "secret not found by key",+ ]+ ):categories.append({"category": "CREDENTIAL_ERROR",diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2index 1a1838c94..2afbb613e 100644--- a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2@@ -84,8 +84,8 @@ When a run fails with "Access Denied", an Akamai/Cloudflare/Imperva reference, o7. Try at least two genuinely distinct approaches before concluding infeasible.8. If still blocked, explain the specific anti-bot evidence observed (for example Cloudflare, CAPTCHA, "verify you are human", Access Denied, or a blank "Just a moment..." page), describe exactly what you tried, and ask whether to try a different proxy/location, entry URL, or alternate source.-MANDATORY: After every workflow update, you MUST test it. Prefer update_and_run_blocks (single call) over separate update_workflow + run_blocks_and_collect_debug calls. Never skip testing. Grow the workflow incrementally (known-good blocks + next block) unless the user explicitly asks for a one-shot full draft. Feasibility decisions must be based on the latest test result. If you conclude the request is infeasible, explain the specific evidence from that latest run.-MANDATORY: The Accept/Reject proposal UI only appears when your latest run_blocks_and_collect_debug or update_and_run_blocks returned ok=true this turn. An untested update_workflow is silently dropped from the user-visible proposal — if you want the user to be able to accept your change, you MUST verify it with a passing test in this same turn. If testing is impossible for any reason (missing credentials, required human input), stop and ask a clarifying question instead of leaving an untested draft.+MANDATORY: After every workflow update, you MUST test it unless the latest user message explicitly asks you to skip testing or create an untested draft. Prefer update_and_run_blocks (single call) over separate update_workflow + run_blocks_and_collect_debug calls. Grow the workflow incrementally (known-good blocks + next block) unless the user explicitly asks for a one-shot full draft. Feasibility decisions must be based on the latest test result. If you conclude the request is infeasible, explain the specific evidence from that latest run.+MANDATORY: The Accept/Reject proposal UI normally appears when your latest run_blocks_and_collect_debug or update_and_run_blocks returned ok=true this turn. If the latest user message explicitly asks for an untested draft (for example, "make a workflow without testing it", "skip testing", or "draft only"), you MAY call update_workflow without a block-running test and respond with REPLY. In that case, say the workflow was drafted without testing as requested, and do NOT say it is successful, working, ready, or verified. If testing is impossible and the user did not explicitly ask to skip testing, stop and ask a clarifying question instead of leaving an untested draft.MANDATORY: If the latest run only validates an intermediate step (for example, "reached homepage"), do NOT present that as the final proposal when the user asked for a larger outcome (for example, finding/downloading specific files). Continue internal iteration.MANDATORY: For multi-step requests (for example, "go to X and then download Y"), do not stop after validating only the first step. The proposed workflow must cover all requested steps.MANDATORY: Do NOT respond to the user after validating only a subset of the requested outcome. If the user asked for N distinct actions (e.g., "navigate AND download", "login AND search AND add to cart"), your workflow must have blocks covering ALL of those actions before you present a final response. A workflow that only navigates to a page is NOT a complete response for "go to X and download Y".diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-user.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-user.j2index 4a946787d..af1d3a2dd 100644--- a/skyvern/forge/prompts/skyvern/workflow-copilot-user.j2+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-user.j2@@ -10,6 +10,16 @@ The user's current workflow definition is:The user is starting with an empty workflow.{% endif %}+{% if workflow_summary is defined and workflow_summary %}+Workflow block summary:++```+{{ workflow_summary }}+```++Use this summary as a block-label index, then inspect the full workflow definition above for exact block details.+{% endif %}+PREVIOUS CONTEXT:{% if chat_history %}diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex 6380ca428..9ef355430 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -7,6 +7,7 @@ from __future__ import annotationsimport asyncioimport contextlib+import refrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import TYPE_CHECKING, Any@@ -34,6 +35,7 @@ from skyvern.forge.sdk.schemas.workflow_copilot import ()from skyvern.forge.sdk.workflow.exceptions import BaseWorkflowHTTPExceptionfrom skyvern.utils.strings import escape_code_fences+from skyvern.utils.yaml_loader import safe_load_no_datesLOG = structlog.get_logger()@@ -42,6 +44,20 @@ WORKFLOW_KNOWLEDGE_BASE_PATH = ()MAX_TURNS = 25+_USER_SUPPLIED_CREDENTIAL_ID_RE = re.compile(r"\bcred_[A-Za-z0-9][A-Za-z0-9_-]*\b")+_UNTESTED_DRAFT_REQUEST_RE = re.compile(+ r"\b(?:"+ r"without\s+testing|"+ r"without\s+(?:a\s+)?test(?:\s+run)?|"+ r"do\s+not\s+test|"+ r"don['’]?t\s+test|"+ r"skip\s+(?:the\s+)?test(?:ing)?|"+ r"no\s+test(?:ing)?|"+ r"untested\s+draft|"+ r"draft\s+only"+ r")\b",+ re.IGNORECASE,+)_BLOCK_GOAL_CONTEXT_PREAMBLE = ("Interpret the latest user message in the context of the prior conversation. If it is a correction, "@@ -182,6 +198,7 @@ def _build_user_context(return prompt_engine.load_prompt(template="workflow-copilot-user",workflow_yaml=escape_code_fences(workflow_yaml or ""),+ workflow_summary=escape_code_fences(_build_workflow_summary(workflow_yaml)),chat_history=escape_code_fences(chat_history_text),global_llm_context=escape_code_fences(global_llm_context or ""),debug_run_info=escape_code_fences(debug_run_info_text),@@ -189,6 +206,177 @@ def _build_user_context()+def _extract_user_supplied_credential_ids(user_message: str) -> list[str]:+ return list(dict.fromkeys(_USER_SUPPLIED_CREDENTIAL_ID_RE.findall(user_message or "")))+++def _user_requests_untested_workflow_draft(user_message: str) -> bool:+ return bool(_UNTESTED_DRAFT_REQUEST_RE.search(user_message or ""))+++def _missing_credential_ids_result(+ missing_credential_ids: list[str],+ global_llm_context: str | None,+) -> AgentResult:+ formatted_ids = ", ".join(f"`{credential_id}`" for credential_id in missing_credential_ids)+ id_word = "ID" if len(missing_credential_ids) == 1 else "IDs"+ was_word = "was" if len(missing_credential_ids) == 1 else "were"+ structured = StructuredContext.from_json_str(global_llm_context)+ structured.decisions_made.append(+ f"credential reference validation blocked missing ids: {', '.join(missing_credential_ids)}"+ )+ return AgentResult(+ user_response=(+ f"The credential {id_word} {formatted_ids} {was_word} not found in this organization. "+ "Please choose one of these paths: provide/select a valid credential ID, create the credential "+ "in the Credentials UI and return with its ID, or explicitly tell me to continue with an "+ "unvalidated draft workflow that will not be run until credentials are available."+ ),+ updated_workflow=None,+ global_llm_context=structured.to_json_str(),+ response_type="ASK_QUESTION",+ workflow_yaml=None,+ workflow_was_persisted=False,+ clear_proposed_workflow=True,+ )+++def _credential_lookup_failed_result(global_llm_context: str | None) -> AgentResult:+ structured = StructuredContext.from_json_str(global_llm_context)+ structured.decisions_made.append("credential reference validation failed before workflow build")+ return AgentResult(+ user_response=(+ "I couldn't verify the supplied credential ID against this organization, so I can't build or run "+ "the workflow with it yet. Please provide/select a valid credential ID, create the credential in "+ "the Credentials UI and return with its ID, or explicitly tell me to continue with an unvalidated "+ "draft workflow that will not be run until credentials are available."+ ),+ updated_workflow=None,+ global_llm_context=structured.to_json_str(),+ response_type="ASK_QUESTION",+ workflow_yaml=None,+ workflow_was_persisted=False,+ clear_proposed_workflow=True,+ )+++async def _credential_validation_result_for_user_message(+ *,+ user_message: str,+ organization_id: str,+ global_llm_context: str | None,+ allow_untested_workflow_draft: bool = False,+) -> AgentResult | None:+ if allow_untested_workflow_draft:+ return None++ credential_ids = _extract_user_supplied_credential_ids(user_message)+ if not credential_ids:+ return None++ try:+ existing_credentials = await app.DATABASE.credentials.get_credentials_by_ids(+ credential_ids,+ organization_id=organization_id,+ )+ except Exception:+ LOG.warning(+ "Copilot failed to validate user-supplied credential IDs",+ organization_id=organization_id,+ credential_ids=credential_ids,+ exc_info=True,+ )+ return _credential_lookup_failed_result(global_llm_context)++ found_ids = {credential.credential_id for credential in existing_credentials}+ missing_ids = [credential_id for credential_id in credential_ids if credential_id not in found_ids]+ if not missing_ids:+ return None+ return _missing_credential_ids_result(missing_ids, global_llm_context)+++def _truncate_summary_text(value: Any, max_chars: int = 240) -> str:+ text = str(value)+ if len(text) <= max_chars:+ return text+ return text[: max_chars - 3].rstrip() + "..."+++def _block_summary_lines(blocks: list[Any], *, depth: int = 0) -> list[str]:+ lines: list[str] = []+ indent = " " * depth+ for block in blocks:+ if not isinstance(block, dict):+ continue++ label = block.get("label") or "(unlabeled)"+ block_type = block.get("block_type") or "unknown"+ line_parts = [f"{indent}- {label} ({block_type})"]+ next_label = block.get("next_block_label")+ if next_label:+ line_parts.append(f"next={next_label}")++ error_code_mapping = block.get("error_code_mapping")+ if isinstance(error_code_mapping, dict) and error_code_mapping:+ mappings = [f"{code}: {_truncate_summary_text(reason)}" for code, reason in error_code_mapping.items()]+ line_parts.append("error_code_mapping={" + "; ".join(mappings) + "}")++ branch_conditions = block.get("branch_conditions")+ if isinstance(branch_conditions, list) and branch_conditions:+ branch_targets = []+ for branch in branch_conditions:+ if not isinstance(branch, dict):+ continue+ target = branch.get("next_block_label")+ if target:+ prefix = "default -> " if branch.get("is_default") else "branch -> "+ branch_targets.append(prefix + str(target))+ if branch_targets:+ line_parts.append("branches=[" + ", ".join(branch_targets) + "]")++ lines.append("; ".join(line_parts))++ loop_blocks = block.get("loop_blocks")+ if isinstance(loop_blocks, list) and loop_blocks:+ lines.extend(_block_summary_lines(loop_blocks, depth=depth + 1))++ return lines+++def _build_workflow_summary(workflow_yaml: str | None) -> str:+ """Return a compact block index for the model before the full YAML.++ The full workflow YAML remains the source of truth, but large block goals+ can bury later labels and per-block error mappings. This summary gives+ block-specific debug turns a cheap index so an existing label like+ ``block_2`` is not missed before the model inspects details in the YAML.+ """+ if not workflow_yaml:+ return ""+ try:+ parsed = safe_load_no_dates(workflow_yaml)+ except Exception:+ return ""+ if not isinstance(parsed, dict):+ return ""++ workflow_definition = parsed.get("workflow_definition")+ if not isinstance(workflow_definition, dict):+ return ""+ blocks = workflow_definition.get("blocks")+ if not isinstance(blocks, list) or not blocks:+ return ""++ lines = _block_summary_lines(blocks)+ if not lines:+ return ""+ summary = "\n".join(lines)+ max_summary_chars = 12_000+ if len(summary) > max_summary_chars:+ return summary[: max_summary_chars - 80].rstrip() + "\n... workflow summary truncated ..."+ return summary++def _build_tool_usage_guide(tool_names_and_descriptions: list[tuple[str, str]]) -> str:if not tool_names_and_descriptions:return ""@@ -245,6 +433,11 @@ def _rewrite_failed_test_response(user_response: str, ctx: CopilotContext) -> st)if ctx.last_test_ok is None and ctx.last_update_block_count is not None and ctx.last_workflow is not None:+ if ctx.allow_untested_workflow_draft:+ return (+ "I drafted the workflow without testing it, as requested. "+ "You can accept it to save, but it has not been verified end-to-end."+ )if has_keepable_draft:return ("I drafted an update but wasn't able to verify it this turn. "@@ -624,6 +817,16 @@ async def run_copilot_agent(api_key: str | None = None,security_rules: str = "",) -> AgentResult:+ allow_untested_workflow_draft = _user_requests_untested_workflow_draft(chat_request.message)+ credential_validation_result = await _credential_validation_result_for_user_message(+ user_message=chat_request.message,+ organization_id=organization_id,+ global_llm_context=global_llm_context,+ allow_untested_workflow_draft=allow_untested_workflow_draft,+ )+ if credential_validation_result is not None:+ return credential_validation_result+# Preflight feasibility classifier — fires on every turn so mid-session pivots# to impossible targets are caught the same as first-turn structural mismatches.from skyvern.forge.sdk.copilot.feasibility_gate import run_feasibility_gate@@ -694,6 +897,7 @@ async def run_copilot_agent(stream=stream,api_key=api_key,user_message=chat_request.message,+ allow_untested_workflow_draft=allow_untested_workflow_draft,block_goal_main_goal=_build_block_goal_main_goal(user_message=chat_request.message,chat_history_text=chat_history_text,diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.pyindex 081f56430..b89cc860c 100644--- a/skyvern/forge/sdk/copilot/context.py+++ b/skyvern/forge/sdk/copilot/context.py@@ -163,6 +163,7 @@ class CopilotContext(AgentContext):copilot_total_timeout_exceeded: bool = Falseuser_message: str = ""block_goal_main_goal: str = ""+ allow_untested_workflow_draft: bool = False# Tool trackingconsecutive_tool_tracker: list[str] = field(default_factory=list)diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.pyindex d33a936d6..b4ff5792e 100644--- a/skyvern/forge/sdk/copilot/enforcement.py+++ b/skyvern/forge/sdk/copilot/enforcement.py@@ -92,7 +92,9 @@ POST_UPDATE_NUDGE = ("You updated the workflow but did not test it. ""You MUST call run_blocks_and_collect_debug (or update_and_run_blocks next time) ""to test at least the first block before responding to the user. "- "This verifies the workflow actually works."+ "This verifies the workflow actually works. "+ "Exception: if the latest user message explicitly asked for an untested draft, "+ "respond with an unvalidated draft instead of testing.")POST_NAVIGATE_NUDGE = (@@ -669,7 +671,11 @@ def _check_enforcement(ctx: Any, result: RunResultStreaming | None = None) -> stctx.explore_without_workflow_nudge_count += 1return POST_EXPLORE_WITHOUT_WORKFLOW_NUDGE- if ctx.update_workflow_called and not ctx.test_after_update_done:+ if (+ ctx.update_workflow_called+ and not ctx.test_after_update_done+ and getattr(ctx, "allow_untested_workflow_draft", False) is not True+ ):return POST_UPDATE_NUDGE# A budget-trip is a structural problem (chain too long), not adiff --git a/skyvern/forge/sdk/copilot/loop_detection.py b/skyvern/forge/sdk/copilot/loop_detection.pyindex cc58c1975..e4744e478 100644--- a/skyvern/forge/sdk/copilot/loop_detection.py+++ b/skyvern/forge/sdk/copilot/loop_detection.py@@ -7,6 +7,8 @@ Two independent guards:patterns (A-B-A-B) bypass it by design.* ``detect_failed_tool_step_loop`` fires on N repeated failures of thesame (tool, args) pair, even when other tools dispatch in between.+ Block-running credential/config failures are keyed by failure category+ instead, because draft arguments can change while the init failure does not.A successful invocation of the same step resets its counter."""@@ -17,9 +19,13 @@ import jsonfrom collections.abc import Iterable, Mapping, MutableMappingfrom typing import Any+from skyvern.forge.failure_classifier import classify_from_failure_reason+MAX_CONSECUTIVE_SAME_TOOL = 3MAX_REPEATED_FAILED_STEP = 3LOOP_DETECTED_MARKER = "LOOP DETECTED:"+ARGUMENT_INSENSITIVE_FAILURE_TOOLS = frozenset({"run_blocks_and_collect_debug", "update_and_run_blocks"})+ARGUMENT_INSENSITIVE_FAILURE_CATEGORIES = frozenset({"CREDENTIAL_ERROR", "PARAMETER_BINDING_ERROR"})def detect_tool_loop(@@ -65,6 +71,73 @@ def tool_step_identity(tool_name: str, arguments: Mapping[str, Any] | None = Nonreturn f"{tool_name}:{digest}"+def _failure_category_identity(tool_name: str, category: str) -> str:+ return f"{tool_name}:failure_category:{category}"+++def _argument_insensitive_failure_category(result: Mapping[str, Any]) -> str | None:+ data = result.get("data")+ if isinstance(data, Mapping):+ raw_categories = data.get("failure_categories")+ if isinstance(raw_categories, list):+ for raw_category in raw_categories:+ if not isinstance(raw_category, Mapping):+ continue+ category = raw_category.get("category")+ if isinstance(category, str) and category in ARGUMENT_INSENSITIVE_FAILURE_CATEGORIES:+ return category++ failure_reason = data.get("failure_reason")+ if isinstance(failure_reason, str):+ categories = classify_from_failure_reason(failure_reason)+ for raw_category in categories or []:+ category = raw_category.get("category")+ if isinstance(category, str) and category in ARGUMENT_INSENSITIVE_FAILURE_CATEGORIES:+ return category++ error = result.get("error")+ if isinstance(error, str):+ categories = classify_from_failure_reason(error)+ for raw_category in categories or []:+ category = raw_category.get("category")+ if isinstance(category, str) and category in ARGUMENT_INSENSITIVE_FAILURE_CATEGORIES:+ return category++ return None+++def _argument_insensitive_failure_identity(tool_name: str, result: Mapping[str, Any]) -> str | None:+ if tool_name not in ARGUMENT_INSENSITIVE_FAILURE_TOOLS:+ return None+ category = _argument_insensitive_failure_category(result)+ return _failure_category_identity(tool_name, category) if category else None+++def _clear_argument_insensitive_failure_identities(tracker: MutableMapping[str, int], tool_name: str) -> None:+ prefix = f"{tool_name}:failure_category:"+ for key in list(tracker):+ if key.startswith(prefix):+ del tracker[key]+++def _detect_argument_insensitive_failed_tool_loop(+ tracker: MutableMapping[str, int],+ tool_name: str,+ threshold: int,+) -> tuple[str, int] | None:+ if tool_name not in ARGUMENT_INSENSITIVE_FAILURE_TOOLS:+ return None++ prefix = f"{tool_name}:failure_category:"+ for key, failure_count in tracker.items():+ if not key.startswith(prefix):+ continue+ next_attempt = failure_count + 1+ if next_attempt >= threshold:+ return key.removeprefix(prefix), failure_count+ return None++def detect_failed_tool_step_loop(tracker: MutableMapping[str, int],tool_name: str,@@ -74,6 +147,17 @@ def detect_failed_tool_step_loop(if not tracker:return None+ category_failure = _detect_argument_insensitive_failed_tool_loop(tracker, tool_name, threshold)+ if category_failure is not None:+ category, failure_count = category_failure+ next_attempt = failure_count + 1+ return (+ f"{LOOP_DETECTED_MARKER} '{tool_name}' has already failed "+ f"{failure_count} times with {category}; blocking attempt #{next_attempt}. "+ "This failure is not tied to the draft arguments. Fix the credential/configuration, "+ "ask the user, or produce your final JSON response."+ )+identity = tool_step_identity(tool_name, arguments)failure_count = tracker.get(identity, 0)next_attempt = failure_count + 1@@ -99,8 +183,10 @@ def record_tool_step_result(identity = tool_step_identity(tool_name, arguments)if result.get("ok", True):tracker.pop(identity, None)+ _clear_argument_insensitive_failure_identities(tracker, tool_name)return+ identity = _argument_insensitive_failure_identity(tool_name, result) or identitytracker[identity] = min(tracker.get(identity, 0) + 1, threshold)diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.pyindex 18eadde8b..d5d7c2d03 100644--- a/skyvern/forge/sdk/copilot/runtime.py+++ b/skyvern/forge/sdk/copilot/runtime.py@@ -94,6 +94,7 @@ class AgentContext:workflow_persisted: bool = Falselast_workflow: Any | None = Nonelast_workflow_yaml: str | None = None+ allow_untested_workflow_draft: bool = Falseeffective_workflow_proxy_location: Any | None = Nonecopilot_run_start_monotonic: float | None = Nonediff --git a/skyvern/forge/sdk/copilot/tools.py b/skyvern/forge/sdk/copilot/tools.pyindex 085a8d73e..6aaf4fc60 100644--- a/skyvern/forge/sdk/copilot/tools.py+++ b/skyvern/forge/sdk/copilot/tools.py@@ -126,6 +126,7 @@ RUN_BLOCKS_POLL_INTERVAL_SECONDS = 5.0# retrieved" warning cannot fire — each task adds a done-callback that logs# exceptions and removes itself from this set._DETACHED_CLEANUP_TASKS: set[asyncio.Task] = set()+_CREDENTIAL_ID_RE = re.compile(r"\bcred_[A-Za-z0-9][A-Za-z0-9_-]*\b")async def _cancel_run_task_if_not_final(@@ -178,6 +179,129 @@ def _log_detached_cleanup_failure(task: asyncio.Task) -> None:LOG.warning("Detached cancel fallback failed", exc_info=exc)+def _extract_credential_ids_from_tool_value(value: Any) -> list[str]:+ found: list[str] = []++ def visit(item: Any) -> None:+ if isinstance(item, str):+ found.extend(_CREDENTIAL_ID_RE.findall(item))+ elif isinstance(item, dict):+ for nested in item.values():+ visit(nested)+ elif isinstance(item, (list, tuple, set)):+ for nested in item:+ visit(nested)+ elif hasattr(item, "model_dump"):+ try:+ visit(item.model_dump(mode="json"))+ except Exception:+ return++ visit(value)+ return list(dict.fromkeys(found))+++def _extract_credential_ids_from_workflow_parameters(parameters: Any) -> list[str]:+ if not isinstance(parameters, list):+ return []++ found: list[str] = []+ for parameter in parameters:+ if not isinstance(parameter, dict):+ continue++ parameter_type = str(parameter.get("parameter_type") or "").lower()+ workflow_parameter_type = str(parameter.get("workflow_parameter_type") or "").lower()+ if parameter_type == "credential":+ found.extend(_extract_credential_ids_from_tool_value(parameter.get("credential_id")))+ elif parameter_type == "workflow" and workflow_parameter_type == WorkflowParameterType.CREDENTIAL_ID.value:+ found.extend(_extract_credential_ids_from_tool_value(parameter.get("default_value")))++ return list(dict.fromkeys(found))+++def _workflow_definition_as_dict(workflow_definition: Any) -> dict[str, Any]:+ if workflow_definition is None:+ return {}+ if isinstance(workflow_definition, dict):+ return workflow_definition+ if hasattr(workflow_definition, "model_dump"):+ try:+ dumped = workflow_definition.model_dump(mode="json")+ except Exception:+ return {}+ return dumped if isinstance(dumped, dict) else {}+ return {}+++def _extract_credential_ids_from_workflow_definition(workflow_definition: Any) -> list[str]:+ definition = _workflow_definition_as_dict(workflow_definition)+ return _extract_credential_ids_from_workflow_parameters(definition.get("parameters"))+++def _extract_credential_ids_from_workflow_yaml(workflow_yaml: str | None) -> list[str]:+ if not workflow_yaml:+ return []+ try:+ parsed = safe_load_no_dates(workflow_yaml)+ except yaml.YAMLError:+ return []+ if not isinstance(parsed, dict):+ return []+ workflow_definition = parsed.get("workflow_definition")+ if not isinstance(workflow_definition, dict):+ return []+ return _extract_credential_ids_from_workflow_parameters(workflow_definition.get("parameters"))+++def _missing_credential_reference_tool_error(missing_credential_ids: list[str]) -> str:+ formatted_ids = ", ".join(f"`{credential_id}`" for credential_id in missing_credential_ids)+ id_word = "ID" if len(missing_credential_ids) == 1 else "IDs"+ was_word = "was" if len(missing_credential_ids) == 1 else "were"+ return (+ f"The credential {id_word} {formatted_ids} {was_word} not found in this organization. "+ "Stop before creating, updating, or running the workflow. Ask the user to provide/select a valid "+ "credential ID, create the credential in the Credentials UI and return with its ID, or explicitly "+ "choose an unvalidated draft workflow that will not be run until credentials are available."+ )+++async def _credential_ids_validation_error(credential_ids: list[str], ctx: AgentContext) -> str | None:+ if not credential_ids:+ return None+ try:+ existing_credentials = await app.DATABASE.credentials.get_credentials_by_ids(+ credential_ids,+ organization_id=ctx.organization_id,+ )+ except Exception:+ LOG.warning(+ "Copilot tool failed to validate credential IDs",+ organization_id=ctx.organization_id,+ credential_ids=credential_ids,+ exc_info=True,+ )+ return (+ "Credential ID validation failed, so the workflow cannot be created, updated, or run safely. "+ "Ask the user to provide/select a valid credential ID or explicitly choose an unvalidated draft "+ "workflow that will not be run until credentials are available."+ )++ found_ids = {credential.credential_id for credential in existing_credentials}+ missing_ids = [credential_id for credential_id in credential_ids if credential_id not in found_ids]+ if not missing_ids:+ return None+ return _missing_credential_reference_tool_error(missing_ids)+++async def _credential_reference_validation_error(value: Any, ctx: AgentContext) -> str | None:+ if isinstance(value, str):+ credential_ids = _extract_credential_ids_from_workflow_yaml(value)+ else:+ credential_ids = _extract_credential_ids_from_tool_value(value)+ return await _credential_ids_validation_error(credential_ids, ctx)++async def _safe_read_workflow_run(workflow_run_id: str,organization_id: str,@@ -591,8 +715,20 @@ def _parameter_binding_invariant_error()-async def _update_workflow(params: dict[str, Any], ctx: AgentContext) -> dict[str, Any]:+async def _update_workflow(+ params: dict[str, Any],+ ctx: AgentContext,+ *,+ allow_missing_credentials: bool | None = None,+) -> dict[str, Any]:workflow_yaml = params["workflow_yaml"]+ if allow_missing_credentials is None:+ allow_missing_credentials = getattr(ctx, "allow_untested_workflow_draft", False) is True+ if not allow_missing_credentials:+ credential_error = await _credential_reference_validation_error(workflow_yaml, ctx)+ if credential_error is not None:+ return {"ok": False, "error": credential_error}+# Prefer the most-recent in-turn emission so cross-path flows (inline# REPLACE_WORKFLOW followed by update_workflow) compare against what the# LLM actually saw, not the turn-start persisted state.@@ -1470,6 +1606,16 @@ async def _run_blocks_and_collect_debug(if not workflow:return {"ok": False, "error": f"Workflow not found: {ctx.workflow_permanent_id}"}+ credential_ids = list(+ dict.fromkeys(+ _extract_credential_ids_from_tool_value(params.get("parameters") or {})+ + _extract_credential_ids_from_workflow_definition(workflow.workflow_definition)+ )+ )+ credential_error = await _credential_ids_validation_error(credential_ids, ctx)+ if credential_error is not None:+ return {"ok": False, "error": credential_error}+for label in block_labels:if not workflow.get_output_parameter(label):return {"ok": False, "error": f"Block label not found in saved workflow: {label!r}"}@@ -2739,7 +2885,11 @@ async def update_workflow_tool(return json.dumps({"ok": False, "error": loop_error})with copilot_span("update_workflow", data={"yaml_length": len(workflow_yaml)}):- result = await _update_workflow(arguments, copilot_ctx)+ result = await _update_workflow(+ arguments,+ copilot_ctx,+ allow_missing_credentials=getattr(copilot_ctx, "allow_untested_workflow_draft", False) is True,+ )_record_workflow_update_result(copilot_ctx, result)record_tool_step_result_for_ctx(copilot_ctx, "update_workflow", arguments, result)sanitized = sanitize_tool_result_for_llm("update_workflow", result)@@ -2933,7 +3083,11 @@ async def update_and_run_blocks_tool(# Step 1: Update the workflowwith copilot_span("update_workflow", data={"yaml_length": len(workflow_yaml)}):- update_result = await _update_workflow({"workflow_yaml": workflow_yaml}, copilot_ctx)+ update_result = await _update_workflow(+ {"workflow_yaml": workflow_yaml},+ copilot_ctx,+ allow_missing_credentials=False,+ )_record_workflow_update_result(copilot_ctx, update_result)if not update_result.get("ok"):diff --git a/skyvern/forge/sdk/routes/workflow_copilot.py b/skyvern/forge/sdk/routes/workflow_copilot.pyindex dab3b5d1c..fe6e0aac3 100644--- a/skyvern/forge/sdk/routes/workflow_copilot.py+++ b/skyvern/forge/sdk/routes/workflow_copilot.py@@ -2,6 +2,7 @@ import asyncioimport contextlibimport timefrom contextlib import contextmanager+from copy import deepcopyfrom dataclasses import dataclassfrom datetime import datetime, timedelta, timezonefrom pathlib import Path@@ -1076,6 +1077,118 @@ def _process_workflow_yaml()+def _workflow_yaml_block_count(workflow_yaml: str | None) -> int:+ if not workflow_yaml:+ return 0+ try:+ parsed_yaml = safe_load_no_dates(workflow_yaml)+ except Exception:+ return 0+ if not isinstance(parsed_yaml, dict):+ return 0++ workflow_definition = parsed_yaml.get("workflow_definition")+ if not isinstance(workflow_definition, dict):+ return 0+ blocks = workflow_definition.get("blocks")+ if not isinstance(blocks, list):+ return 0+ return len(blocks)+++def _strip_runtime_block_fields(block: dict[str, Any]) -> dict[str, Any]:+ cleaned = deepcopy(block)+ cleaned.pop("output_parameter", None)+ cleaned.pop("workflow_system_prompt", None)++ parameters = cleaned.pop("parameters", None)+ if isinstance(parameters, list) and "parameter_keys" not in cleaned:+ parameter_keys = [+ parameter.get("key")+ for parameter in parameters+ if isinstance(parameter, dict)+ and parameter.get("key")+ and parameter.get("parameter_type") != ParameterType.OUTPUT.value+ ]+ if parameter_keys:+ cleaned["parameter_keys"] = parameter_keys++ loop_over = cleaned.pop("loop_over", None)+ if isinstance(loop_over, dict) and "loop_over_parameter_key" not in cleaned:+ loop_over_parameter_key = loop_over.get("key")+ if loop_over_parameter_key:+ cleaned["loop_over_parameter_key"] = loop_over_parameter_key++ loop_blocks = cleaned.get("loop_blocks")+ if isinstance(loop_blocks, list):+ cleaned["loop_blocks"] = [+ _strip_runtime_block_fields(loop_block) if isinstance(loop_block, dict) else loop_block+ for loop_block in loop_blocks+ ]+ return cleaned+++def _workflow_to_copilot_yaml(workflow: Workflow) -> str:+ workflow_data = workflow.model_dump(mode="json", exclude_none=True)+ workflow_definition = deepcopy(workflow_data.get("workflow_definition") or {})++ parameters = workflow_definition.get("parameters")+ if isinstance(parameters, list):+ workflow_definition["parameters"] = [+ parameter+ for parameter in parameters+ if not (isinstance(parameter, dict) and parameter.get("parameter_type") == ParameterType.OUTPUT.value)+ ]++ blocks = workflow_definition.get("blocks")+ if isinstance(blocks, list):+ workflow_definition["blocks"] = [+ _strip_runtime_block_fields(block) if isinstance(block, dict) else block for block in blocks+ ]++ request_data = {+ key: workflow_data[key]+ for key in WorkflowCreateYAMLRequest.model_fields+ if key != "workflow_definition" and key in workflow_data+ }+ request_data["workflow_definition"] = workflow_definition++ try:+ workflow_request = WorkflowCreateYAMLRequest.model_validate(request_data)+ yaml_data = workflow_request.model_dump(mode="json", exclude_none=True)+ except ValidationError:+ LOG.warning(+ "Persisted workflow did not round-trip through copilot YAML schema; using best-effort workflow dump",+ workflow_id=workflow.workflow_id,+ workflow_permanent_id=workflow.workflow_permanent_id,+ exc_info=True,+ )+ yaml_data = request_data+ return yaml.safe_dump(yaml_data, sort_keys=False)+++def _ensure_copilot_workflow_yaml(chat_request: WorkflowCopilotChatRequest, original_workflow: Workflow) -> None:+ if _workflow_yaml_block_count(chat_request.workflow_yaml) > 0:+ return+ workflow_definition = original_workflow.workflow_definition+ if workflow_definition is None or not workflow_definition.blocks:+ return++ persisted_workflow_yaml = _workflow_to_copilot_yaml(original_workflow)+ if not persisted_workflow_yaml:+ return++ LOG.warning(+ "Copilot V2 chat request had no workflow blocks; using persisted workflow YAML",+ workflow_permanent_id=chat_request.workflow_permanent_id,+ workflow_id=original_workflow.workflow_id,+ submitted_workflow_yaml_length=len(chat_request.workflow_yaml or ""),+ persisted_workflow_yaml_length=len(persisted_workflow_yaml),+ persisted_block_count=len(workflow_definition.blocks),+ )+ chat_request.workflow_yaml = persisted_workflow_yaml++async def _new_copilot_chat_post(request: Request,chat_request: WorkflowCopilotChatRequest,@@ -1190,6 +1303,7 @@ 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)llm_api_handler = await _resolve_copilot_agent_handler(chat_request.workflow_permanent_id, organization.organization_iddiff --git a/tests/smoke_tests/test_while_loop_pagination.py b/tests/smoke_tests/test_while_loop_pagination.pynew file mode 100644index 000000000..56002e215--- /dev/null+++ b/tests/smoke_tests/test_while_loop_pagination.py@@ -0,0 +1,136 @@+from typing import Any+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from skyvern.forge.sdk.workflow.models import block as block_module+from skyvern.forge.sdk.workflow.models.block import Block, WhileLoopBlock+from skyvern.forge.sdk.workflow.workflow_definition_converter import convert_workflow_definition+from skyvern.schemas.workflows import (+ ActionBlockYAML,+ BlockResult,+ BlockStatus,+ BranchCriteriaYAML,+ ExtractionBlockYAML,+ WhileLoopBlockYAML,+ WorkflowDefinitionYAML,+)+from tests.unit.fake_workflow_run_context import FakeWorkflowRunContext+++class SmokeWorkflowRunContext(FakeWorkflowRunContext):+ def get_value(self, key: str) -> Any:+ return self.values[key]++ async def register_output_parameter_value_post_execution(self, parameter: Any, value: Any) -> None:+ self.set_value(parameter.key, value)+ if not parameter.key.endswith("_output"):+ return++ block_label = parameter.key.removesuffix("_output")+ self.set_value(block_label, dict(value) if isinstance(value, dict) else value)+ self.workflow_run_outputs[block_label] = value+++def _make_pagination_while_loop() -> WhileLoopBlock:+ workflow_definition = WorkflowDefinitionYAML(+ parameters=[],+ blocks=[+ WhileLoopBlockYAML(+ label="paginate_results",+ condition=BranchCriteriaYAML(+ criteria_type="jinja2_template",+ expression="{{ current_index == 0 or extract_page.has_next_page }}",+ ),+ loop_blocks=[+ ExtractionBlockYAML(+ label="extract_page",+ next_block_label="click_next",+ data_extraction_goal="Extract visible rows and whether another page is available",+ data_schema={+ "type": "object",+ "properties": {+ "rows": {"type": "array", "items": {"type": "object"}},+ "has_next_page": {"type": "boolean"},+ },+ },+ ),+ ActionBlockYAML(+ label="click_next",+ navigation_goal="Click the Next button if it is enabled",+ ),+ ],+ )+ ],+ )++ converted = convert_workflow_definition(workflow_definition, workflow_id="wf_smoke")+ loop_block = converted.blocks[0]+ assert isinstance(loop_block, WhileLoopBlock)+ return loop_block+++async def test_while_loop_paginates_until_next_is_unavailable() -> None:+ loop_block = _make_pagination_while_loop()+ workflow_run_context = SmokeWorkflowRunContext(values={})+ pages = [+ {"rows": [{"name": "Alpha"}, {"name": "Beta"}], "has_next_page": True},+ {"rows": [{"name": "Gamma"}], "has_next_page": False},+ ]+ current_page = 0+ executed_steps: list[tuple[str, int]] = []++ async def fake_execute_safe(block: Block, **kwargs: Any) -> BlockResult:+ nonlocal current_page++ loop_index = kwargs["current_index"]+ executed_steps.append((block.label, loop_index))++ if block.label == "extract_page":+ output_value = pages[current_page]+ elif block.label == "click_next":+ output_value = {"clicked": pages[current_page]["has_next_page"]}+ if pages[current_page]["has_next_page"]:+ current_page += 1+ else:+ raise AssertionError(f"Unexpected block executed: {block.label}")++ await workflow_run_context.register_output_parameter_value_post_execution(block.output_parameter, output_value)+ return BlockResult(+ success=True,+ output_parameter=block.output_parameter,+ output_parameter_value=output_value,+ status=BlockStatus.completed,+ workflow_run_block_id=f"wrb_{block.label}_{loop_index}",+ )++ mock_app = MagicMock()+ mock_skyvern_ctx = MagicMock()+ with (+ patch.object(Block, "execute_safe", new=fake_execute_safe),+ patch.dict(block_module.__dict__, {"app": mock_app, "skyvern_context": mock_skyvern_ctx}),+ ):+ mock_skyvern_ctx.current.return_value = None+ mock_app.DATABASE.workflow_runs.create_or_update_workflow_run_output_parameter = AsyncMock()+ mock_app.DATABASE.observer.update_workflow_run_block = AsyncMock()++ result = await loop_block._execute_while_loop_helper(+ workflow_run_id="wr_smoke",+ workflow_run_block_id="wrb_paginate_results",+ workflow_run_context=workflow_run_context,+ organization_id="org_smoke",+ )++ assert executed_steps == [+ ("extract_page", 0),+ ("click_next", 0),+ ("extract_page", 1),+ ("click_next", 1),+ ]+ assert result.natural_completion is True+ assert len(result.outputs_with_loop_values) == 2+ assert len(result.block_outputs) == 4+ assert all(block_output.status == BlockStatus.completed for block_output in result.block_outputs)+ assert workflow_run_context.values["extract_page"]["rows"] == [{"name": "Gamma"}]+ assert workflow_run_context.values["extract_page"]["has_next_page"] is Falsediff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.pyindex ff4d53b12..95301d4fd 100644--- a/tests/unit/test_copilot_agent_helpers.py+++ b/tests/unit/test_copilot_agent_helpers.py@@ -4,7 +4,9 @@ from __future__ import annotationsimport jsonfrom types import SimpleNamespace-from unittest.mock import MagicMock+from unittest.mock import AsyncMock, MagicMock++import pytestfrom skyvern.forge.sdk.copilot import agent as agent_module@@ -110,6 +112,22 @@ class TestFailedTestResponseNormalization:original = "Let me know what you want to build."assert _rewrite_failed_test_response(original, ctx) == original+ def test_rewrite_untested_draft_request_surfaces_explicit_unverified_copy(self) -> None:+ from skyvern.forge.sdk.copilot.agent import _rewrite_failed_test_response++ ctx = _ctx(+ allow_untested_workflow_draft=True,+ last_workflow=object(),+ last_workflow_yaml="title: drafted",+ last_update_block_count=2,+ last_test_ok=None,+ )+ rewritten = _rewrite_failed_test_response("Done.", ctx)++ assert "without testing it, as requested" in rewritten+ assert "not been verified end-to-end" in rewritten+ assert "successful" not in rewritten.lower()+def test_rewrite_appends_keep_draft_affordance_when_draft_on_hand(self) -> None:from skyvern.forge.sdk.copilot.agent import _rewrite_failed_test_response@@ -175,6 +193,21 @@ class TestVerifiedWorkflowOrNone:assert _verified_workflow_or_none(ctx) == (None, None)+class TestUntestedDraftRequest:+ def test_detects_explicit_skip_testing_request(self) -> None:+ from skyvern.forge.sdk.copilot.agent import _user_requests_untested_workflow_draft++ assert _user_requests_untested_workflow_draft("Can you just make a workflow without testing it?")+ assert _user_requests_untested_workflow_draft("Draft only please; do not test.")+ assert _user_requests_untested_workflow_draft("Skip testing and create the workflow.")++ def test_does_not_detect_routine_testing_mentions(self) -> None:+ from skyvern.forge.sdk.copilot.agent import _user_requests_untested_workflow_draft++ assert not _user_requests_untested_workflow_draft("Build and test this workflow.")+ assert not _user_requests_untested_workflow_draft("Test the login step before you finish.")++class TestShouldRestorePersistedWorkflow:"""SKY-9143: auto_accept=True must still restore when no proposal shipped."""@@ -774,6 +807,246 @@ class TestCredentialRefusalReachesAgent:assert cross_ref.search(desc), f"{tool.name} missing refusal cross-reference"+class TestUserSuppliedCredentialIdValidation:+ def test_extracts_unique_credential_ids_from_latest_message(self) -> None:+ ids = agent_module._extract_user_supplied_credential_ids(+ "Use cred_123456789, then cred_abc-DEF_42. Also repeat cred_123456789."+ )++ assert ids == ["cred_123456789", "cred_abc-DEF_42"]++ def test_ignores_non_credential_secret_text(self) -> None:+ ids = agent_module._extract_user_supplied_credential_ids(+ "My username is [email protected] and my password is hunter2."+ )++ assert ids == []++ @pytest.mark.asyncio+ async def test_missing_user_supplied_credential_ids_return_ask_question(self, monkeypatch) -> None:+ get_credentials_by_ids = AsyncMock(return_value=[SimpleNamespace(credential_id="cred_valid")])+ monkeypatch.setattr(+ agent_module.app,+ "DATABASE",+ SimpleNamespace(credentials=SimpleNamespace(get_credentials_by_ids=get_credentials_by_ids)),+ )++ result = await agent_module._credential_validation_result_for_user_message(+ user_message="Please build it with cred_valid and cred_missing.",+ organization_id="org-1",+ global_llm_context=None,+ )++ assert result is not None+ assert result.response_type == "ASK_QUESTION"+ assert result.updated_workflow is None+ assert result.workflow_yaml is None+ assert result.workflow_was_persisted is False+ assert result.clear_proposed_workflow is True+ assert "cred_missing" in result.user_response+ assert "not found in this organization" in result.user_response+ assert "unvalidated draft workflow" in result.user_response+ get_credentials_by_ids.assert_awaited_once_with(["cred_valid", "cred_missing"], organization_id="org-1")++ @pytest.mark.asyncio+ async def test_missing_user_supplied_credential_ids_continue_for_explicit_untested_draft(self, monkeypatch) -> None:+ get_credentials_by_ids = AsyncMock(return_value=[])+ monkeypatch.setattr(+ agent_module.app,+ "DATABASE",+ SimpleNamespace(credentials=SimpleNamespace(get_credentials_by_ids=get_credentials_by_ids)),+ )++ result = await agent_module._credential_validation_result_for_user_message(+ user_message="Build an untested draft with cred_missing.",+ organization_id="org-1",+ global_llm_context=None,+ allow_untested_workflow_draft=True,+ )++ assert result is None+ get_credentials_by_ids.assert_not_called()++ @pytest.mark.asyncio+ async def test_valid_user_supplied_credential_ids_continue_normally(self, monkeypatch) -> None:+ get_credentials_by_ids = AsyncMock(return_value=[SimpleNamespace(credential_id="cred_valid")])+ monkeypatch.setattr(+ agent_module.app,+ "DATABASE",+ SimpleNamespace(credentials=SimpleNamespace(get_credentials_by_ids=get_credentials_by_ids)),+ )++ result = await agent_module._credential_validation_result_for_user_message(+ user_message="Please build it with cred_valid.",+ organization_id="org-1",+ global_llm_context=None,+ )++ assert result is None+ get_credentials_by_ids.assert_awaited_once_with(["cred_valid"], organization_id="org-1")++ def test_translate_untested_draft_request_surfaces_unvalidated_workflow(self) -> None:+ wf = SimpleNamespace(name="drafted")+ ctx = _ctx(+ allow_untested_workflow_draft=True,+ last_workflow=wf,+ last_workflow_yaml="title: drafted",+ last_update_block_count=4,+ last_test_ok=None,+ )+ result = _fake_run_result({"type": "REPLY", "user_response": "Done."})++ agent_result = agent_module._translate_to_agent_result(+ result, ctx, global_llm_context=None, chat_request=_chat_request(), organization_id="org-1"+ )++ assert agent_result.updated_workflow is wf+ assert agent_result.workflow_yaml == "title: drafted"+ assert agent_result.unvalidated is True+ assert "without testing it, as requested" in agent_result.user_response+++class TestNativeToolCredentialIdValidation:+ def test_extracts_credential_ids_from_nested_tool_values(self) -> None:+ from skyvern.forge.sdk.copilot.tools import _extract_credential_ids_from_tool_value++ ids = _extract_credential_ids_from_tool_value(+ {+ "workflow_yaml": "credential_id: cred_valid",+ "parameters": {"login": "cred_missing", "note": "repeat cred_valid"},+ }+ )++ assert ids == ["cred_valid", "cred_missing"]++ def test_workflow_yaml_extraction_ignores_credential_like_parameter_keys(self) -> None:+ from skyvern.forge.sdk.copilot.tools import _extract_credential_ids_from_workflow_yaml++ ids = _extract_credential_ids_from_workflow_yaml(+ """+workflow_definition:+ parameters:+ - parameter_type: workflow+ workflow_parameter_type: credential_id+ key: cred_param+ default_value: cred_valid+ - parameter_type: workflow+ workflow_parameter_type: string+ key: cred_not_an_id+ default_value: cred_also_not_an_id+"""+ )++ assert ids == ["cred_valid"]++ @pytest.mark.asyncio+ async def test_missing_tool_credential_reference_returns_blocking_error(self, monkeypatch) -> None:+ from skyvern.forge.sdk.copilot.tools import _credential_reference_validation_error++ get_credentials_by_ids = AsyncMock(return_value=[SimpleNamespace(credential_id="cred_valid")])+ monkeypatch.setattr(+ agent_module.app,+ "DATABASE",+ SimpleNamespace(credentials=SimpleNamespace(get_credentials_by_ids=get_credentials_by_ids)),+ )++ error = await _credential_reference_validation_error(+ """+workflow_definition:+ parameters:+ - parameter_type: credential+ key: credentials+ credential_id: cred_valid+ - parameter_type: workflow+ workflow_parameter_type: credential_id+ key: backup_credentials+ default_value: cred_missing+""",+ _ctx(),+ )++ assert error is not None+ assert "cred_missing" in error+ assert "not found in this organization" in error+ assert "Stop before creating, updating, or running the workflow" in error+ get_credentials_by_ids.assert_awaited_once_with(["cred_valid", "cred_missing"], organization_id="org-1")++ @pytest.mark.asyncio+ async def test_valid_tool_credential_reference_allows_tool_path(self, monkeypatch) -> None:+ from skyvern.forge.sdk.copilot.tools import _credential_reference_validation_error++ get_credentials_by_ids = AsyncMock(return_value=[SimpleNamespace(credential_id="cred_valid")])+ monkeypatch.setattr(+ agent_module.app,+ "DATABASE",+ SimpleNamespace(credentials=SimpleNamespace(get_credentials_by_ids=get_credentials_by_ids)),+ )++ error = await _credential_reference_validation_error({"credential_id": "cred_valid"}, _ctx())++ assert error is None+ get_credentials_by_ids.assert_awaited_once_with(["cred_valid"], organization_id="org-1")++ @pytest.mark.asyncio+ async def test_update_workflow_allows_missing_credentials_for_explicit_untested_draft(self, monkeypatch) -> None:+ from skyvern.forge.sdk.copilot.tools import _update_workflow++ ctx = _ctx(allow_untested_workflow_draft=True)++ workflow = MagicMock()+ workflow.title = "Untested Draft"+ workflow.description = ""+ workflow.workflow_definition = MagicMock()+ workflow.workflow_definition.blocks = []+ workflow.proxy_location = None+ workflow.webhook_callback_url = None+ workflow.persist_browser_session = False+ workflow.model = None+ workflow.max_screenshot_scrolls = None+ workflow.extra_http_headers = None+ workflow.run_with = None+ workflow.ai_fallback = None+ workflow.cache_key = None+ workflow.run_sequentially = False+ workflow.sequential_key = None++ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.tools._process_workflow_yaml",+ lambda **kwargs: workflow,+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.tools.resolve_copilot_created_by_stamp",+ AsyncMock(return_value="copilot"),+ )+ workflow_service = MagicMock()+ workflow_service.update_workflow_definition = AsyncMock()+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools.app.WORKFLOW_SERVICE", workflow_service)+ get_credentials_by_ids = AsyncMock(return_value=[])+ monkeypatch.setattr(+ agent_module.app,+ "DATABASE",+ SimpleNamespace(credentials=SimpleNamespace(get_credentials_by_ids=get_credentials_by_ids)),+ )++ result = await _update_workflow(+ {+ "workflow_yaml": """+workflow_definition:+ parameters:+ - parameter_type: workflow+ workflow_parameter_type: credential_id+ key: login_credentials+ default_value: cred_missing+ blocks: []+"""+ },+ ctx,+ )++ assert result["ok"] is True+ get_credentials_by_ids.assert_not_called()++class TestResponseTypeClassificationRuleReachesAgent:"""Pin the classifier rule that selects ASK_QUESTION when `user_response` asks the user for required input — the agent.py null-out gate keys on `resp_type == "ASK_QUESTION"` and depends on this prompt text."""@@ -788,4 +1061,6 @@ class TestResponseTypeClassificationRuleReachesAgent:assert "goal_reached: false" in promptassert "Classify by intent, not punctuation" in promptassert "does NOT imply REPLY" in prompt+ assert "explicitly asks for an untested draft" in prompt+ assert "workflow was drafted without testing as requested" in promptassert prompt.index("RESPONSE-TYPE CLASSIFICATION") < prompt.index("**Option 1: Reply to the user**")diff --git a/tests/unit/test_copilot_enforcement_pruning.py b/tests/unit/test_copilot_enforcement_pruning.pyindex f8b0fa98e..e3b9f0eb1 100644--- a/tests/unit/test_copilot_enforcement_pruning.py+++ b/tests/unit/test_copilot_enforcement_pruning.py@@ -655,6 +655,17 @@ class TestEnforcement:assert nudge != POST_EXPLORE_WITHOUT_WORKFLOW_NUDGEassert ctx.explore_without_workflow_nudge_count == 0+ def test_update_without_test_allowed_for_explicit_untested_draft(self) -> None:+ from skyvern.forge.sdk.copilot.enforcement import _check_enforcement++ ctx = self._make_ctx(+ allow_untested_workflow_draft=True,+ update_workflow_called=True,+ test_after_update_done=False,+ )++ assert _check_enforcement(ctx) is None+def test_explore_without_workflow_not_when_test_done(self) -> None:from skyvern.forge.sdk.copilot.enforcement import POST_EXPLORE_WITHOUT_WORKFLOW_NUDGE, _check_enforcementdiff --git a/tests/unit/test_copilot_loop_detection.py b/tests/unit/test_copilot_loop_detection.pyindex 564f9a38a..485a3fab9 100644--- a/tests/unit/test_copilot_loop_detection.py+++ b/tests/unit/test_copilot_loop_detection.py@@ -106,6 +106,57 @@ class TestFailedToolStepLoopDetection:assert detect_failed_tool_step_loop(tracker, "click", {"selector": "#second"}) is Noneassert detect_failed_tool_step_loop(tracker, "click", {"selector": "#first"}) is not None+ def test_block_running_credential_errors_share_failure_streak_across_arguments(self) -> None:+ tracker: dict[str, int] = {}++ record_tool_step_result(+ tracker,+ "run_blocks_and_collect_debug",+ {"block_labels": ["draft_a"], "parameters": {}},+ {"ok": False, "error": "Credential username not found by key: first"},+ )+ record_tool_step_result(+ tracker,+ "run_blocks_and_collect_debug",+ {"block_labels": ["draft_b"], "parameters": {}},+ {"ok": False, "error": "Credential username not found by key: second"},+ )++ msg = detect_failed_tool_step_loop(+ tracker,+ "run_blocks_and_collect_debug",+ {"block_labels": ["draft_c"], "parameters": {}},+ )++ assert msg is not None+ assert "LOOP DETECTED" in msg+ assert "CREDENTIAL_ERROR" in msg++ def test_generic_block_running_errors_still_key_by_arguments(self) -> None:+ tracker: dict[str, int] = {}++ record_tool_step_result(+ tracker,+ "run_blocks_and_collect_debug",+ {"block_labels": ["draft_a"], "parameters": {}},+ {"ok": False, "error": "temporary page state mismatch"},+ )+ record_tool_step_result(+ tracker,+ "run_blocks_and_collect_debug",+ {"block_labels": ["draft_b"], "parameters": {}},+ {"ok": False, "error": "temporary page state mismatch"},+ )++ assert (+ detect_failed_tool_step_loop(+ tracker,+ "run_blocks_and_collect_debug",+ {"block_labels": ["draft_c"], "parameters": {}},+ )+ is None+ )+def test_block_threshold_is_two_failures(self) -> None:tracker: dict[str, int] = {}diff --git a/tests/unit/test_failure_classifier.py b/tests/unit/test_failure_classifier.pyindex 230de1278..538a71f87 100644--- a/tests/unit/test_failure_classifier.py+++ b/tests/unit/test_failure_classifier.py@@ -207,6 +207,12 @@ class TestCredentialError:categories = [r["category"] for r in result]assert "CREDENTIAL_ERROR" in categories+ def test_key_lookup_failure(self) -> None:+ result = classify_from_failure_reason("Credential username not found by key: login")+ assert result is not None+ categories = [r["category"] for r in result]+ assert "CREDENTIAL_ERROR" in categories+def test_exception_type_bitwarden(self) -> None:class BitwardenVaultError(Exception):passdiff --git a/tests/unit/test_workflow_copilot_prompt_injection.py b/tests/unit/test_workflow_copilot_prompt_injection.pyindex 46dd8a0f0..524a5ca3d 100644--- a/tests/unit/test_workflow_copilot_prompt_injection.py+++ b/tests/unit/test_workflow_copilot_prompt_injection.py@@ -12,7 +12,7 @@ from 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+from skyvern.forge.sdk.copilot.agent import _build_system_prompt, _build_user_context, _build_workflow_summaryfrom skyvern.forge.sdk.routes.workflow_copilot import copilot_call_llmfrom skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotChatRequestfrom skyvern.utils.strings import escape_code_fences@@ -361,6 +361,34 @@ class TestBuildUserContext:# must be escaped by escape_code_fences().assert "``` injected ```" not in rendered+ def test_workflow_summary_indexes_block_labels_and_error_mappings(self) -> None:+ workflow_yaml = """+title: Invoice workflow+workflow_definition:+ parameters: []+ blocks:+ - block_type: file_download+ label: block_2+ navigation_goal: Download the invoice for {{ invoice_date }}+ error_code_mapping:+ DATA_UNAVAILABLE: only if the account exists but the invoice for {{ invoice_date }} is missing+"""++ summary = _build_workflow_summary(workflow_yaml)+ rendered = _build_user_context(+ workflow_yaml=workflow_yaml,+ chat_history_text="",+ global_llm_context="",+ debug_run_info_text="",+ user_message="why did block_2 not trigger DATA_UNAVAILABLE?",+ )++ assert "- block_2 (file_download)" in summary+ assert "DATA_UNAVAILABLE: only if the account exists" in summary+ assert "Workflow block summary:" in rendered+ assert "- block_2 (file_download)" in rendered+ assert "Use this summary as a block-label index" in rendered+class TestUserTemplateCodeFencingNewCopilot:"""Verify untrusted variables are wrapped in code fences (legacy user template)."""diff --git a/tests/unit/test_workflow_copilot_workflow_state.py b/tests/unit/test_workflow_copilot_workflow_state.pynew file mode 100644index 000000000..b51dd9aeb--- /dev/null+++ b/tests/unit/test_workflow_copilot_workflow_state.py@@ -0,0 +1,131 @@+from datetime import datetime, timezone++import yaml++from skyvern.forge.sdk.routes.workflow_copilot import _ensure_copilot_workflow_yaml, _workflow_to_copilot_yaml+from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotChatRequest+from skyvern.forge.sdk.workflow.models.block import FileDownloadBlock+from skyvern.forge.sdk.workflow.models.parameter import OutputParameter, WorkflowParameter, WorkflowParameterType+from skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowDefinition+++def _output_parameter(now: datetime) -> OutputParameter:+ return OutputParameter(+ output_parameter_id="op_block_2",+ workflow_id="w_saved",+ key="block_2_output",+ created_at=now,+ modified_at=now,+ )+++def _saved_workflow() -> Workflow:+ now = datetime.now(timezone.utc)+ invoice_date = WorkflowParameter(+ workflow_parameter_id="wp_invoice_date",+ workflow_id="w_saved",+ key="invoice_date",+ workflow_parameter_type=WorkflowParameterType.STRING,+ created_at=now,+ modified_at=now,+ )+ block_output = _output_parameter(now)+ block = FileDownloadBlock(+ label="block_2",+ output_parameter=block_output,+ navigation_goal="Download the invoice for {{ invoice_date }}",+ parameters=[invoice_date],+ error_code_mapping={+ "DATA_UNAVAILABLE": ("only if the account exists but the invoice for {{ invoice_date }} is missing"),+ },+ )++ return Workflow(+ workflow_id="w_saved",+ organization_id="o_test",+ title="Saved workflow",+ workflow_permanent_id="wpid_test",+ version=3,+ is_saved_task=False,+ workflow_definition=WorkflowDefinition(+ parameters=[invoice_date, block_output],+ blocks=[block],+ ),+ created_at=now,+ modified_at=now,+ )+++def _chat_request(workflow_yaml: str) -> WorkflowCopilotChatRequest:+ return WorkflowCopilotChatRequest(+ workflow_permanent_id="wpid_test",+ workflow_id="w_client",+ message="why did block_2 not trigger DATA_UNAVAILABLE?",+ workflow_yaml=workflow_yaml,+ )+++def test_workflow_to_copilot_yaml_keeps_saved_blocks_without_runtime_fields() -> None:+ persisted_yaml = _workflow_to_copilot_yaml(_saved_workflow())+ parsed = yaml.safe_load(persisted_yaml)++ blocks = parsed["workflow_definition"]["blocks"]+ assert blocks[0]["label"] == "block_2"+ assert blocks[0]["block_type"] == "file_download"+ assert blocks[0]["error_code_mapping"]["DATA_UNAVAILABLE"].startswith("only if the account exists")+ assert blocks[0]["parameter_keys"] == ["invoice_date"]+ assert "output_parameter" not in blocks[0]+ assert "parameters" not in blocks[0]+ assert all(parameter["parameter_type"] != "output" for parameter in parsed["workflow_definition"]["parameters"])+++def test_ensure_copilot_workflow_yaml_uses_persisted_workflow_when_request_has_no_blocks() -> None:+ chat_request = _chat_request(+ """+title: Stale client workflow+workflow_definition:+ parameters: []+ blocks: []+"""+ )++ _ensure_copilot_workflow_yaml(chat_request, _saved_workflow())++ parsed = yaml.safe_load(chat_request.workflow_yaml)+ assert parsed["workflow_definition"]["blocks"][0]["label"] == "block_2"+ assert parsed["workflow_definition"]["blocks"][0]["block_type"] == "file_download"+++def test_ensure_copilot_workflow_yaml_ignores_persisted_workflow_without_definition() -> None:+ workflow = _saved_workflow()+ workflow.workflow_definition = None+ chat_request = _chat_request(+ """+title: Stale client workflow+workflow_definition:+ parameters: []+ blocks: []+"""+ )++ _ensure_copilot_workflow_yaml(chat_request, workflow)++ parsed = yaml.safe_load(chat_request.workflow_yaml)+ assert parsed["workflow_definition"]["blocks"] == []+++def test_ensure_copilot_workflow_yaml_preserves_client_workflow_when_it_has_blocks() -> None:+ client_yaml = """+title: Client workflow+workflow_definition:+ parameters: []+ blocks:+ - block_type: goto_url+ label: client_block+ url: https://example.com+"""+ chat_request = _chat_request(client_yaml)++ _ensure_copilot_workflow_yaml(chat_request, _saved_workflow())++ assert chat_request.workflow_yaml == client_yaml