Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Fix stale frontend lint disables (#5917)
Andrew Neilson590c5a5d1912
diff --git a/skyvern-frontend/src/components/ui/use-toast.ts b/skyvern-frontend/src/components/ui/use-toast.tsindex ed6a594d1..263f6856b 100644--- a/skyvern-frontend/src/components/ui/use-toast.ts+++ b/skyvern-frontend/src/components/ui/use-toast.ts@@ -13,13 +13,6 @@ type ToasterToast = Omit<ToastProps, "title"> & {action?: ToastActionElement;};-const actionTypes = {- ADD_TOAST: "ADD_TOAST",- UPDATE_TOAST: "UPDATE_TOAST",- DISMISS_TOAST: "DISMISS_TOAST",- REMOVE_TOAST: "REMOVE_TOAST",-} as const;-let count = 0;function genId() {@@ -27,7 +20,12 @@ function genId() {return count.toString();}-type ActionType = typeof actionTypes;+type ActionType = {+ ADD_TOAST: "ADD_TOAST";+ UPDATE_TOAST: "UPDATE_TOAST";+ DISMISS_TOAST: "DISMISS_TOAST";+ REMOVE_TOAST: "REMOVE_TOAST";+};type Action =| {diff --git a/skyvern-frontend/src/routes/workflows/hooks/useDebugSessionRunsQuery.ts b/skyvern-frontend/src/routes/workflows/hooks/useDebugSessionRunsQuery.tsindex 441dfdfaf..9f9ed1b80 100644--- a/skyvern-frontend/src/routes/workflows/hooks/useDebugSessionRunsQuery.ts+++ b/skyvern-frontend/src/routes/workflows/hooks/useDebugSessionRunsQuery.ts@@ -6,9 +6,7 @@ type Props = {debugSessionId?: string;};-const debugSessionStatuses = ["created", "completed"] as const;--type DebugSessionStatus = (typeof debugSessionStatuses)[number];+type DebugSessionStatus = "created" | "completed";interface DebugSession {debug_session_id: string;diff --git a/skyvern/constants.py b/skyvern/constants.pyindex 14f360484..7206d460a 100644--- a/skyvern/constants.py+++ b/skyvern/constants.py@@ -3,6 +3,11 @@ from pathlib import Path# This is the attribute name used to tag interactable elementsSKYVERN_ID_ATTR: str = "unique_id"++# Value sent in the x-user-agent header by the Skyvern UI. Used to distinguish UI-triggered+# runs from API/SDK callers (e.g. for trigger_type classification and routing strategy).+SKYVERN_UI_USER_AGENT: str = "skyvern-ui"+SKYVERN_DIR = Path(__file__).parentREPO_ROOT_DIR = SKYVERN_DIR.parentdiff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex 1ee719765..94d603e9a 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -2,7 +2,7 @@ import asyncioimport copyimport hashlibfrom datetime import timedelta-from typing import Any, Dict, List+from typing import TYPE_CHECKING, Any, Dict, Listimport httpximport structlog@@ -31,6 +31,9 @@ from skyvern.webeye.scraper.scraped_page import ELEMENT_NODE_ATTRIBUTES, Cleanupfrom skyvern.webeye.utils.dom import SkyvernElementfrom skyvern.webeye.utils.page import SkyvernFrame+if TYPE_CHECKING:+ from skyvern.forge.sdk.db.enums import WorkflowRunTriggerType+LOG = structlog.get_logger()_LLM_CALL_TIMEOUT_SECONDS = 30 # 30s@@ -442,6 +445,29 @@ class AgentFunction:Cloud overrides this to True and provides the Temporal-backed implementations below."""+ def get_flex_llm_key(self, llm_key: str | None) -> str | None:+ """Return a flex-tier router key for the given LLM key, or None if no flex twin exists.++ Cloud overrides this with the Gemini family → flex+GPT-5-fallback mapping.+ OSS no-op so self-hosted users without flex routers see no behavior change.+ """+ return None++ async def should_use_flex_llm_routing(+ self,+ *,+ trigger_type: "WorkflowRunTriggerType | None",+ organization_id: str,+ workflow_permanent_id: str,+ workflow_run_id: str,+ ) -> bool:+ """Decide whether a given workflow run is eligible for flex-tier LLM routing.++ Cloud overrides this to consult its experimentation provider; OSS has no flex+ routers so the default returns False.+ """+ return False+# Phrases that indicate a magic-link confirmation page meant to be closed.# Keep lowercase; matching is case-insensitive.MAGIC_LINK_CLOSE_SIGNALS: tuple[str, ...] = (diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2index aaf3e3ee5..c8507bba8 100644--- a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2@@ -151,12 +151,13 @@ IMPORTANT WORKFLOW RULES:- "wait" for explicit pauses between blocks.- "goto_url" for direct URL navigation and grounded URL-state shortcuts.* Prefer a `goto_url` URL-parameter shortcut over a click-driven `navigation` block when requested state (dates, destination, search terms, stable search params) maps to a URL that is supplied by the user, observed on the site, present in a link/form/action URL, or follows a same-site pattern visible in context. Do NOT invent website-specific paths or query parameters from memory. For URL-encoded dynamic page state, `goto_url` may bootstrap the page but must be followed by a persisted verification block before extraction: use `code` for DOM checks, `validation` for semantic/visual checks, or `navigation` when missing state must be changed through the UI. Put any follow-up actions in subsequent blocks, and verify dynamic URL-state shortcuts from the live page before extraction.-* Commit a draft workflow as soon as you have a plausible block sequence and a target URL/selector. Do NOT walk the search UI step-by-step or fetch page contents through `evaluate`/`fetch` before the first `update_and_run_blocks` call when a `goto_url` to a likely page can be tested directly. Page introspection through direct browser tools is a fallback after a block run fails or returns ambiguous evidence, not preparation for the first run.+* Commit a draft workflow as soon as you have a plausible block sequence and a target URL/selector. This same commit-early rule applies when an existing workflow draft needs a well-scoped additive edit and the user has supplied a clear condition plus action target (for example, if a condition is met, go to that URL): update the YAML and call `update_and_run_blocks` instead of answering with a prose-only block outline or asking for confirmation. Do NOT walk the search UI step-by-step or fetch page contents through `evaluate`/`fetch` before the first `update_and_run_blocks` call when a `goto_url` to a likely page can be tested directly. Page introspection through direct browser tools is a fallback after a block run fails or returns ambiguous evidence, not preparation for the first run.* Keep `navigation_goal` to ONE atomic action per block. You MUST split into separate blocks if your `navigation_goal` would cover more than one of: (a) a search-form input, (b) a date or filter selection, (c) a results-page click into a detail view, (d) a final extraction. Conjunctions like "and"/"then"/commas separating distinct UI actions inside a single `navigation_goal` are a strong signal you are bundling — decompose. The verifier checks every sub-condition after each step, so bundled goals return "continue" until the budget exhausts. When one request maps to several sub-tasks and no `goto_url` shortcut applies, decompose into one block per sub-task chained via `next_block_label`. The final stage of search → click → extract should be an `extraction` block, not another `navigation`.* Set `complete_criterion` on every decomposed `navigation` block to the observable post-action page state — without it, smaller blocks still return vague "continue" verdicts.* Use descriptive, unique labels for blocks (snake_case format).* Reference parameters using Jinja2 syntax: {% raw %}{{ parameters.param_key }}{% endraw %}* When a downstream block (text_prompt, navigation, validation, send_email, etc.) consumes an upstream `extraction` block's output, reference the specific sub-field under `output.extracted_information` (e.g. {% raw %}`{{ extract_article.output.extracted_information.article_text }}`{% endraw %}), NOT the bare {% raw %}`{{ extract_article.output }}`{% endraw %} or {% raw %}`{{ extract_article.output.extracted_information }}`{% endraw %}. Bare references stringify the whole dict and feed a JSON dump to the consumer, which then emits a placeholder summary instead of acting on the value.+* For conditional branches that depend on prior extraction output, page state, or a plain-language user condition, prefer `criteria_type: prompt` with a natural-language `expression`. Do NOT write pure Jinja such as {% raw %}`{{ inspect_table.output.extracted_information.has_match == false }}`{% endraw %} unless you are certain the exact output parameter key is available in the workflow context. Prompt criteria receive a safe snapshot of prior extraction results and avoid brittle label/output-key mismatches.* Inline literal values directly in block config when the value is non-sensitive, used once, and not meant to be a reusable runtime input. Example: hardcode a specific URL or a one-off search term in the block's navigation_goal or data_extraction_goal instead of creating a workflow parameter for it.* Introduce a top-level workflow parameter ONLY when the value is: reused across multiple blocks, credential/secret-like, a structured JSON or file_url input, or clearly intended to remain configurable across runs.* For ANY parameter you DO introduce, the workflow YAML MUST contain a matching top-level parameter definition under `workflow_definition.parameters` with the same `key` — the block's `{% raw %}{{ parameters.param_key }}{% endraw %}` references resolve against that list. Mismatches cause a PARAMETER_BINDING_ERROR at runtime.diff --git a/skyvern/forge/sdk/api/llm/api_handler_factory.py b/skyvern/forge/sdk/api/llm/api_handler_factory.pyindex d53c87ba5..f6d96ed28 100644--- a/skyvern/forge/sdk/api/llm/api_handler_factory.py+++ b/skyvern/forge/sdk/api/llm/api_handler_factory.py@@ -567,9 +567,88 @@ class LLMAPIHandlerFactory:and settings.OPENAI_COMPATIBLE_GITHUB_COPILOT_DOMAIN in settings.OPENAI_COMPATIBLE_API_BASE)+ @staticmethod+ def _maybe_get_flex_handler(default: LLMAPIHandler) -> LLMAPIHandler | None:+ """Return a flex-tier handler if context says we should flex-route the given default,+ or None to indicate the caller should use the default handler unchanged.++ Centralizes the flex routing decision so both `get_override_llm_api_handler`+ (override-aware callers) and `wrap_for_flex_routing` (direct-caller protection+ for `app.LLM_API_HANDLER` etc.) consult the same logic and tag the same span.+ """+ ctx = skyvern_context.current()+ if ctx is None or not ctx.use_flex_llm_routing:+ return None+ # Cached handlers carry .llm_key (set in get_llm_api_handler /+ # get_llm_api_handler_with_router). For LLMCaller-backed handlers (openrouter,+ # GitHub Copilot via OPENAI_COMPATIBLE) the returned handler is `llm_caller.call`+ # — a bound method whose .__self__ is the LLMCaller instance carrying .llm_key.+ # Fall back to settings.LLM_KEY for stub handlers (e.g. dummy_llm_api_handler).+ effective_key = (+ getattr(default, "llm_key", None)+ or getattr(getattr(default, "__self__", None), "llm_key", None)+ or settings.LLM_KEY+ )+ flex_key = app.AGENT_FUNCTION.get_flex_llm_key(effective_key)+ # is_registered() check makes the gate a clean no-op on deploys where flex routers+ # weren't registered (e.g. ENABLE_AZURE_GPT5=false). Without it every eligible call+ # would log a warning and pay the cost of an exception just to fall through.+ if not flex_key or not LLMConfigRegistry.is_registered(flex_key):+ return None+ try:+ flex_handler = LLMAPIHandlerFactory.get_llm_api_handler(flex_key)+ # get_current_span() returns a NonRecordingSpan when no span is active;+ # set_attribute is a no-op on that, so no None check needed.+ span = otel_trace.get_current_span()+ span.set_attribute("flex_routing_applied", True)+ span.set_attribute("flex_routing_resolved_key", flex_key)+ return flex_handler+ except Exception:+ LOG.warning(+ "Failed to get flex LLM API handler, falling back to non-flex resolution.",+ flex_key=flex_key,+ effective_key=effective_key,+ exc_info=True,+ )+ return None++ @staticmethod+ def wrap_for_flex_routing(handler: LLMAPIHandler) -> LLMAPIHandler:+ """Wrap a default LLM handler so it applies flex routing when context says so.++ Use this for handlers stored on `app.*` that direct callers might invoke without+ going through get_override_llm_api_handler (e.g. task_v2_service uses+ `await app.LLM_API_HANDLER(...)` directly for metadata/summary calls). The+ wrapper preserves .llm_key so other code that introspects handlers still works.+ """++ async def flex_aware_handler(*args: Any, **kwargs: Any) -> Any:+ flex_handler = LLMAPIHandlerFactory._maybe_get_flex_handler(handler)+ target = flex_handler if flex_handler is not None else handler+ return await target(*args, **kwargs)++ # Preserve .llm_key on the wrapper so introspection (incl. _maybe_get_flex_handler+ # and observability tags) still finds the underlying default's key. For bound-method+ # handlers (LLMCaller.call from openrouter / OPENAI_COMPATIBLE paths), the key lives+ # on __self__ rather than the bound method itself — surface it directly so downstream+ # _maybe_get_flex_handler doesn't fall through to settings.LLM_KEY (which could route+ # the call to the wrong model family).+ flex_aware_handler.llm_key = ( # type: ignore[attr-defined]+ getattr(handler, "llm_key", None) or getattr(getattr(handler, "__self__", None), "llm_key", None)+ )+ return flex_aware_handler+@staticmethoddef get_override_llm_api_handler(override_llm_key: str | None, *, default: LLMAPIHandler) -> LLMAPIHandler:- if not override_llm_key:+ # Cloud flex routing applies only on the default-handler path (no explicit override).+ # Block/task-level `llm_key` overrides represent a deliberate caller choice — including+ # the GPT-4.1 fallback variants — and the existing contract on this method (see comment+ # below) is that explicit overrides honor the exact model choice. We respect that.+ # Flex routing is treated as default-path tier optimization, not a model rewriter.+ if override_llm_key is None:+ flex_handler = LLMAPIHandlerFactory._maybe_get_flex_handler(default)+ if flex_handler is not None:+ return flex_handlerreturn defaulttry:# Explicit overrides should honor the exact model choice and skip experimentation reroutes.@@ -591,17 +670,21 @@ class LLMAPIHandlerFactory:if not isinstance(llm_config, LLMRouterConfig):raise InvalidLLMConfigError(llm_key)+ fallback_groups: list[str]+ if not llm_config.fallback_model_group:+ fallback_groups = []+ elif isinstance(llm_config.fallback_model_group, str):+ fallback_groups = [llm_config.fallback_model_group]+ else:+ fallback_groups = list(llm_config.fallback_model_group)+router = litellm.Router(model_list=[dataclasses.asdict(model) for model in llm_config.model_list],redis_host=llm_config.redis_host,redis_port=llm_config.redis_port,redis_password=llm_config.redis_password,routing_strategy=llm_config.routing_strategy,- fallbacks=(- [{llm_config.main_model_group: [llm_config.fallback_model_group]}]- if llm_config.fallback_model_group- else []- ),+ fallbacks=([{llm_config.main_model_group: fallback_groups}] if fallback_groups else []),num_retries=llm_config.num_retries,retry_after=llm_config.retry_delay_seconds,disable_cooldowns=llm_config.disable_cooldowns,diff --git a/skyvern/forge/sdk/api/llm/config_registry.py b/skyvern/forge/sdk/api/llm/config_registry.pyindex 2b084670e..9fe9e6ea2 100644--- a/skyvern/forge/sdk/api/llm/config_registry.py+++ b/skyvern/forge/sdk/api/llm/config_registry.py@@ -18,6 +18,11 @@ class LLMConfigRegistry:def is_router_config(llm_key: str) -> bool:return isinstance(LLMConfigRegistry.get_config(llm_key), LLMRouterConfig)+ @classmethod+ def is_registered(cls, llm_key: str) -> bool:+ """True if `llm_key` has been explicitly registered (no synthesis fallbacks)."""+ return llm_key in cls._configs+@staticmethoddef validate_config(llm_key: str, config: LLMRouterConfig | LLMConfig) -> None:missing_env_vars = config.get_missing_env_vars()diff --git a/skyvern/forge/sdk/core/skyvern_context.py b/skyvern/forge/sdk/core/skyvern_context.pyindex c8a4c8387..83952ad6d 100644--- a/skyvern/forge/sdk/core/skyvern_context.py+++ b/skyvern/forge/sdk/core/skyvern_context.py@@ -13,6 +13,8 @@ from skyvern.config import settingsif TYPE_CHECKING:from playwright.async_api import Frame, Page+ from skyvern.forge.sdk.db.enums import WorkflowRunTriggerType+LOG = structlog.get_logger()# Cap on entries kept in `recent_dialog_messages` so a chatty page (e.g. validation@@ -72,6 +74,15 @@ class SkyvernContext:enable_speed_optimizations: bool = Falseuse_artifact_bundling: bool = False+ # Trigger type of the enclosing workflow run (manual/api/scheduled/webhook).+ # Routed through SkyvernContext so non-API entry points (workers, scripts) can populate it+ # without taking a dependency on the public-API request shape.+ trigger_type: WorkflowRunTriggerType | None = None+ # When true, downstream LLM handler selection may swap the resolved handler to a+ # flex-tier router. Cloud sets this at run boot via a PostHog flag for non-UI runs;+ # OSS keeps it False because OSS has no flex routers registered.+ use_flex_llm_routing: bool = False+# script run contextcode_version: int | None = Nonescript_id: str | None = Nonediff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.pyindex c2c07d367..10eae9afd 100644--- a/skyvern/forge/sdk/routes/agent_protocol.py+++ b/skyvern/forge/sdk/routes/agent_protocol.py@@ -29,6 +29,7 @@ from skyvern import analyticsfrom skyvern._version import __version__from skyvern.analytics import get_oss_versionfrom skyvern.config import settings+from skyvern.constants import SKYVERN_UI_USER_AGENTfrom skyvern.exceptions import (MissingBrowserAddressError,SkyvernHTTPException,@@ -303,6 +304,9 @@ async def run_task()if run_request.engine == RunEngine.skyvern_v2:# create task v2+ v2_trigger_type = (+ WorkflowRunTriggerType.manual if x_user_agent == SKYVERN_UI_USER_AGENT else WorkflowRunTriggerType.api+ )try:task_v2 = await task_v2_service.initialize_task_v2(organization=current_org,@@ -312,6 +316,7 @@ async def run_task(totp_verification_url=run_request.totp_url,webhook_callback_url=run_request.webhook_url,proxy_location=run_request.proxy_location,+ trigger_type=v2_trigger_type,publish_workflow=run_request.publish_workflow,extracted_information_schema=run_request.data_extraction_schema,error_code_mapping=run_request.error_code_mapping,@@ -1856,6 +1861,7 @@ async def run_block(user_id: str = Depends(org_auth_service.get_current_user_id),template: bool = Query(False),x_api_key: Annotated[str | None, Header()] = None,+ x_user_agent: Annotated[str | None, Header()] = None,) -> BlockRunResponse:"""Kick off the execution of one or more blocks in a workflow. Returns the@@ -1875,11 +1881,15 @@ async def run_block(block_labels=block_run_request.block_labels,)+ block_trigger_type = (+ WorkflowRunTriggerType.manual if x_user_agent == SKYVERN_UI_USER_AGENT else WorkflowRunTriggerType.api+ )workflow_run = await block_service.ensure_workflow_run(organization=organization,template=template,workflow_permanent_id=block_run_request.workflow_id,block_run_request=block_run_request,+ trigger_type=block_trigger_type,)browser_session_id = block_run_request.browser_session_id@@ -3432,6 +3442,7 @@ async def run_task_v2(organization: Organization = Depends(org_auth_service.get_current_org),x_max_iterations_override: Annotated[int | str | None, Header()] = None,x_max_steps_override: Annotated[int | str | None, Header()] = None,+ x_user_agent: Annotated[str | None, Header()] = None,) -> dict[str, Any]:if x_max_iterations_override or x_max_steps_override:LOG.info(@@ -3442,6 +3453,9 @@ async def run_task_v2(await PermissionCheckerFactory.get_instance().check(organization, browser_session_id=data.browser_session_id)await app.RATE_LIMITER.rate_limit_submit_run(organization.organization_id)+ legacy_v2_trigger_type = (+ WorkflowRunTriggerType.manual if x_user_agent == SKYVERN_UI_USER_AGENT else WorkflowRunTriggerType.api+ )try:task_v2 = await task_v2_service.initialize_task_v2(organization=organization,@@ -3459,6 +3473,7 @@ async def run_task_v2(browser_session_id=data.browser_session_id,extra_http_headers=data.extra_http_headers,browser_address=data.browser_address,+ trigger_type=legacy_v2_trigger_type,)except MissingBrowserAddressError as e:raise HTTPException(status_code=400, detail=str(e)) from ediff --git a/skyvern/forge/sdk/routes/credentials.py b/skyvern/forge/sdk/routes/credentials.pyindex 129c1ad41..72e2a14be 100644--- a/skyvern/forge/sdk/routes/credentials.py+++ b/skyvern/forge/sdk/routes/credentials.py@@ -37,7 +37,7 @@ from skyvern.exceptions import HttpException as SkyvernHttpExceptionfrom skyvern.exceptions import SkyvernHTTPExceptionfrom skyvern.forge import appfrom skyvern.forge.sdk.core.aiohttp_helper import aiohttp_request-from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType+from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType, WorkflowRunTriggerTypefrom skyvern.forge.sdk.executor.factory import AsyncExecutorFactoryfrom skyvern.forge.sdk.routes.code_samples import (CREATE_CREDENTIAL_CODE_SAMPLE_CREDIT_CARD_PYTHON,@@ -568,6 +568,7 @@ async def test_login(workflow_permanent_id=workflow.workflow_permanent_id,organization=current_org,max_steps_override=None,+ trigger_type=WorkflowRunTriggerType.api,)await AsyncExecutorFactory.get_executor().execute_workflow(@@ -759,6 +760,7 @@ async def test_credential(workflow_permanent_id=workflow.workflow_permanent_id,organization=current_org,max_steps_override=None,+ trigger_type=WorkflowRunTriggerType.api,)await AsyncExecutorFactory.get_executor().execute_workflow(diff --git a/skyvern/forge/sdk/routes/run_blocks.py b/skyvern/forge/sdk/routes/run_blocks.pyindex dce664707..22b8714cf 100644--- a/skyvern/forge/sdk/routes/run_blocks.py+++ b/skyvern/forge/sdk/routes/run_blocks.py@@ -4,10 +4,11 @@ import structlogfrom fastapi import BackgroundTasks, Depends, Header, HTTPException, Requestfrom skyvern.config import settings-from skyvern.constants import DEFAULT_LOGIN_PROMPT+from skyvern.constants import DEFAULT_LOGIN_PROMPT, SKYVERN_UI_USER_AGENTfrom skyvern.exceptions import MissingBrowserAddressErrorfrom skyvern.forge import appfrom skyvern.forge.sdk.core import skyvern_context+from skyvern.forge.sdk.db.enums import WorkflowRunTriggerTypefrom skyvern.forge.sdk.routes.code_samples import (DOWNLOAD_FILES_CODE_SAMPLE_PYTHON,DOWNLOAD_FILES_CODE_SAMPLE_TS,@@ -62,6 +63,7 @@ async def _run_workflow_and_build_response(totp_verification_url: str | None,totp_identifier: str | None,x_api_key: str | None,+ x_user_agent: str | None = None,) -> WorkflowRunResponse:context = skyvern_context.ensure_context()request_id = context.request_id@@ -77,6 +79,9 @@ async def _run_workflow_and_build_response(extra_http_headers=run_block_request.extra_http_headers,)+ trigger_type = (+ WorkflowRunTriggerType.manual if x_user_agent == SKYVERN_UI_USER_AGENT else WorkflowRunTriggerType.api+ )try:workflow_run = await workflow_service.run_workflow(workflow_id=workflow_id,@@ -88,6 +93,7 @@ async def _run_workflow_and_build_response(request_id=request_id,request=request,background_tasks=background_tasks,+ trigger_type=trigger_type,)except MissingBrowserAddressError as e:raise HTTPException(status_code=400, detail=str(e)) from e@@ -144,6 +150,7 @@ async def login(login_request: LoginRequest,organization: Organization = Depends(org_auth_service.get_current_org),x_api_key: Annotated[str | None, Header()] = None,+ x_user_agent: Annotated[str | None, Header()] = None,) -> WorkflowRunResponse:url = _validate_url(login_request.url)totp_verification_url = _validate_url(login_request.totp_url)@@ -277,6 +284,7 @@ async def login(totp_verification_url=totp_verification_url,totp_identifier=resolved_totp_identifier,x_api_key=x_api_key,+ x_user_agent=x_user_agent,)@@ -304,6 +312,7 @@ async def download_files(download_files_request: DownloadFilesRequest,organization: Organization = Depends(org_auth_service.get_current_org),x_api_key: Annotated[str | None, Header()] = None,+ x_user_agent: Annotated[str | None, Header()] = None,) -> WorkflowRunResponse:url = _validate_url(download_files_request.url)totp_verification_url = _validate_url(download_files_request.totp_url)@@ -366,4 +375,5 @@ async def download_files(totp_verification_url=totp_verification_url,totp_identifier=download_files_request.totp_identifier,x_api_key=x_api_key,+ x_user_agent=x_user_agent,)diff --git a/skyvern/forge/sdk/routes/sdk.py b/skyvern/forge/sdk/routes/sdk.pyindex ba87e8bf8..be1081a79 100644--- a/skyvern/forge/sdk/routes/sdk.py+++ b/skyvern/forge/sdk/routes/sdk.py@@ -10,6 +10,7 @@ from skyvern.forge import appfrom skyvern.forge.sdk.api.files import validate_download_urlfrom skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.core.skyvern_context import SkyvernContext+from skyvern.forge.sdk.db.enums import WorkflowRunTriggerTypefrom skyvern.forge.sdk.routes.routers import base_routerfrom skyvern.forge.sdk.schemas.organizations import Organizationfrom skyvern.forge.sdk.schemas.sdk_actions import (@@ -90,6 +91,7 @@ async def run_sdk_action(workflow_permanent_id=workflow.workflow_permanent_id,organization=organization,version=None,+ trigger_type=WorkflowRunTriggerType.api,)workflow_run = await app.DATABASE.workflow_runs.update_workflow_run(workflow_run_id=workflow_run.workflow_run_id,diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.pyindex defc4379b..fcb363618 100644--- a/skyvern/forge/sdk/workflow/models/block.py+++ b/skyvern/forge/sdk/workflow/models/block.py@@ -5707,6 +5707,9 @@ class TaskV2Block(Block):)loop_internal_state = copy.deepcopy(current_context.loop_internal_state) if current_context else Nonetry:+ # TaskV2Block child runs inherit the parent run's trigger_type so non-UI parents+ # don't silently drop flex-routing eligibility for their TaskV2 children.+ inherited_v2_trigger_type = current_context.trigger_type if current_context else Nonetask_v2 = await task_v2_service.initialize_task_v2(organization=organization,user_prompt=resolved_prompt,@@ -5717,6 +5720,7 @@ class TaskV2Block(Block):totp_verification_url=resolved_totp_verification_url,max_screenshot_scrolling_times=workflow_run.max_screenshot_scrolls,workflow_system_prompt=self.workflow_system_prompt,+ trigger_type=inherited_v2_trigger_type,)await app.DATABASE.observer.update_task_v2(task_v2.observer_cruise_id, status=TaskV2Status.queued, organization_id=organization_id@@ -8001,11 +8005,13 @@ class WorkflowTriggerBlock(Block):# setup_workflow_run() can replace the current context without# flushing the parent's pending workflow_feature_flags summary.parent_context = skyvern_context.current()+ inherited_trigger_type = parent_context.trigger_type if parent_context else Nonewith skyvern_context.scoped(skyvern_context.SkyvernContext(run_id=parent_context.run_id if parent_context else None,root_workflow_run_id=parent_context.root_workflow_run_id if parent_context else None,copilot_session_id=parent_context.copilot_session_id if parent_context else None,+ trigger_type=inherited_trigger_type,)):try:@@ -8016,6 +8022,7 @@ class WorkflowTriggerBlock(Block):organization=organization,parent_workflow_run_id=workflow_run_id,ignore_inherited_workflow_system_prompt=self.ignore_workflow_system_prompt,+ trigger_type=inherited_trigger_type,)except Exception as e:error_msg = get_user_facing_exception_message(e)@@ -8107,6 +8114,8 @@ class WorkflowTriggerBlock(Block):# separately; the worker reads it back from the DB inside# ``execute_workflow``. Symmetric with the sync branch above# — the flag is written once, at spawn time, for both paths.+ async_parent_context = skyvern_context.current()+ async_inherited_trigger_type = async_parent_context.trigger_type if async_parent_context else Nonetriggered_workflow_run = await run_workflow(workflow_id=resolved_workflow_permanent_id,organization=organization,@@ -8115,6 +8124,7 @@ class WorkflowTriggerBlock(Block):background_tasks=None,parent_workflow_run_id=workflow_run_id,ignore_inherited_workflow_system_prompt=self.ignore_workflow_system_prompt,+ trigger_type=async_inherited_trigger_type,)except Exception as e:error_msg = get_user_facing_exception_message(e)diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex 0c457cd8f..a527bb8f2 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -884,6 +884,7 @@ class WorkflowService:max_screenshot_scrolls=workflow_request.max_screenshot_scrolls,loop_internal_state=copy.deepcopy(context.loop_internal_state) if context else None,copilot_session_id=resolved_copilot_session_id,+ trigger_type=trigger_type,))@@ -907,6 +908,17 @@ class WorkflowService:LOG.warning("Failed to check USE_ARTIFACT_BUNDLING flag for workflow", exc_info=True)new_context.use_artifact_bundling = False+ # Resolve flex routing eligibility once per run boot. Site B+ # (scripts/run_workflow.py) re-resolves in the Temporal worker — both go+ # through the same AgentFunction hook so the cloud side is the single+ # owner of the flag name and property shape.+ new_context.use_flex_llm_routing = await app.AGENT_FUNCTION.should_use_flex_llm_routing(+ trigger_type=trigger_type,+ organization_id=organization.organization_id,+ workflow_permanent_id=workflow_run.workflow_permanent_id,+ workflow_run_id=workflow_run.workflow_run_id,+ )+# Create all the workflow run parameters, AWSSecretParameter won't have workflow run parameters created.all_workflow_parameters = await self.get_workflow_parameters(workflow_id=workflow.workflow_id)try:diff --git a/skyvern/schemas/llm.py b/skyvern/schemas/llm.pyindex 05f813858..e3a01cd24 100644--- a/skyvern/schemas/llm.py+++ b/skyvern/schemas/llm.py@@ -126,7 +126,7 @@ class LLMRouterConfig(LLMConfigBase):redis_host: str | None = Noneredis_port: int | None = Noneredis_password: str | None = None- fallback_model_group: str | None = None+ fallback_model_group: str | list[str] | None = Nonerouting_strategy: Literal["simple-shuffle","least-busy",diff --git a/skyvern/services/block_service.py b/skyvern/services/block_service.pyindex 83f616563..67b95a0ed 100644--- a/skyvern/services/block_service.py+++ b/skyvern/services/block_service.py@@ -6,6 +6,7 @@ from fastapi import BackgroundTasks, Requestfrom skyvern.exceptions import OutputParameterNotFound, WorkflowNotFoundfrom skyvern.forge import appfrom skyvern.forge.sdk.core import skyvern_context+from skyvern.forge.sdk.db.enums import WorkflowRunTriggerTypefrom skyvern.forge.sdk.executor.factory import AsyncExecutorFactoryfrom skyvern.forge.sdk.schemas.organizations import Organizationfrom skyvern.forge.sdk.workflow.models.parameter import OutputParameter@@ -44,6 +45,7 @@ async def ensure_workflow_run(workflow_permanent_id: str,block_run_request: BlockRunRequest,x_max_steps_override: int | None = None,+ trigger_type: WorkflowRunTriggerType | None = None,) -> WorkflowRun:context = skyvern_context.ensure_context()@@ -69,6 +71,7 @@ async def ensure_workflow_run(request_id=context.request_id,debug_session_id=block_run_request.debug_session_id,code_gen=block_run_request.code_gen,+ trigger_type=trigger_type,)return workflow_rundiff --git a/skyvern/services/task_v2_service.py b/skyvern/services/task_v2_service.pyindex f1aa5a8ed..1c275da1b 100644--- a/skyvern/services/task_v2_service.py+++ b/skyvern/services/task_v2_service.py@@ -26,7 +26,7 @@ from skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.core.hashing import generate_url_hashfrom skyvern.forge.sdk.core.security import generate_skyvern_webhook_signaturefrom skyvern.forge.sdk.core.skyvern_context import SkyvernContext-from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType+from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType, WorkflowRunTriggerTypefrom skyvern.forge.sdk.schemas.organizations import Organizationfrom skyvern.forge.sdk.schemas.task_v2 import TaskV2, TaskV2Metadata, TaskV2Status, ThoughtScenario, ThoughtTypefrom skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunTimeline, WorkflowRunTimelineType@@ -261,6 +261,7 @@ async def initialize_task_v2(extra_http_headers: dict[str, str] | None = None,browser_address: str | None = None,run_with: str | None = None,+ trigger_type: WorkflowRunTriggerType | None = None,) -> TaskV2:task_v2 = await app.DATABASE.observer.create_task_v2(prompt=user_prompt,@@ -313,6 +314,7 @@ async def initialize_task_v2(version=None,max_steps_override=max_steps_override,parent_workflow_run_id=parent_workflow_run_id,+ trigger_type=trigger_type,)except Exception:LOG.error("Failed to setup cruise workflow run", exc_info=True)@@ -484,6 +486,9 @@ async def run_task_v2(workflow, workflow_run = None, Noneparent_context = skyvern_context.current()current_run_id = parent_context.run_id if parent_context and parent_context.run_id else task_v2_id+ # Carry trigger_type + use_flex_llm_routing forward from the parent context (set in+ # scripts/run_task_v2.py at worker boot) so flex routing eligibility persists into the+ # scoped TaskV2 execution context.context = SkyvernContext(organization_id=organization_id,organization_name=organization.organization_name,@@ -493,6 +498,8 @@ async def run_task_v2(request_id=request_id,browser_session_id=browser_session_id,loop_internal_state=copy.deepcopy(parent_context.loop_internal_state) if parent_context else None,+ trigger_type=parent_context.trigger_type if parent_context else None,+ use_flex_llm_routing=parent_context.use_flex_llm_routing if parent_context else False,)# SKY-7005: scoped() restores the parent context on exit, preserving# loop_internal_state so per-iteration download filtering continues todiff --git a/tests/unit/test_workflow_copilot_prompt_injection.py b/tests/unit/test_workflow_copilot_prompt_injection.pyindex 524a5ca3d..054f5d8c1 100644--- a/tests/unit/test_workflow_copilot_prompt_injection.py+++ b/tests/unit/test_workflow_copilot_prompt_injection.py@@ -72,6 +72,23 @@ class TestAgentTemplateCorrectionRules:assert "Labels become output keys" in renderedassert "Jinja block reference" in rendered+ def test_agent_template_extends_commit_early_to_additive_edits(self) -> None:+ rendered = prompt_engine.load_prompt("workflow-copilot-agent", **_AGENT_TEMPLATE_DEFAULTS)++ assert "existing workflow draft needs a well-scoped additive edit" in rendered+ assert "clear condition plus action target" in rendered+ assert "update_and_run_blocks" in rendered+ assert "prose-only block outline" in rendered++ def test_agent_template_prefers_prompt_criteria_for_extraction_conditionals(self) -> None:+ rendered = prompt_engine.load_prompt("workflow-copilot-agent", **_AGENT_TEMPLATE_DEFAULTS)++ assert "conditional branches that depend on prior extraction output" in rendered+ assert "criteria_type: prompt" in rendered+ assert "Do NOT write pure Jinja" in rendered+ assert "inspect_table.output.extracted_information.has_match" in rendered+ assert "safe snapshot of prior extraction results" in rendered+class TestUserTemplateCodeFencing:"""Verify untrusted variables are wrapped in code fences."""diff --git a/tests/unit/test_workflow_run_parameter_batching.py b/tests/unit/test_workflow_run_parameter_batching.pyindex 89c2a3c27..c446c715f 100644--- a/tests/unit/test_workflow_run_parameter_batching.py+++ b/tests/unit/test_workflow_run_parameter_batching.py@@ -97,6 +97,8 @@ async def test_setup_workflow_run_raises_on_missing_required_parameters() -> Nonwith patch("skyvern.forge.sdk.workflow.service.app") as mock_app:mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)+ mock_app.AGENT_FUNCTION.should_use_flex_llm_routing = AsyncMock(return_value=False)+with pytest.raises(MissingValueForParameter):await service.setup_workflow_run(request_id="req_test",@@ -140,6 +142,8 @@ async def test_setup_workflow_run_persistence_error_identifies_specific_failing_with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)+ mock_app.AGENT_FUNCTION.should_use_flex_llm_routing = AsyncMock(return_value=False)+with pytest.raises(WorkflowRunParameterPersistenceError) as exc_info:await service.setup_workflow_run(request_id="req_test",@@ -170,6 +174,8 @@ async def test_setup_workflow_run_raises_on_non_string_credential_id() -> None:with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)+ mock_app.AGENT_FUNCTION.should_use_flex_llm_routing = AsyncMock(return_value=False)+with pytest.raises(InvalidCredentialId):await service.setup_workflow_run(request_id="req_test",@@ -198,6 +204,8 @@ async def test_setup_workflow_run_batches_credential_validation() -> None:with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)++ mock_app.AGENT_FUNCTION.should_use_flex_llm_routing = AsyncMock(return_value=False)mock_app.DATABASE.credentials.get_credentials_by_ids = AsyncMock(return_value=[SimpleNamespace(credential_id=f"cred_id_{i}") for i in range(3)])@@ -227,6 +235,8 @@ async def test_setup_workflow_run_skips_credential_lookup_when_no_credentials()with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)++ mock_app.AGENT_FUNCTION.should_use_flex_llm_routing = AsyncMock(return_value=False)mock_app.DATABASE.credentials.get_credentials_by_ids = AsyncMock(return_value=[])await service.setup_workflow_run(@@ -253,6 +263,8 @@ async def test_setup_workflow_run_raises_invalid_credential_when_missing() -> Nowith patch("skyvern.forge.sdk.workflow.service.app") as mock_app:mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)++ mock_app.AGENT_FUNCTION.should_use_flex_llm_routing = AsyncMock(return_value=False)mock_app.DATABASE.credentials.get_credentials_by_ids = AsyncMock(return_value=[])with pytest.raises(InvalidCredentialId) as exc_info:@@ -283,6 +295,8 @@ async def test_setup_workflow_run_surfaces_all_missing_credentials() -> None:with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)++ mock_app.AGENT_FUNCTION.should_use_flex_llm_routing = AsyncMock(return_value=False)# Only cred_id_0 exists; cred_id_1 and cred_id_2 are missing.mock_app.DATABASE.credentials.get_credentials_by_ids = AsyncMock(return_value=[SimpleNamespace(credential_id="cred_id_0")]@@ -319,6 +333,8 @@ async def test_setup_workflow_run_dedupes_repeated_credential_ids() -> None:with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)++ mock_app.AGENT_FUNCTION.should_use_flex_llm_routing = AsyncMock(return_value=False)mock_app.DATABASE.credentials.get_credentials_by_ids = AsyncMock(return_value=[SimpleNamespace(credential_id="cred_shared")])@@ -353,6 +369,8 @@ async def test_setup_workflow_run_preserves_parent_loop_state_when_replacing_conwith patch("skyvern.forge.sdk.workflow.service.app") as mock_app:mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)+ mock_app.AGENT_FUNCTION.should_use_flex_llm_routing = AsyncMock(return_value=False)+await service.setup_workflow_run(request_id="req_test",workflow_request=WorkflowRequestBody(data={}),@@ -393,6 +411,8 @@ async def test_setup_workflow_run_opens_one_outer_session() -> None:request = WorkflowRequestBody(data={"k": "v"})with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)++ mock_app.AGENT_FUNCTION.should_use_flex_llm_routing = AsyncMock(return_value=False)mock_app.DATABASE.workflow_runs.Session = lambda: _Counter()await service.setup_workflow_run(request_id="req_test",@@ -446,6 +466,8 @@ async def test_setup_workflow_run_rolls_back_outer_session_on_batch_failure() ->request = WorkflowRequestBody(data={"a": "1", "b": "2"})with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)++ mock_app.AGENT_FUNCTION.should_use_flex_llm_routing = AsyncMock(return_value=False)mock_app.DATABASE.workflow_runs.Session = lambda: _Session()await service.setup_workflow_run(request_id="req_test",