Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat: default new workflows to run_with="agent" (#6060)
pedrohsdb576c11b4230b
diff --git a/skyvern-frontend/src/routes/tasks/create/PromptBox.tsx b/skyvern-frontend/src/routes/tasks/create/PromptBox.tsxindex 03c23d6be..f72fa6002 100644--- a/skyvern-frontend/src/routes/tasks/create/PromptBox.tsx+++ b/skyvern-frontend/src/routes/tasks/create/PromptBox.tsx@@ -126,13 +126,22 @@ function deriveHandoffTitle(prompt: string): string {return `${collapsed.slice(0, HANDOFF_TITLE_MAX_LEN - 1).trimEnd()}…`;}-function buildBlankWorkflowRequest(title: string): WorkflowCreateYAMLRequest {+function runWithFromSelector(+ legacyVersion: "v1" | "v2" | "v2-code",+): "agent" | "code" {+ return legacyVersion === "v2-code" ? "code" : "agent";+}++function buildBlankWorkflowRequest(+ title: string,+ runWith: "agent" | "code" = "agent",+): WorkflowCreateYAMLRequest {return {title,description: "",ai_fallback: true,code_version: 2,- run_with: "code",+ run_with: runWith,workflow_definition: {version: 2,blocks: [],@@ -144,9 +153,7 @@ function buildBlankWorkflowRequest(title: string): WorkflowCreateYAMLRequest {function PromptBox({ enableCopilotHandoff = false }: PromptBoxProps) {const navigate = useNavigate();const [prompt, setPrompt] = useState<string>("");- const [selectValue, setSelectValue] = useState<"v1" | "v2" | "v2-code">(- "v2-code",- ); // v2-code is the default+ const [selectValue, setSelectValue] = useState<"v1" | "v2" | "v2-code">("v2"); // v2 (agent) is the defaultconst credentialGetter = useCredentialGetter();const queryClient = useQueryClient();const [webhookCallbackUrl, setWebhookCallbackUrl] = useState<string | null>(@@ -191,7 +198,7 @@ function PromptBox({ enableCopilotHandoff = false }: PromptBoxProps) {totp_identifier: totpIdentifier,max_screenshot_scrolls: maxScreenshotScrolls,publish_workflow: publishWorkflow,- run_with: "code",+ run_with: version === "v2-code" ? "code" : "agent",ai_fallback: true,extracted_information_schema: dataSchema? (() => {@@ -267,10 +274,16 @@ function PromptBox({ enableCopilotHandoff = false }: PromptBoxProps) {});const handoffWorkflowMutation = useMutation({- mutationFn: async ({ prompt }: { prompt: string }) => {+ mutationFn: async ({+ prompt,+ runWith,+ }: {+ prompt: string;+ runWith: "agent" | "code";+ }) => {const client = await getClient(credentialGetter);const yaml = convertToYAML(- buildBlankWorkflowRequest(deriveHandoffTitle(prompt)),+ buildBlankWorkflowRequest(deriveHandoffTitle(prompt), runWith),);const result = await client.post<string, { data: WorkflowApiResponse }>("/workflows",@@ -316,8 +329,9 @@ function PromptBox({ enableCopilotHandoff = false }: PromptBoxProps) {return;}submitInFlightRef.current = true;+ const runWith = runWithFromSelector(legacyVersion);if (enableCopilotHandoff) {- handoffWorkflowMutation.mutate({ prompt });+ handoffWorkflowMutation.mutate({ prompt, runWith });return;}generateWorkflowMutation.mutate({ prompt, version: legacyVersion });diff --git a/skyvern-frontend/src/routes/workflows/Workflows.tsx b/skyvern-frontend/src/routes/workflows/Workflows.tsxindex e9436e617..c39e87638 100644--- a/skyvern-frontend/src/routes/workflows/Workflows.tsx+++ b/skyvern-frontend/src/routes/workflows/Workflows.tsx@@ -113,7 +113,7 @@ const emptyWorkflowRequest: WorkflowCreateYAMLRequest = {description: "",ai_fallback: true,code_version: 2,- run_with: "code",+ run_with: "agent",workflow_definition: {version: 2,blocks: [],diff --git a/skyvern-frontend/src/routes/workflows/WorkflowsPageBanner.tsx b/skyvern-frontend/src/routes/workflows/WorkflowsPageBanner.tsxindex c585c6883..bce52b357 100644--- a/skyvern-frontend/src/routes/workflows/WorkflowsPageBanner.tsx+++ b/skyvern-frontend/src/routes/workflows/WorkflowsPageBanner.tsx@@ -9,7 +9,7 @@ const emptyWorkflowRequest: WorkflowCreateYAMLRequest = {description: "",ai_fallback: true,code_version: 2,- run_with: "code",+ run_with: "agent",workflow_definition: {version: 2,blocks: [],diff --git a/skyvern/cli/mcp_tools/__init__.py b/skyvern/cli/mcp_tools/__init__.pyindex 47173af0b..21ff28c92 100644--- a/skyvern/cli/mcp_tools/__init__.py+++ b/skyvern/cli/mcp_tools/__init__.py@@ -311,10 +311,12 @@ BAD: One giant block trying to do everything at once.- When in doubt, split into multiple 1.0 blocks (cheaper, more observable)### Caching-MCP-created workflows default to run_with="code". First run uses AI agent; subsequent runs replay \-a cached script (10-100x faster, no LLM calls). Set run_with="agent" for first-time testing, \-debugging, or when the target site redesigned. Use script tools to inspect: \-script_list_for_workflow -> script_get_code -> script_versions -> script_fallback_episodes.+MCP-created workflows default to run_with="agent". Set run_with="code" to opt into cached script \+execution: the first run still uses the AI agent (recording a script), but subsequent runs replay \+the cached script (10-100x faster, no LLM calls). For JSON definitions, code_version=2 is also \+injected by default; YAML definitions use the backend schema (currently leaves code_version unset). \+Use script tools to inspect: script_list_for_workflow -> script_get_code -> script_versions -> \+script_fallback_episodes.### Block Typesnavigation (most common), extraction, for_loop, conditional, code, text_prompt, action, goto_url, \diff --git a/skyvern/cli/mcp_tools/prompts.py b/skyvern/cli/mcp_tools/prompts.pyindex ddc13bda4..1cd443a73 100644--- a/skyvern/cli/mcp_tools/prompts.py+++ b/skyvern/cli/mcp_tools/prompts.py@@ -402,16 +402,21 @@ or what the data looks like), not the schema.## Caching Considerations-Workflows created via MCP default to Code 2.0 (code_version=2, run_with="code").+Workflows created via MCP default to AI agent execution (run_with="agent"). For JSON definitions \+code_version=2 is also injected by default; YAML definitions use the backend schema (currently \+leaves code_version unset, so pass `code_version: 2` explicitly in YAML if you want to opt into \+the v2 caching framework). Set run_with="code" on the workflow (or at run time) to opt into cached \+script execution.### What this means for workflow design-- **First run**: The AI agent runs all blocks, recording actions. A cached script is generated afterward.-- **Subsequent runs**: The script replays deterministically — 10-100x faster, no LLM costs.-- **AI fallback**: If the script encounters an element it cannot find, it falls back to the AI agent \-for that step. The fallback episode is recorded and used to improve the script.+- **run_with="agent" (default)**: Every run uses the AI agent end-to-end. Higher LLM cost but most \+flexible — recommended for workflows that are still being designed or that target sites that change often.+- **run_with="code"**: First run uses the AI agent and records a cached script; subsequent runs replay \+the script deterministically (10-100x faster, no LLM costs). If the script encounters an element it \+cannot find, it falls back to the AI agent for that step.-### Design for cacheability+### Design for cacheability (only matters when you opt into run_with="code")1. Use stable selectors: navigation goals that reference exact field labels cache better than vague \descriptions. "Fill in the 'Company Name' field" caches better than "fill in the first text box."@@ -422,11 +427,9 @@ in navigation_goal become part of the script literally.### Overriding execution mode at run time-Pass `run_with="agent"` to `skyvern_workflow_run` to force AI execution for a specific run without \-changing the workflow definition. This is useful for:-- First runs when no script exists yet (the system handles this automatically)-- Debugging: comparing AI behavior vs script behavior-- Sites that changed layout since the last successful script run+Pass `run_with="code"` to `skyvern_workflow_run` to force cached-script execution for a single run \+without changing the workflow definition (only meaningful once a script exists). Pass \+`run_with="agent"` to force AI execution for debugging or after a site redesign."""diff --git a/skyvern/cli/mcp_tools/workflow.py b/skyvern/cli/mcp_tools/workflow.pyindex 602cc92c9..7e87c1531 100644--- a/skyvern/cli/mcp_tools/workflow.py+++ b/skyvern/cli/mcp_tools/workflow.py@@ -420,7 +420,7 @@ def _validate_definition_structure(json_def: dict[str, Any] | None, action: str)_CODE_V2_DEFAULTS: dict[str, Any] = {"code_version": 2,- "run_with": "code",+ "run_with": "agent",}_DEFAULT_MCP_PROXY_LOCATION = ProxyLocation.RESIDENTIAL@@ -558,7 +558,7 @@ def _inject_missing_top_level_defaults(definition: str, fmt: str, defaults: dictdef _inject_code_v2_defaults(definition: str, fmt: str) -> str:- """Inject Code 2.0 defaults (code_version=2, run_with=code) when not explicitly set.+ """Inject Code 2.0 defaults (code_version=2, run_with=agent) when not explicitly set.Only modifies JSON definitions (or auto-detected JSON). YAML is returned unchanged."""@@ -907,7 +907,9 @@ async def skyvern_workflow_create(One block per step: "navigation" for actions, "extraction" for data. Do NOT use deprecated "task" type.Call skyvern_block_schema() for block types and schemas. Use {{parameter_key}} for input references.- Defaults to Code 2.0 (run_with="code"). Blocks share a browser session automatically.+ Defaults to AI agent execution (run_with="agent"). For JSON definitions, code_version=2 is also+ injected (YAML definitions go through the backend schema, which currently leaves code_version unset).+ Pass run_with="code" to opt into cached script execution. Blocks share a browser session automatically."""if format not in ("json", "yaml", "auto"):return make_result(diff --git a/tests/unit/test_mcp_script_caching_live.py b/tests/unit/test_mcp_script_caching_live.pyindex ce8aa1b5d..21d940df6 100644--- a/tests/unit/test_mcp_script_caching_live.py+++ b/tests/unit/test_mcp_script_caching_live.py@@ -337,7 +337,7 @@ async def test_deploy_script_via_mcp(monkeypatch):# ----------------------------------------------------------------------------# Scenario 6: Workflow create shows caching defaults+# Scenario 6: Workflow create surfaces caching fields when caller opts in# ---------------------------------------------------------------------------@@ -366,6 +366,7 @@ async def test_workflow_create_surfaces_caching_fields_via_mcp(monkeypatch):definition = json.dumps({"title": "Test",+ "run_with": "code","workflow_definition": {"parameters": [],"blocks": [diff --git a/tests/unit/test_mcp_workflow_create_defaults.py b/tests/unit/test_mcp_workflow_create_defaults.pyindex 370b0a4da..5ad502c5d 100644--- a/tests/unit/test_mcp_workflow_create_defaults.py+++ b/tests/unit/test_mcp_workflow_create_defaults.py@@ -39,7 +39,7 @@ def test_defaults_injected_when_not_specified() -> None:result = _inject_code_v2_defaults(definition, "json")parsed = json.loads(result)assert parsed["code_version"] == 2- assert parsed["run_with"] == "code"+ assert parsed["run_with"] == "agent"def test_defaults_injected_in_auto_mode() -> None:@@ -48,16 +48,16 @@ def test_defaults_injected_in_auto_mode() -> None:result = _inject_code_v2_defaults(definition, "auto")parsed = json.loads(result)assert parsed["code_version"] == 2- assert parsed["run_with"] == "code"+ assert parsed["run_with"] == "agent"def test_explicit_values_preserved() -> None:"""When the user explicitly sets these fields, their values are preserved."""- definition = _minimal_workflow_json(code_version=1, run_with="agent")+ definition = _minimal_workflow_json(code_version=1, run_with="code")result = _inject_code_v2_defaults(definition, "json")parsed = json.loads(result)assert parsed["code_version"] == 1- assert parsed["run_with"] == "agent"+ assert parsed["run_with"] == "code"def test_explicit_null_run_with_preserved() -> None: