Skip to content

Automate browser based workflows with AI

Add user-selectable browser type for workflows and runs (backend) (#8550)

LawyZheng3135143fc367
diff --git a/alembic/versions/2026_09_15_0950-de8067e9e60c_add_browser_type_to_workflows_and_workflow_runs.py b/alembic/versions/2026_09_15_0950-de8067e9e60c_add_browser_type_to_workflows_and_workflow_runs.py
new file mode 100644
index 000000000..1babce2b7
--- /dev/null
+++ b/alembic/versions/2026_09_15_0950-de8067e9e60c_add_browser_type_to_workflows_and_workflow_runs.py
@@ -0,0 +1,31 @@
+"""add browser type to workflows and workflow runs
+
+Revision ID: de8067e9e60c
+Revises: f57aeaae936b
+Create Date: 2026-09-15T09:50:10.055078+00:00
+
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = "de8067e9e60c"
+down_revision: Union[str, None] = "f57aeaae936b"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.execute("SET LOCAL lock_timeout = '5s'")
+ op.add_column("workflow_runs", sa.Column("browser_type", sa.String(), nullable=True))
+ op.add_column("workflows", sa.Column("browser_type", sa.String(), nullable=True))
+
+
+def downgrade() -> None:
+ op.execute("SET LOCAL lock_timeout = '5s'")
+ op.drop_column("workflow_runs", "browser_type")
+ op.drop_column("workflows", "browser_type")
diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.json
index 46bbda3b0..fe5e4cd5c 100644
--- a/docs/api-reference/openapi.json
+++ b/docs/api-reference/openapi.json
@@ -1390,6 +1390,63 @@
"x-fern-sdk-method-name": "delete_folder"
}
},
+ "/v1/browser_types": {
+ "get": {
+ "tags": [
+ "Server"
+ ],
+ "summary": "List selectable browser types",
+ "description": "List the selectable browser engines for the workflow/run browser_type setting. The list is runtime-capability aware: a runtime that can honor an explicit engine (the cloud dynamic-browser capability) returns all supported engines, while a runtime without it (OSS/self-host) returns an empty list rather than advertising selections the server would reject.",
+ "operationId": "get_browser_types_v1_browser_types_get",
+ "parameters": [
+ {
+ "name": "x-api-key",
+ "in": "header",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings.",
+ "title": "X-Api-Key"
+ },
+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings."
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successfully listed selectable browser types",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/BrowserTypeOption"
+ },
+ "title": "Response Get Browser Types V1 Browser Types Get"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ },
+ "x-fern-sdk-method-name": "get_browser_types"
+ }
+ },
"/v1/runs/{workflow_run_id}/tags": {
"post": {
"tags": [
@@ -10914,6 +10971,24 @@
"title": "BrowserSessionResponse",
"description": "Response model for browser session information."
},
+ "BrowserTypeOption": {
+ "properties": {
+ "value": {
+ "type": "string",
+ "title": "Value"
+ },
+ "label": {
+ "type": "string",
+ "title": "Label"
+ }
+ },
+ "type": "object",
+ "required": [
+ "value",
+ "label"
+ ],
+ "title": "BrowserTypeOption"
+ },
"BulkCancelRunsRequest": {
"properties": {
"run_ids": {
@@ -28438,6 +28513,17 @@
"title": "Run With",
"default": "agent"
},
+ "browser_type": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Browser Type"
+ },
"ai_fallback": {
"type": "boolean",
"title": "Ai Fallback",
@@ -28805,6 +28891,18 @@
"title": "Run With",
"default": "agent"
},
+ "browser_type": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Browser Type",
+ "description": "Browser engine for runs of this workflow, one of the supported browser types (e.g. msedge, chrome, stealth-chromium). A workflow-run setting overrides this. Null means the system default."
+ },
"ai_fallback": {
"type": "boolean",
"title": "Ai Fallback",
@@ -29910,6 +30008,17 @@
],
"title": "Run With"
},
+ "browser_type": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Browser Type"
+ },
"script_run": {
"anyOf": [
{
@@ -30835,6 +30944,21 @@
"code"
]
},
+ "browser_type": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Browser Type",
+ "description": "Browser engine for this run, one of the supported browser types (e.g. msedge, chrome, stealth-chromium). Overrides the workflow-level setting. Null inherits from the workflow.",
+ "examples": [
+ "chrome"
+ ]
+ },
"run_metadata": {
"anyOf": [
{
@@ -31119,6 +31243,21 @@
"code"
]
},
+ "browser_type": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Browser Type",
+ "description": "Browser engine for this run, one of the supported browser types (e.g. msedge, chrome, stealth-chromium). Overrides the workflow-level setting. Null inherits from the workflow.",
+ "examples": [
+ "chrome"
+ ]
+ },
"run_metadata": {
"anyOf": [
{
diff --git a/skyvern/cli/mcp_tools/workflow.py b/skyvern/cli/mcp_tools/workflow.py
index 385f0e40d..1a91f63e6 100644
--- a/skyvern/cli/mcp_tools/workflow.py
+++ b/skyvern/cli/mcp_tools/workflow.py
@@ -526,6 +526,7 @@ _WORKFLOW_UPDATE_PRESERVED_TOP_LEVEL_FIELDS = (
"pin_saved_session_ip",
"browser_profile_id",
"browser_profile_key",
+ "browser_type",
"model",
"is_saved_task",
"max_screenshot_scrolls",
diff --git a/skyvern/forge/sdk/db/models.py b/skyvern/forge/sdk/db/models.py
index a9d893ea2..0dd237876 100644
--- a/skyvern/forge/sdk/db/models.py
+++ b/skyvern/forge/sdk/db/models.py
@@ -617,6 +617,7 @@ class WorkflowModel(SoftDeleteMixin, Base):
status = Column(String, nullable=False, default="published")
generate_script = Column(Boolean, default=False, nullable=False)
run_with = Column(String, nullable=True) # 'agent' or 'code'
+ browser_type = Column(String, nullable=True) # BrowserType value; None means system default
ai_fallback = Column(Boolean, default=True, nullable=False, server_default=sqlalchemy.true())
cache_key = Column(String, nullable=True)
adaptive_caching = Column(Boolean, default=False, nullable=False, server_default=sqlalchemy.false())
@@ -803,6 +804,7 @@ class WorkflowRunModel(Base):
sequential_key = Column(String, nullable=True)
sequential_credential_id = Column(String, nullable=True)
run_with = Column(String, nullable=True) # 'agent' or 'code'
+ browser_type = Column(String, nullable=True) # BrowserType value; None means system default
debug_session_id: Column = Column(String, nullable=True)
trigger_type = Column(String, nullable=True)
workflow_schedule_id = Column(String, nullable=True, index=True)
diff --git a/skyvern/forge/sdk/db/repositories/workflow_runs.py b/skyvern/forge/sdk/db/repositories/workflow_runs.py
index 948f8e6ff..e7153b336 100644
--- a/skyvern/forge/sdk/db/repositories/workflow_runs.py
+++ b/skyvern/forge/sdk/db/repositories/workflow_runs.py
@@ -225,6 +225,7 @@ class WorkflowRunsRepository(BaseRepository):
sequential_key: str | None = None,
sequential_credential_id: str | None = None,
run_with: str | None = None,
+ browser_type: str | None = None,
debug_session_id: str | None = None,
ai_fallback: bool | None = None,
code_gen: bool | None = None,
@@ -264,6 +265,7 @@ class WorkflowRunsRepository(BaseRepository):
sequential_key=sequential_key,
sequential_credential_id=sequential_credential_id,
run_with=run_with,
+ browser_type=browser_type,
debug_session_id=debug_session_id,
ai_fallback=ai_fallback,
code_gen=code_gen,
diff --git a/skyvern/forge/sdk/db/repositories/workflows.py b/skyvern/forge/sdk/db/repositories/workflows.py
index 06a263c53..1ea7e07a2 100644
--- a/skyvern/forge/sdk/db/repositories/workflows.py
+++ b/skyvern/forge/sdk/db/repositories/workflows.py
@@ -252,6 +252,7 @@ class WorkflowsRepository(BaseRepository):
is_saved_task: bool = False,
status: WorkflowStatus = WorkflowStatus.published,
run_with: str | None = None,
+ browser_type: str | None = None,
ai_fallback: bool = True,
cache_key: str | None = None,
adaptive_caching: bool = False,
@@ -296,6 +297,7 @@ class WorkflowsRepository(BaseRepository):
is_saved_task=is_saved_task,
status=status,
run_with=run_with,
+ browser_type=browser_type,
ai_fallback=ai_fallback,
cache_key=cache_key or DEFAULT_SCRIPT_RUN_ID,
adaptive_caching=adaptive_caching,
diff --git a/skyvern/forge/sdk/db/utils.py b/skyvern/forge/sdk/db/utils.py
index af3b9ea49..e719b6f88 100644
--- a/skyvern/forge/sdk/db/utils.py
+++ b/skyvern/forge/sdk/db/utils.py
@@ -69,7 +69,7 @@ from skyvern.forge.sdk.workflow.models.workflow import (
WorkflowStatus,
)
from skyvern.schemas.proxy_pinning import redact_proxy_location
-from skyvern.schemas.runs import GeoTarget, ProxyLocation, ProxyLocationInput, ScriptRunResponse
+from skyvern.schemas.runs import GeoTarget, ProxyLocation, ProxyLocationInput, ScriptRunResponse, read_browser_type
from skyvern.schemas.scripts import Script, ScriptBlock, ScriptFile
from skyvern.schemas.workflows import BlockStatus, BlockType
from skyvern.webeye.actions.actions import (
@@ -632,6 +632,7 @@ def convert_to_workflow(
extra_http_headers=workflow_model.extra_http_headers,
cdp_connect_headers=workflow_model.cdp_connect_headers,
run_with=workflow_model.run_with,
+ browser_type=read_browser_type(workflow_model),
ai_fallback=workflow_model.ai_fallback,
cache_key=workflow_model.cache_key,
adaptive_caching=workflow_model.adaptive_caching,
@@ -698,6 +699,7 @@ def convert_to_workflow_run(
if workflow_run_model.script_run
else None,
run_with=workflow_run_model.run_with,
+ browser_type=read_browser_type(workflow_run_model),
code_gen=workflow_run_model.code_gen,
ai_fallback=workflow_run_model.ai_fallback,
trigger_type=_safe_trigger_type(workflow_run_model.trigger_type),
diff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.py
index 2d0318498..57e6ddead 100644
--- a/skyvern/forge/sdk/routes/agent_protocol.py
+++ b/skyvern/forge/sdk/routes/agent_protocol.py
@@ -155,10 +155,12 @@ from skyvern.schemas.artifacts import EntityType, entity_type_to_param
from skyvern.schemas.folders import Folder, FolderCreate, FolderUpdate, UpdateWorkflowFolderRequest
from skyvern.schemas.runs import (
BROWSER_ADDRESS_SERVER_ASSIGNED_CONTEXT_KEY,
+ BROWSER_SESSION_SERVER_ASSIGNED_CONTEXT_KEY,
CUA_ENGINES,
MAX_SEARCH_FETCH_LIMIT,
BlockRunRequest,
BlockRunResponse,
+ BrowserTypeOption,
BulkCancelRunsRequest,
BulkCancelRunsResponse,
RunEngine,
@@ -171,6 +173,8 @@ from skyvern.schemas.runs import (
UploadFileResponse,
WorkflowRunRequest,
WorkflowRunResponse,
+ read_browser_type,
+ supported_browser_type_options,
)
from skyvern.schemas.tags import (
RunTagHistoryResponse,
@@ -219,6 +223,7 @@ from skyvern.utils.organization_slug import is_org_slug_unique_violation
from skyvern.utils.url_validators import validate_webhook_url
from skyvern.utils.yaml_loader import format_yaml_error, safe_load_no_dates
from skyvern.webeye.actions.actions import Action
+from skyvern.webeye.real_browser_manager import runtime_supports_browser_type_selection
LOG = structlog.get_logger()
@@ -600,6 +605,7 @@ def _workflow_run_request_to_legacy_request(workflow_run_request: WorkflowRunReq
cdp_connect_headers=workflow_run_request.cdp_connect_headers,
browser_address=workflow_run_request.browser_address,
run_with=workflow_run_request.run_with,
+ browser_type=read_browser_type(workflow_run_request),
ai_fallback=workflow_run_request.ai_fallback,
run_metadata=workflow_run_request.run_metadata,
)
@@ -613,6 +619,21 @@ def _tag_write_context_from_caller(caller: org_auth_service.CallerContext) -> Ta
)
+def _hydrate_run_request_for_response(
+ run_request: WorkflowRunRequest, workflow_run: WorkflowRun, workflow: Workflow | None
+) -> WorkflowRunRequest:
+ """Echo the effective persisted values on the create response without mutating the caller's request.
+
+ A run that omits browser_type inherits the workflow's engine (resolved onto workflow_run at
+ persistence), so the returned request must report that engine rather than the request's omitted
+ null; the title is hydrated from the workflow when one exists.
+ """
+ updates: dict[str, str | None] = {"browser_type": read_browser_type(workflow_run)}
+ if workflow is not None:
+ updates["title"] = workflow.title
+ return run_request.model_copy(update=updates)
+
+
@base_router.post(
"/run/agents",
tags=["Runs"],
@@ -702,14 +723,14 @@ async def run_workflow(
if workflow_run.workflow_id:
span.set_attribute("workflow_id", workflow_run.workflow_id)
- # Hydrate workflow title from workflow_run.workflow_id
+ # Hydrate the returned request from the persisted run: workflow title (when the workflow exists) and
+ # the effective browser_type, so a run that omitted browser_type reports the inherited engine
+ # instead of the request's null.
workflow = await app.WORKFLOW_SERVICE.get_workflow(
workflow_id=workflow_run.workflow_id,
organization_id=current_org.organization_id,
)
- workflow_run_request_hydrated = workflow_run_request
- if workflow:
- workflow_run_request_hydrated = workflow_run_request.model_copy(update={"title": workflow.title})
+ workflow_run_request_hydrated = _hydrate_run_request_for_response(workflow_run_request, workflow_run, workflow)
return WorkflowRunResponse(
run_id=workflow_run.workflow_run_id,
@@ -1630,6 +1651,39 @@ async def get_folders(
return result
+@base_router.get(
+ "/browser_types",
+ tags=["Server"],
+ response_model=list[BrowserTypeOption],
+ description=(
+ "List the selectable browser engines for the workflow/run browser_type setting. The list is "
+ "runtime-capability aware: a runtime that can honor an explicit engine (the cloud "
+ "dynamic-browser capability) returns all supported engines, while a runtime without it "
+ "(OSS/self-host) returns an empty list rather than advertising selections the server would "
+ "reject."
+ ),
+ summary="List selectable browser types",
+ openapi_extra={
+ "x-fern-sdk-method-name": "get_browser_types",
+ },
+ responses={200: {"description": "Successfully listed selectable browser types"}},
+)
+# Backwards-compatible aliases (legacy prefix + trailing slash); hidden from schema in favor of the
+# canonical /browser_types above.
+@legacy_base_router.get("/browser_types", response_model=list[BrowserTypeOption], include_in_schema=False)
+@legacy_base_router.get("/browser_types/", response_model=list[BrowserTypeOption], include_in_schema=False)
+@base_router.get("/browser_types/", response_model=list[BrowserTypeOption], include_in_schema=False)
+async def get_browser_types(
+ current_org: Organization = Depends(org_auth_service.get_current_org),
+) -> list[BrowserTypeOption]:
+ """Selectable browser engines for the workflow/run browser_type setting, generated from the
+ BrowserType domain enum. Capability-gated: only advertised where the runtime can actually honor an
+ explicit selection (the cloud dynamic-browser creator is registered); OSS/self-host returns []."""
+ if not runtime_supports_browser_type_selection():
+ return []
+ return supported_browser_type_options()
+
+
@legacy_base_router.put("/folders/{folder_id}", response_model=Folder, tags=["agent"], include_in_schema=False)
@legacy_base_router.put("/folders/{folder_id}/", response_model=Folder, include_in_schema=False)
@base_router.put(
@@ -3538,7 +3592,10 @@ async def run_block(
failure_reason=workflow_run.failure_reason,
created_at=workflow_run.created_at,
modified_at=workflow_run.modified_at,
- run_request=block_run_request,
+ # Echo the effective persisted engine (an omitted browser_type inherits the workflow default at
+ # setup) without mutating the caller's input model, so the response matches the launched engine
+ # instead of reporting the request's null.
+ run_request=block_run_request.model_copy(update={"browser_type": read_browser_type(workflow_run)}),
downloaded_files=None,
recording_url=None,
browser_session_id=workflow_run.browser_session_id,
@@ -3829,9 +3886,13 @@ def _workflow_run_request_from_workflow_request(
"browser_address": workflow_request.browser_address,
"run_with": workflow_request.run_with,
"ai_fallback": workflow_request.ai_fallback,
+ "browser_type": read_browser_type(workflow_request),
"run_metadata": workflow_request.run_metadata,
},
- context={BROWSER_ADDRESS_SERVER_ASSIGNED_CONTEXT_KEY: True},
+ context={
+ BROWSER_ADDRESS_SERVER_ASSIGNED_CONTEXT_KEY: True,
+ BROWSER_SESSION_SERVER_ASSIGNED_CONTEXT_KEY: True,
+ },
)
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 0f89ae7a4..35908cc82 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -65,7 +65,7 @@ from opentelemetry import trace as otel_trace
from playwright.async_api import BrowserContext, Page
from playwright.async_api import TimeoutError as PlaywrightTimeoutError
from pydantic import BaseModel, Field, PrivateAttr, field_validator, model_validator
-from sqlalchemy.exc import InterfaceError, OperationalError
+from sqlalchemy.exc import InterfaceError, OperationalError, SQLAlchemyError
from skyvern.config import settings
from skyvern.constants import (
@@ -105,6 +105,7 @@ from skyvern.exceptions import (
TaskNotFound,
UnexpectedTaskStatus,
UnresolvableHost,
+ WorkflowNotFound,
get_user_facing_exception_message,
)
from skyvern.forge import app
@@ -256,7 +257,7 @@ from skyvern.forge.sdk.workflow.secret_encryption import (
)
from skyvern.schemas.browser_session_close import BrowserSessionCloseReason
from skyvern.schemas.emails import EmailBodyFormat
-from skyvern.schemas.runs import RunEngine
+from skyvern.schemas.runs import RunEngine, read_browser_type
from skyvern.schemas.self_heal import HealClassification, HealSkipReason, HealStatus, OutputObligation
from skyvern.schemas.workflows import (
ERROR_CODE_MAPPING_MAX_ENTRIES,
@@ -16906,6 +16907,14 @@ class WorkflowTriggerBlock(Block):
# session; for async (fire-and-forget), let the child's Temporal worker
# handle its own browser.
created_fresh_session = False
+ # Set when the sync branch pre-resolves the target workflow's version to seed the child's
+ # engine into its session; reused by setup below so the workflow is resolved only once.
+ resolved_target_workflow_id: str | None = None
+ # Domain BrowserType of the fresh server-owned session this trigger provisions to match the
+ # target workflow's engine (kept separate from its mapped PersistentBrowserType). Passed to
+ # setup_workflow_run so the child run persists that engine despite carrying a browser_session_id;
+ # stays None for caller-supplied sessions and parent-shared browsers.
+ child_effective_browser_type: str | None = None
if self.browser_session_id:
resolved_browser_session_id = self.browser_session_id
elif self.use_parent_browser_session and browser_session_id:
@@ -16920,11 +16929,42 @@ class WorkflowTriggerBlock(Block):
# its own persistent session to avoid sharing the parent's browser.
parent_workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(workflow_run_id)
proxy_location = parent_workflow_run.proxy_location if parent_workflow_run else None
+ # This session is provisioned before the child inherits the target workflow's browser_type
+ # in setup below, so resolve the target's default engine now and seed it into the session.
+ # An explicit engine is passed as a workflow-owned selection (with the parent run id) so the
+ # session manager's first-party guard fires; null keeps the current default. The resolved
+ # version is reused by setup so the target workflow is loaded only once.
+ # Lazy import: real_browser_manager pulls block back in at module load (circular).
+ from skyvern.webeye.real_browser_manager import to_persistent_session_browser_type
+
+ child_session_kwargs: dict[str, Any] = {}
+ # Production get_workflow_by_permanent_id is async; some legacy cleanup/fence tests inject a
+ # plain (non-async) MagicMock whose call result is not awaitable. Pre-resolve the target
+ # workflow only when the result is actually awaitable — otherwise fall back to the legacy
+ # null/default path (no engine seeding, no version pin) so existing failure/cleanup behavior
+ # proceeds. This pre-resolution runs before the setup handler below, so a target-lookup
+ # failure (workflow deleted -> WorkflowNotFound, or a DB error) is routed to the same _fail
+ # path rather than escaping execute; unrelated exceptions still propagate.
+ try:
+ maybe_target_workflow = app.WORKFLOW_SERVICE.get_workflow_by_permanent_id(
+ resolved_workflow_permanent_id, organization_id=organization_id
+ )
+ if inspect.isawaitable(maybe_target_workflow):
+ target_workflow = await maybe_target_workflow
+ resolved_target_workflow_id = target_workflow.workflow_id
+ child_effective_browser_type = read_browser_type(target_workflow)
+ child_mapped_browser_type = to_persistent_session_browser_type(child_effective_browser_type)
+ if child_mapped_browser_type is not None:
+ child_session_kwargs["browser_type"] = child_mapped_browser_type
+ child_session_kwargs["workflow_run_id"] = workflow_run_id
+ except (WorkflowNotFound, SQLAlchemyError) as e:
+ return await _fail(f"Failed to resolve triggered workflow: {get_user_facing_exception_message(e)}")
try:
child_browser_session = await app.PERSISTENT_SESSIONS_MANAGER.create_session(
organization_id=organization_id,
proxy_location=proxy_location,
timeout_minutes=30,
+ **child_session_kwargs,
)
resolved_browser_session_id = child_browser_session.persistent_browser_session_id
created_fresh_session = True
@@ -16977,6 +17017,14 @@ class WorkflowTriggerBlock(Block):
parent_workflow_run_id=workflow_run_id,
ignore_inherited_workflow_system_prompt=self.ignore_workflow_system_prompt,
trigger_type=inherited_trigger_type,
+ resolved_workflow_id=resolved_target_workflow_id,
+ # A child sharing the parent's browser runs in the parent's engine, so it
+ # must not inherit the target workflow's browser_type (which it would never use).
+ shares_parent_browser=self.use_parent_browser_session,
+ # The fresh server-owned session provisioned above was seeded to the target
+ # workflow's engine, so persist that engine on the child run for fidelity even
+ # though it carries a browser_session_id. None for caller-supplied/parent-shared.
+ server_owned_browser_type=child_effective_browser_type if created_fresh_session else None,
)
except Exception as e:
error_msg = get_user_facing_exception_message(e)
diff --git a/skyvern/forge/sdk/workflow/models/workflow.py b/skyvern/forge/sdk/workflow/models/workflow.py
index 8c7fc3d91..2d60e45ab 100644
--- a/skyvern/forge/sdk/workflow/models/workflow.py
+++ b/skyvern/forge/sdk/workflow/models/workflow.py
@@ -28,12 +28,20 @@ from skyvern.forge.sdk.workflow.models.run_limits import (
MaxScreenshotScrolls,
reject_bool_max_elapsed_time_minutes,
)
-from skyvern.forge.sdk.workflow.models.validators import normalize_run_metadata, normalize_run_with
+from skyvern.forge.sdk.workflow.models.validators import (
+ normalize_run_metadata,
+ normalize_run_with,
+)
from skyvern.schemas.runs import (
BROWSER_ADDRESS_SERVER_ASSIGNED_CONTEXT_KEY,
+ BROWSER_TYPE_ATTACH_CONFLICT_MESSAGE,
ProxyLocationInput,
ScriptRunResponse,
+ _browser_address_is_server_assigned,
+ _browser_session_is_server_assigned,
_validate_browser_address,
+ browser_type_attach_conflict,
+ normalize_browser_type,
)
from skyvern.schemas.workflows import WorkflowStatus
from skyvern.utils.secret_headers import mask_header_values
@@ -57,6 +65,7 @@ class WorkflowRequestBody(BaseModel):
cdp_connect_headers: dict[str, str] | None = None
browser_address: str | None = None
run_with: str | None = None
+ browser_type: str | None = None
ai_fallback: bool | None = None
run_metadata: dict[str, str] | None = None
@@ -77,6 +86,11 @@ class WorkflowRequestBody(BaseModel):
def validate_run_metadata(cls, v: dict[str, str] | None) -> dict[str, str] | None:
return normalize_run_metadata(v)
+ @field_validator("browser_type", mode="before")
+ @classmethod
+ def _normalize_browser_type(cls, v: str | None) -> str | None:
+ return normalize_browser_type(v)
+
@field_validator("browser_address")
@classmethod
def validate_browser_address(cls, browser_address: str | None, info: ValidationInfo) -> str | None:
@@ -84,6 +98,23 @@ class WorkflowRequestBody(BaseModel):
return browser_address
return _validate_browser_address(browser_address)
+ @model_validator(mode="after")
+ def _reject_browser_type_with_attached_browser(self, info: ValidationInfo) -> Self:
+ if not browser_type_attach_conflict(
+ browser_type=self.browser_type,
+ browser_session_id=self.browser_session_id,
+ browser_address=self.browser_address,
+ ):
+ return self
+ # A raw browser_type+attachment conflict exists. Reconstruction re-materializes the server's own
+ # persisted state (a typed run can legitimately gain a server-generated session), so a
+ # SERVER-ASSIGNED session/address is excused; a caller-supplied one (no context) still 422s.
+ session_ok = self.browser_session_id is None or _browser_session_is_server_assigned(info)
+ address_ok = self.browser_address is None or _browser_address_is_server_assigned(info)
+ if session_ok and address_ok:
+ return self
+ raise ValueError(BROWSER_TYPE_ATTACH_CONFLICT_MESSAGE)
+
@model_validator(mode="after")
def _reject_start_fresh_with_session(self) -> Self:
# Covers the legacy /workflows/{id}/run endpoint, which parses this body directly. Upstream
@@ -208,6 +239,7 @@ class Workflow(BaseModel):
extra_http_headers: dict[str, str] | None = None
cdp_connect_headers: dict[str, str] | None = None
run_with: str = "agent"
+ browser_type: str | None = None
ai_fallback: bool = True
cache_key: str | None = None
adaptive_caching: bool = False
@@ -314,6 +346,7 @@ class WorkflowRun(BaseModel):
max_elapsed_time_minutes: int | None = None
browser_address: str | None = None
run_with: str | None = None
+ browser_type: str | None = None
script_run: ScriptRunResponse | None = None
job_id: str | None = None
depends_on_workflow_run_id: str | None = None
@@ -485,6 +518,7 @@ class WorkflowRunResponseBase(BaseModel):
max_screenshot_scrolls: int | None = None
browser_address: str | None = None
run_with: str = "agent"
+ browser_type: str | None = None
script_run: ScriptRunResponse | None = None
script_id: str | None = None
errors: list[dict[str, Any]] | None = None
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.py
index 483a46406..354dfb3ed 100644
--- a/skyvern/forge/sdk/workflow/service.py
+++ b/skyvern/forge/sdk/workflow/service.py
@@ -225,6 +225,7 @@ from skyvern.schemas.runs import (
RunType,
WorkflowRunRequest,
WorkflowRunResponse,
+ read_browser_type,
resolve_start_fresh,
should_suppress_memory_write,
)
@@ -273,6 +274,11 @@ from skyvern.webeye.actions.action_types import ActionType
from skyvern.webeye.actions.actions import Action
from skyvern.webeye.browser_state import BrowserState
from skyvern.webeye.profile_cookie_merge import cookie_delta, seed_cookie_values, union_cookies_into_profile_dir
+from skyvern.webeye.real_browser_manager import (
+ SelectedBrowserTypeUnsupportedError,
+ ensure_runtime_supports_browser_type,
+ to_persistent_session_browser_type,
+)
from skyvern.webeye.session_cookies import (
persist_session_cookies,
read_persisted_session_cookies,
@@ -321,6 +327,19 @@ _T6 = TypeVar("_T6")
_USER_DEFINED_ERROR_KEYS = {"error_code", "reasoning", "confidence_float", "error_type"}
+def partition_reuse_bound_key_by_browser_type(reuse_bound_key: str, persistent_browser_type_value: str) -> str:
+ """Fold an explicit persistent browser type into a real reuse identity.
+
+ A run that pins an engine must never adopt a live session created for a different engine (or an
+ untyped session), and two runs sharing the same identity and the same engine must still reuse.
+ The raw identity is hashed into the composite so no credential/profile reuse key leaks; the
+ result is deterministic and index-safe (short, fixed-length). Callers must only reach here with a
+ real reuse identity (never an admission-off sentinel) and a recognized explicit engine.
+ """
+ composite = f"{reuse_bound_key}\x00bt={persistent_browser_type_value}".encode()
+ return f"bt:{persistent_browser_type_value}:sha256:{sha256(composite).hexdigest()}"
+
+
def _strict_user_defined_error_payload(value: Any) -> dict[str, Any] | None:
if type(value) is not dict or set(value) != _USER_DEFINED_ERROR_KEYS:
return None
@@ -2566,6 +2585,8 @@ class WorkflowService:
copilot_session_id: str | None = None,
resolved_workflow_id: str | None = None,
tag_write_context: TagWriteContext | None = None,
+ shares_parent_browser: bool = False,
+ server_owned_browser_type: str | None = None,
) -> WorkflowRun:
"""
Create a workflow run and its parameters. Validate the workflow and the organization. If there are missing
@@ -2626,6 +2647,28 @@ class WorkflowService:
)
if workflow_request.run_with is None:
workflow_request.run_with = workflow.run_with
+ # Attachment ownership wins: an attached browser (a live session or a remote
+ # browser_address) already owns its engine, so never inherit the workflow's browser_type
+ # onto an attached run — it must persist None, or the browser_type+session/address
+ # validators would reject the response/retry reconstruction. A synchronous trigger child
+ # that shares the parent's (in-memory) browser is the same case: the child runs in the
+ # parent's engine, so a per-child selection is meaningless and inheriting a stale workflow
+ # default would report an engine the child never uses. Only an unattached, non-shared run
+ # inherits the workflow default (explicit run browser_type > workflow default > null).
+ #
+ # server_owned_browser_type is an explicit provenance signal from the caller (the sync
+ # WorkflowTriggerBlock) that it provisioned a FRESH server-owned session seeded to that
+ # engine for this run: the child truly executes in that engine, so persist it despite the
+ # browser_session_id. Never inferred from the session id, and never set for a caller-supplied
+ # session/address or a parent-shared browser — a server-assigned session is excused from the
+ # attach-conflict validators on reconstruction.
+ if workflow_request.browser_type is None:
+ if server_owned_browser_type is not None:
+ workflow_request.browser_type = server_owned_browser_type
+ elif not shares_parent_browser and not (
+ workflow_request.browser_session_id or workflow_request.browser_address
+ ):
+ workflow_request.browser_type = read_browser_type(workflow)
# Force ai_fallback=True for adaptive caching (code_version >= 2) runs.
# Adaptive caching requires AI fallback to self-heal when cached scripts break.
@@ -3890,6 +3933,7 @@ class WorkflowService:
browser_session_id: str | None = None,
browser_profile_id: str | None = None,
proxy_location: ProxyLocationInput = None,
+ browser_type: str | None = None,
) -> PersistentBrowserSession | None:
if browser_session_id: # the user has supplied an id, so no need to create one
return None
@@ -3902,12 +3946,17 @@ class WorkflowService:
timeouts = [getattr(block, "timeout_seconds", 60 * 60) for block in human_interaction_blocks]
timeout_seconds = sum(timeouts) + 60 * 60
+ mapped_browser_type = to_persistent_session_browser_type(browser_type)
+ browser_type_kwargs: dict[str, Any] = (
+ {"browser_type": mapped_browser_type} if mapped_browser_type is not None else {}
+ )
browser_session = await app.PERSISTENT_SESSIONS_MANAGER.create_session(
organization_id=organization_id,
timeout_minutes=timeout_seconds // 60,
browser_profile_id=browser_profile_id,
proxy_location=proxy_location,
inherit_profile_proxy=True,
+ **browser_type_kwargs,
)
return browser_session
@@ -4048,6 +4097,14 @@ class WorkflowService:
parameter_values,
persisted_selections,
)
+ resolved_browser_type = to_persistent_session_browser_type(read_browser_type(workflow_run))
+ if resolved_browser_type is not None:
+ # Partition the reuse identity by the pinned engine so Chrome and Edge (and
+ # untyped) runs never adopt each other's live session. Null/default keeps the
+ # exact legacy key for backward compatibility.
+ reuse_bound_key = partition_reuse_bound_key_by_browser_type(
+ reuse_bound_key, resolved_browser_type.value
+ )
except Exception:
LOG.warning(
"Reusable browser identity is unresolvable; using a fresh browser for this run",
@@ -4546,6 +4603,10 @@ class WorkflowService:
last_unusable_session_id: str | None = None
for _ in range(2):
try:
+ mapped_browser_type = to_persistent_session_browser_type(read_browser_type(workflow_run))
+ browser_type_kwargs: dict[str, Any] = (
+ {"browser_type": mapped_browser_type} if mapped_browser_type is not None else {}
+ )
browser_session = await app.PERSISTENT_SESSIONS_MANAGER.create_session(
organization_id=organization_id,
timeout_minutes=30,
@@ -4554,6 +4615,7 @@ class WorkflowService:
inherit_profile_proxy=True,
bound_workflow_permanent_id=workflow_permanent_id,
bound_key=bound_key,
+ **browser_type_kwargs,
)
except IntegrityError:
browser_session = await app.DATABASE.browser_sessions.get_live_bound_persistent_browser_session(
@@ -5166,6 +5228,7 @@ class WorkflowService:
browser_session_id=browser_session_id,
browser_profile_id=browser_profile_id if using_managed_browser_profile else None,
proxy_location=workflow_run.proxy_location,
+ browser_type=read_browser_type(workflow_run),
)
if browser_session:
@@ -8469,6 +8532,7 @@ class WorkflowService:
extra_http_headers: dict[str, str] | None = None,
cdp_connect_headers: dict[str, str] | None = None,
run_with: str | None = None,
+ browser_type: str | None = None,
cache_key: str | None = None,
ai_fallback: bool | None = None,
run_sequentially: bool = False,
@@ -8512,6 +8576,7 @@ class WorkflowService:
extra_http_headers=extra_http_headers,
cdp_connect_headers=cdp_connect_headers,
run_with=run_with,
+ browser_type=browser_type,
cache_key=cache_key,
ai_fallback=True if ai_fallback is None else ai_fallback,
run_sequentially=run_sequentially,
@@ -9474,6 +9539,7 @@ class WorkflowService:
browser_address=workflow_request.browser_address,
sequential_key=sequential_key,
run_with=workflow_request.run_with,
+ **({"browser_type": _bt} if (_bt := read_browser_type(workflow_request)) is not None else {}),
debug_session_id=debug_session_id,
ai_fallback=workflow_request.ai_fallback,
code_gen=code_gen,
@@ -9547,6 +9613,15 @@ class WorkflowService:
browser_session = None
else:
try:
+ mapped_browser_type = to_persistent_session_browser_type(read_browser_type(workflow_run))
+ # This forced session is created before the run context is installed, so pass
+ # the run id explicitly alongside an explicit engine — otherwise the manager
+ # cannot see a workflow_run_id and its workflow-owned first-party guard never
+ # fires. Null/default keeps the exact legacy call shape (no extra kwargs).
+ browser_type_kwargs: dict[str, Any] = {}
+ if mapped_browser_type is not None:
+ browser_type_kwargs["browser_type"] = mapped_browser_type
+ browser_type_kwargs["workflow_run_id"] = workflow_run.workflow_run_id
browser_session = await app.PERSISTENT_SESSIONS_MANAGER.create_session(
organization_id=organization_id,
proxy_location=workflow_request.proxy_location,
@@ -9554,6 +9629,7 @@ class WorkflowService:
runnable_type=FORCED_WORKFLOW_SESSION_RUNNABLE_TYPE,
browser_profile_id=forced_browser_profile_id,
inherit_profile_proxy=True,
+ **browser_type_kwargs,
)
browser_session_id = browser_session.persistent_browser_session_id
LOG.info(
@@ -9599,6 +9675,7 @@ class WorkflowService:
browser_address=workflow_request.browser_address,
sequential_key=sequential_key,
run_with=workflow_request.run_with,
+ **({"browser_type": _bt} if (_bt := read_browser_type(workflow_request)) is not None else {}),
debug_session_id=debug_session_id,
ai_fallback=workflow_request.ai_fallback,
code_gen=code_gen,
@@ -11091,6 +11168,7 @@ class WorkflowService:
task_v2=capped_task_v2(task_v2) if cap_output_values else task_v2,
browser_address=workflow_run.browser_address,
run_with=workflow_run.run_with,
+ browser_type=read_browser_type(workflow_run),
script_run=workflow_run.script_run,
script_id=workflow_run.script_run.script_id if workflow_run.script_run else None,
errors=errors,
@@ -11756,6 +11834,7 @@ class WorkflowService:
totp_identifier=workflow_run.totp_identifier,
start_fresh_browser=bool(workflow_run.start_fresh_browser),
reuse_browser_session=workflow_run.reuse_browser_session,
+ browser_type=read_browser_type(workflow_run),
),
errors=workflow_run_status_response.errors,
step_count=workflow_run_status_response.total_steps,
@@ -12230,6 +12309,7 @@ class WorkflowService:
extra_http_headers=runtime_workflow.extra_http_headers,
cdp_connect_headers=cdp_connect_headers,
run_with=runtime_workflow.run_with,
+ browser_type=read_browser_type(runtime_workflow),
ai_fallback=runtime_workflow.ai_fallback,
cache_key=runtime_workflow.cache_key,
code_version=runtime_workflow.code_version,
@@ -12339,6 +12419,7 @@ class WorkflowService:
is_saved_task=request.is_saved_task,
status=request.status,
run_with=request.run_with,
+ browser_type=read_browser_type(request),
cache_key=request.cache_key,
ai_fallback=request.ai_fallback,
run_sequentially=request.run_sequentially,
@@ -12439,6 +12520,14 @@ class WorkflowService:
validate_code_block_templates: bool = True,
) -> Workflow:
organization_id = organization.organization_id
+ # Fail fast before any persistence path (idempotent, update, or initial create): a browser_type
+ # this runtime cannot honor is rejected at ingress with a 4xx instead of a 200-on-save that
+ # then fails at every launch. Only an explicitly-requested selection is checked, so an update
+ # that omits the field (and inherits the stored value) is untouched.
+ try:
+ ensure_runtime_supports_browser_type(read_browser_type(request))
+ except SelectedBrowserTypeUnsupportedError as e:
+ raise SkyvernHTTPException(str(e), HTTPStatus.BAD_REQUEST) from e
title = resolved_title
if title is None:
title = await self.resolve_workflow_creation_title(organization_id, request)
@@ -12569,6 +12658,14 @@ class WorkflowService:
is_saved_task=request.is_saved_task,
status=request.status,
run_with=request.run_with,
+ # A save that omits browser_type inherits the stored engine (the editor's payload
+ # omits it); an explicit value — including null to clear — is honored. Mirrors the
+ # pin_saved_session_ip / code_version siblings above.
+ browser_type=(
+ request.browser_type
+ if "browser_type" in request.model_fields_set
+ else read_browser_type(existing_latest_workflow)
+ ),
cache_key=request.cache_key,
ai_fallback=request.ai_fallback,
run_sequentially=request.run_sequentially,
diff --git a/skyvern/schemas/runs.py b/skyvern/schemas/runs.py
index b73ee4f5d..bdaf0dc50 100644
--- a/skyvern/schemas/runs.py
+++ b/skyvern/schemas/runs.py
@@ -1,7 +1,8 @@
from __future__ import annotations
from datetime import datetime
-from typing import TYPE_CHECKING, Annotated, Any, Literal, TypeAlias, Union
+from enum import StrEnum
+from typing import TYPE_CHECKING, Annotated, Any, Literal, Protocol, TypeAlias, Union
from pydantic import (
AliasChoices,
@@ -26,7 +27,10 @@ from skyvern.forge.sdk.workflow.models.run_limits import (
MaxScreenshotScrolls,
reject_bool_max_elapsed_time_minutes,
)
-from skyvern.forge.sdk.workflow.models.validators import normalize_run_metadata, normalize_run_with
+from skyvern.forge.sdk.workflow.models.validators import (
+ normalize_run_metadata,
+ normalize_run_with,
+)
from skyvern.schemas.docs.doc_examples import (
BROWSER_SESSION_ID_EXAMPLES,
ERROR_CODE_MAPPING_EXAMPLES,
@@ -69,10 +73,105 @@ from skyvern.schemas.run_enums import ( # noqa: F401
from skyvern.utils.secret_headers import mask_header_values
from skyvern.utils.url_validators import WebhookUrl, validate_browser_host, validate_url
+
+class BrowserType(StrEnum):
+ """Browser engine selectable at the workflow and workflow-run level.
+
+ This is the workflow/run feature's own domain truth for browser selection. It is deliberately a
+ distinct enum from the PBS ``PersistentBrowserType`` (which stays dedicated to persistent-session
+ concepts) — not an alias or subclass. The concrete serialized values are intentionally shared
+ with PBS (a contract test enforces value parity), and the cloud runtime maps them by value
+ through ``CloudBrowserType.from_source_browser_type``.
+ """
+
+ MSEdge = "msedge"
+ Chrome = "chrome"
+ StealthChromium = "stealth-chromium"
+
+
+# Human labels for the pickers. A value missing here still surfaces (with a derived label), so a
+# newly added BrowserType needs no edit to appear — only an optional nicer label.
+_BROWSER_TYPE_LABELS: dict[str, str] = {
+ BrowserType.MSEdge.value: "Microsoft Edge",
+ BrowserType.Chrome.value: "Google Chrome",
+ BrowserType.StealthChromium.value: "Stealth Chromium",
+}
+
+
+class SupportsBrowserType(Protocol):
+ """A workflow/run/request model (or its ORM row) that carries a ``browser_type`` selection."""
+
+ browser_type: str | None
+
+
+def read_browser_type(source: SupportsBrowserType) -> str | None:
+ """Null/type-safe read of a ``browser_type`` selection from a model-like object.
+
+ An absent attribute, or a non-string value, reads as ``None``; a real string — valid or not — is
+ returned unchanged so the normal BrowserType validator / fail-fast still governs it downstream.
+ """
+ value = getattr(source, "browser_type", None)
+ return value if isinstance(value, str) else None
+
+
+def normalize_browser_type(v: str | None) -> str | None:
+ """Validate a user-supplied workflow/run browser_type against the ``BrowserType`` domain enum.
+
+ None passes through (inherit workflow / system default). An unrecognized value raises so the
+ public API rejects it. ``BrowserType`` is the workflow/run source of truth (distinct from PBS's
+ PersistentBrowserType).
+ """
+ if v is None:
+ return None
+ try:
+ return BrowserType(v).value
+ except ValueError:
+ valid = ", ".join(t.value for t in BrowserType)
+ raise ValueError(f"Invalid browser_type '{v}'; must be one of: {valid}")
+
+
+def _default_browser_type_label(value: str) -> str:
+ return value.replace("-", " ").replace("_", " ").title()
+
+
+# One shared contract for both request models: an attached browser (a live session or a remote
+# browser_address) already owns its engine, so a browser_type selection alongside it is a conflict.
+# A browser_profile_id is intentionally still allowed with browser_type (the selection overrides the
+# profile-derived engine).
+BROWSER_TYPE_ATTACH_CONFLICT_MESSAGE = (
+ "browser_type cannot be combined with browser_session_id or browser_address — an attached browser "
+ "owns its engine. Remove the browser_type selection, or drop the session/address to pick an engine."
+)
+
+
+def browser_type_attach_conflict(
+ *, browser_type: str | None, browser_session_id: str | None, browser_address: str | None
+) -> bool:
+ """A non-null browser_type combined with an attached browser (session or remote address) is a
+ conflict. browser_profile_id is deliberately not an attachment here."""
+ return browser_type is not None and (browser_session_id is not None or browser_address is not None)
+
+
+class BrowserTypeOption(BaseModel):
+ value: str
+ label: str
+
+
+def supported_browser_type_options() -> list[BrowserTypeOption]:
+ """Selectable browser engines for the workflow/run browser_type setting, generated from the
+ ``BrowserType`` enum so a new engine surfaces to validation, this options list, and the UI
+ without separate option maintenance."""
+ return [
+ BrowserTypeOption(value=t.value, label=_BROWSER_TYPE_LABELS.get(t.value, _default_browser_type_label(t.value)))
+ for t in BrowserType
+ ]
+
+
MAX_SEARCH_FETCH_LIMIT = 1000
MAX_RUN_ATTACHED_FILES = 50
_BROWSER_ADDRESS_ADAPTER = TypeAdapter(AnyHttpUrl | WebsocketUrl)
BROWSER_ADDRESS_SERVER_ASSIGNED_CONTEXT_KEY = "browser_address_is_server_assigned"
+BROWSER_SESSION_SERVER_ASSIGNED_CONTEXT_KEY = "browser_session_id_is_server_assigned"
# Type checkers need string Literal values, while pydantic's discriminated
# union preserves enum instances when runtime Literals use the enum members.
@@ -114,6 +213,10 @@ def _browser_address_is_server_assigned(info: ValidationInfo) -> bool:
return bool(info.context and info.context.get(BROWSER_ADDRESS_SERVER_ASSIGNED_CONTEXT_KEY))
+def _browser_session_is_server_assigned(info: ValidationInfo) -> bool:
+ return bool(info.context and info.context.get(BROWSER_SESSION_SERVER_ASSIGNED_CONTEXT_KEY))
+
+
class TaskRunRequest(BaseModel):
prompt: str = Field(
description=TASK_PROMPT_DOC_STRING,
@@ -401,6 +504,13 @@ class WorkflowRunRequest(BaseModel):
description="Whether to run the workflow with agent or code. Null inherits from the workflow setting.",
examples=["agent", "code"],
)
+ browser_type: str | None = Field(
+ default=None,
+ description="Browser engine for this run, one of the supported browser types "
+ "(e.g. msedge, chrome, stealth-chromium). Overrides the workflow-level setting. "
+ "Null inherits from the workflow.",
+ examples=["chrome"],
+ )
run_metadata: dict[str, str] | None = Field(
default=None,
description="String key/value metadata to attach to this workflow run for analytics tag filtering.",
@@ -419,6 +529,11 @@ class WorkflowRunRequest(BaseModel):
return None
return normalize_run_with(v)
+ @field_validator("browser_type", mode="before")
+ @classmethod
+ def _normalize_browser_type(cls, v: str | None) -> str | None:
+ return normalize_browser_type(v)
+
@field_validator("max_elapsed_time_minutes", mode="before")
@classmethod
def validate_max_elapsed_time_minutes(cls, value: object) -> object:
@@ -447,6 +562,24 @@ class WorkflowRunRequest(BaseModel):
def _mask_cdp_connect_headers(self, headers: dict[str, str] | None) -> dict[str, str] | None:
return mask_header_values(headers)
+ @model_validator(mode="after")
+ def _reject_browser_type_with_attached_browser(self, info: ValidationInfo) -> WorkflowRunRequest:
+ if not browser_type_attach_conflict(
+ browser_type=self.browser_type,
+ browser_session_id=self.browser_session_id,
+ browser_address=self.browser_address,
+ ):
+ return self
+ # A raw browser_type+attachment conflict exists. Reconstruction re-materializes the server's own
+ # persisted state (a typed run can legitimately gain a server-generated session via reuse /
+ # FORCE_BROWSER_SESSION / human-interaction), so a SERVER-ASSIGNED session/address is excused;
+ # a caller-supplied one (no context) still 422s at ingress.
+ session_ok = self.browser_session_id is None or _browser_session_is_server_assigned(info)
+ address_ok = self.browser_address is None or _browser_address_is_server_assigned(info)
+ if session_ok and address_ok:
+ return self
+ raise ValueError(BROWSER_TYPE_ATTACH_CONFLICT_MESSAGE)
+
@model_validator(mode="after")
def _reject_start_fresh_with_session(self) -> WorkflowRunRequest:
if self.start_fresh_browser and self.browser_session_id:
diff --git a/skyvern/schemas/workflows.py b/skyvern/schemas/workflows.py
index 5cf28bf10..50a4f2d9f 100644
--- a/skyvern/schemas/workflows.py
+++ b/skyvern/schemas/workflows.py
@@ -25,7 +25,7 @@ from skyvern.forge.sdk.workflow.models.run_limits import (
)
from skyvern.forge.sdk.workflow.models.validators import normalize_run_with
from skyvern.schemas.emails import EmailBodyFormat
-from skyvern.schemas.runs import GeoTarget, ProxyLocation, RunEngine
+from skyvern.schemas.runs import GeoTarget, ProxyLocation, RunEngine, normalize_browser_type
from skyvern.utils.secret_headers import mask_header_values
from skyvern.utils.strings import sanitize_identifier
from skyvern.utils.templating import replace_jinja_reference
@@ -1661,6 +1661,12 @@ class WorkflowCreateYAMLRequest(BaseModel):
cdp_connect_headers: dict[str, str] | None = None
status: WorkflowStatus = WorkflowStatus.published
run_with: str = "agent"
+ browser_type: str | None = Field(
+ default=None,
+ description="Browser engine for runs of this workflow, one of the supported browser types "
+ "(e.g. msedge, chrome, stealth-chromium). A workflow-run setting overrides this. "
+ "Null means the system default.",
+ )
ai_fallback: bool = True
cache_key: str | None = "default"
adaptive_caching: bool = False
@@ -1684,6 +1690,11 @@ class WorkflowCreateYAMLRequest(BaseModel):
def _normalize_run_with(cls, v: str | None) -> str:
return normalize_run_with(v)
+ @field_validator("browser_type", mode="before")
+ @classmethod
+ def _normalize_browser_type(cls, v: str | None) -> str | None:
+ return normalize_browser_type(v)
+
@field_validator("browser_profile_key", mode="before")
@classmethod
def _normalize_browser_profile_key(cls, v: str | None) -> str | None:
diff --git a/skyvern/services/block_service.py b/skyvern/services/block_service.py
index 5e0b8fb14..9d5469ee9 100644
--- a/skyvern/services/block_service.py
+++ b/skyvern/services/block_service.py
@@ -1,9 +1,10 @@
import typing as t
+from http import HTTPStatus
import structlog
from fastapi import BackgroundTasks, Request
-from skyvern.exceptions import OutputParameterNotFound, WorkflowNotFound
+from skyvern.exceptions import OutputParameterNotFound, SkyvernHTTPException, WorkflowNotFound
from skyvern.forge import app
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.db.enums import WorkflowRunTriggerType
@@ -11,8 +12,12 @@ from skyvern.forge.sdk.executor.factory import AsyncExecutorFactory
from skyvern.forge.sdk.schemas.organizations import Organization
from skyvern.forge.sdk.workflow.models.parameter import OutputParameter
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRequestBody, WorkflowRun
-from skyvern.schemas.runs import BlockRunRequest
+from skyvern.schemas.runs import BlockRunRequest, read_browser_type
from skyvern.services import workflow_service
+from skyvern.webeye.real_browser_manager import (
+ SelectedBrowserTypeUnsupportedError,
+ ensure_runtime_supports_browser_type,
+)
LOG = structlog.get_logger()
@@ -49,6 +54,14 @@ async def ensure_workflow_run(
) -> WorkflowRun:
context = skyvern_context.ensure_context()
+ # Fail fast before the block run is prepared/persisted: reject an explicit browser_type this runtime
+ # cannot honor with a 4xx (the same predicate and contract as the run_workflow ingress), rather than
+ # persisting the debugger run and only rejecting at launch. No-op when unset or on a supporting runtime.
+ try:
+ ensure_runtime_supports_browser_type(read_browser_type(block_run_request))
+ except SelectedBrowserTypeUnsupportedError as e:
+ raise SkyvernHTTPException(str(e), HTTPStatus.BAD_REQUEST) from e
+
legacy_workflow_request = WorkflowRequestBody(
data=block_run_request.parameters,
proxy_location=block_run_request.proxy_location,
@@ -57,6 +70,11 @@ async def ensure_workflow_run(
totp_verification_url=block_run_request.totp_url,
browser_session_id=block_run_request.browser_session_id,
browser_profile_id=block_run_request.browser_profile_id,
+ # Forward the explicit engine so the block run executes in the selected browser_type instead of
+ # dropping it and inheriting the workflow default (which mismatched BlockRunResponse's echo).
+ # BlockRunRequest already rejects browser_type + an attached session/address at ingress, so this
+ # never reaches the WorkflowRequestBody attach-conflict validator with both set.
+ browser_type=block_run_request.browser_type,
start_fresh_browser=block_run_request.start_fresh_browser,
reuse_browser_session=block_run_request.reuse_browser_session,
max_screenshot_scrolls=block_run_request.max_screenshot_scrolls,
diff --git a/skyvern/services/workflow_service.py b/skyvern/services/workflow_service.py
index 0c6549864..9d92535fa 100644
--- a/skyvern/services/workflow_service.py
+++ b/skyvern/services/workflow_service.py
@@ -1,9 +1,11 @@
import typing as t
+from http import HTTPStatus
import structlog
from fastapi import BackgroundTasks, Request
from skyvern.config import settings
+from skyvern.exceptions import SkyvernHTTPException
from skyvern.forge import app
from skyvern.forge.sdk.db.enums import BrowserSeedSource, WorkflowRunTriggerType
from skyvern.forge.sdk.executor.factory import AsyncExecutorFactory
@@ -14,14 +16,26 @@ from skyvern.forge.sdk.workflow.models.validators import drop_reserved_tag_value
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRequestBody, WorkflowRun
from skyvern.schemas.runs import (
BROWSER_ADDRESS_SERVER_ASSIGNED_CONTEXT_KEY,
+ BROWSER_SESSION_SERVER_ASSIGNED_CONTEXT_KEY,
RunStatus,
RunType,
WorkflowRunRequest,
WorkflowRunResponse,
+ read_browser_type,
+)
+from skyvern.webeye.real_browser_manager import (
+ SelectedBrowserTypeUnsupportedError,
+ ensure_runtime_supports_browser_type,
)
LOG = structlog.get_logger(__name__)
-_SERVER_ASSIGNED_BROWSER_ADDRESS_CONTEXT = {BROWSER_ADDRESS_SERVER_ASSIGNED_CONTEXT_KEY: True}
+# Reconstruction re-materializes the server's own persisted row (browser_type may coexist with a
+# server-generated session/address), so mark both as server-assigned to excuse the attach-conflict
+# validator — caller ingress, which never sets this context, is still rejected.
+_SERVER_ASSIGNED_BROWSER_ATTACHMENT_CONTEXT = {
+ BROWSER_ADDRESS_SERVER_ASSIGNED_CONTEXT_KEY: True,
+ BROWSER_SESSION_SERVER_ASSIGNED_CONTEXT_KEY: True,
+}
def workflow_request_body_from_existing_run(
@@ -59,11 +73,14 @@ def workflow_request_body_from_existing_run(
"browser_address": workflow_run.browser_address,
"run_with": workflow_run.run_with,
"ai_fallback": workflow_run.ai_fallback,
+ # Preserve the original run-level browser_type so a retry (manual or credential fallback)
+ # keeps the user's engine override instead of silently reverting to routing.
+ "browser_type": read_browser_type(workflow_run),
# Replayed tags may predate the reserved-value rule; drop those entries rather than
# letting the request-model validator fail the whole retry.
"run_metadata": drop_reserved_tag_values(run_metadata),
},
- context=_SERVER_ASSIGNED_BROWSER_ADDRESS_CONTEXT,
+ context=_SERVER_ASSIGNED_BROWSER_ATTACHMENT_CONTEXT,
)
@@ -170,6 +187,13 @@ async def run_workflow(
ignore_inherited_workflow_system_prompt: bool = False,
tag_write_context: TagWriteContext | None = None,
) -> WorkflowRun:
+ # Fail fast before the run is prepared/persisted: reject a run-level browser_type this runtime
+ # cannot honor with a 4xx, rather than accepting it and failing at launch. No-op when unset or on
+ # a runtime that supports an explicit selection (cloud).
+ try:
+ ensure_runtime_supports_browser_type(read_browser_type(workflow_request))
+ except SelectedBrowserTypeUnsupportedError as e:
+ raise SkyvernHTTPException(str(e), HTTPStatus.BAD_REQUEST) from e
workflow_run = await prepare_workflow(
workflow_id=workflow_id,
organization=organization,
@@ -258,8 +282,9 @@ async def get_workflow_run_response(
"browser_profile_id": None if fresh_browser else workflow_run.browser_profile_id,
"browser_session_id": None if fresh_browser else workflow_run.browser_session_id,
"start_fresh_browser": fresh_browser,
+ "browser_type": read_browser_type(workflow_run),
},
- context=_SERVER_ASSIGNED_BROWSER_ADDRESS_CONTEXT,
+ context=_SERVER_ASSIGNED_BROWSER_ATTACHMENT_CONTEXT,
),
errors=workflow_run_resp.errors,
step_count=workflow_run_resp.total_steps,
diff --git a/skyvern/webeye/real_browser_manager.py b/skyvern/webeye/real_browser_manager.py
index 47e4abc66..44ef46dcd 100644
--- a/skyvern/webeye/real_browser_manager.py
+++ b/skyvern/webeye/real_browser_manager.py
@@ -7,6 +7,7 @@ from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass, replace
from datetime import UTC, datetime
+from typing import TYPE_CHECKING
import structlog
@@ -17,6 +18,7 @@ from skyvern.exceptions import (
MissingBrowserState,
MissingBrowserStateForBrowserSession,
MissingOrganizationForBrowserSession,
+ SkyvernException,
)
from skyvern.forge import app
from skyvern.forge.sdk.api.files import resolve_run_download_id
@@ -30,7 +32,7 @@ from skyvern.forge.sdk.streaming.registries import (
stream_ref_active,
)
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRun
-from skyvern.schemas.runs import ProxyLocation, ProxyLocationInput
+from skyvern.schemas.runs import ProxyLocation, ProxyLocationInput, read_browser_type
from skyvern.webeye.browser_artifacts import DownloadBinding, RecordingPrefixSnapshot, VideoArtifact
from skyvern.webeye.browser_engine import (
BrowserEngineBootstrapError,
@@ -55,8 +57,64 @@ from skyvern.webeye.real_browser_state import RealBrowserState
from skyvern.webeye.session_cookies import persist_session_cookies
from skyvern.webeye.video_utils import prepare_recording_for_upload
+if TYPE_CHECKING:
+ from skyvern.forge.sdk.schemas.persistent_browser_sessions import PersistentBrowserType
+
LOG = structlog.get_logger()
+
+def to_persistent_session_browser_type(browser_type_value: str | None) -> PersistentBrowserType | None:
+ """Adapter at the persistent-session runtime boundary.
+
+ Maps the independent workflow/run ``BrowserType`` value into the PBS ``PersistentBrowserType``
+ runtime representation for persistent-session allocation. This is the one sanctioned conversion
+ point: the workflow/run domain never references ``PersistentBrowserType`` as its own type — it
+ passes its value through here. An unknown value or ``None`` returns ``None`` so the session keeps
+ the current routing behavior. The two enums stay distinct (value parity is guarded by tests).
+ """
+ from skyvern.forge.sdk.schemas.persistent_browser_sessions import PersistentBrowserType
+
+ if not browser_type_value:
+ return None
+ return PersistentBrowserType.from_source_browser_type(str(browser_type_value))
+
+
+# The cloud-only registry key under which the dynamic-browser creator is registered. Its presence is
+# the runtime capability that can actually honor a workflow/run browser_type selection (cloud dynamic
+# lane, or a cloud fixed-worker whose compliance wrapper reroutes there). Absent on OSS/self-host.
+_CLOUD_DYNAMIC_BROWSER_TYPE = "dynamic-browser"
+
+
+def runtime_supports_browser_type_selection() -> bool:
+ """Whether this runtime can honor an explicit workflow/run browser_type selection — i.e. the
+ cloud dynamic-browser creator is registered (cloud dynamic lane, or a cloud fixed-worker whose
+ compliance wrapper reroutes there). False on OSS/self-host. Reads the registry without mutating it;
+ it is the single source of truth for both the fail-closed guard and the options endpoint."""
+ return BrowserContextFactory._creators.get(_CLOUD_DYNAMIC_BROWSER_TYPE) is not None
+
+
+class SelectedBrowserTypeUnsupportedError(SkyvernException):
+ """A recognized workflow/run browser_type was selected on a runtime with no dynamic-browser
+ capability to honor it (OSS/self-host). Fail closed instead of silently launching the fixed
+ global browser and ignoring the selection."""
+
+ def __init__(self, browser_type: str) -> None:
+ super().__init__(
+ f"browser_type={browser_type!r} is not supported by this runtime: it has no dynamic-browser "
+ "capability to honor an explicit engine selection. Remove the browser_type setting or run on "
+ "Skyvern Cloud."
+ )
+
+
+def ensure_runtime_supports_browser_type(browser_type: str | None) -> None:
+ """Fail fast at API ingress: reject a browser_type this runtime cannot honor before any workflow or
+ run is persisted, instead of accepting it and only raising SelectedBrowserTypeUnsupportedError at
+ launch (200-on-create, then every run fails). No-op when unset or when the runtime supports an
+ explicit selection — the same predicate the launch-time guard and the options endpoint use."""
+ if browser_type is not None and not runtime_supports_browser_type_selection():
+ raise SelectedBrowserTypeUnsupportedError(str(browser_type))
+
+
_WORKFLOW_RUN_KEY_PREFIX = f"{WORKFLOW_RUN_PREFIX}_"
# Matched to the CDP proxy's own stamp throttle: the idle budget it feeds is minutes (MIN_TIMEOUT is
@@ -592,7 +650,19 @@ class RealBrowserManager(BrowserManager):
browser_session_id: str | None = None,
engine_run_key: str | None = None,
engine_workflow_run_id: str | None = None,
+ user_browser_type: str | None = None,
) -> BrowserState:
+ # Fail closed before any driver/browser launch: a recognized engine selection can only be
+ # honored where the cloud dynamic-browser creator is registered (cloud dynamic lane, or a
+ # cloud fixed-worker whose compliance wrapper reroutes there). On OSS/self-host that creator
+ # is absent, so the base factory would launch settings.BROWSER_TYPE and silently ignore the
+ # selection — refuse instead. Null/unrecognized selections keep the existing legacy behavior.
+ if (
+ to_persistent_session_browser_type(user_browser_type) is not None
+ and not runtime_supports_browser_type_selection()
+ ):
+ raise SelectedBrowserTypeUnsupportedError(str(user_browser_type))
+
run_key = engine_run_key or canonical_run_key(
workflow_run_id=workflow_run_id, task_id=task_id, script_id=script_id
)
@@ -650,6 +720,7 @@ class RealBrowserManager(BrowserManager):
browser_address_is_server_assigned=bool(context and context.browser_address_is_server_assigned),
browser_profile_id=browser_profile_id,
browser_session_id=browser_session_id,
+ user_browser_type=user_browser_type,
engine_selection=selection,
_reconcile_persistent_init_scripts=browser_session_id is not None,
)
@@ -1145,6 +1216,7 @@ class RealBrowserManager(BrowserManager):
browser_address=workflow_run.browser_address,
browser_profile_id=browser_profile_id,
browser_session_id=browser_session_id,
+ user_browser_type=read_browser_type(workflow_run),
)
if browser_session_id: