Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Add Claude Sonnet 5.5 LLM keys with Bedrock/Anthropic fallbacks; default GPT-6 Sol to medium effort (SKY-16907) (#8723)
Andrew Neilsona05d621b851d
diff --git a/.env.example b/.env.exampleindex c56809a6d..49dec8998 100644--- a/.env.example+++ b/.env.example@@ -100,7 +100,8 @@ YUTORI_TOOL_SET=""# OPENAI_GPT6_1_SOL_FLEX_WITH_FALLBACK,# OPENAI_GPT6_LUNA_FLEX_WITH_FALLBACK, ANTHROPIC_CLAUDE5.5_OPUS,# BEDROCK_ANTHROPIC_CLAUDE5.5_OPUS_INFERENCE_PROFILE,-# BEDROCK_ANTHROPIC_CLAUDE5.5_OPUS_WITH_FALLBACK,+# BEDROCK_ANTHROPIC_CLAUDE5.5_OPUS_WITH_FALLBACK, ANTHROPIC_CLAUDE5.5_SONNET,+# BEDROCK_ANTHROPIC_CLAUDE5.5_SONNET_INFERENCE_PROFILE,# XAI_GROK_4_5, ANTHROPIC_CLAUDE5_OPUS, ANTHROPIC_CLAUDE5.1_FABLE,# ANTHROPIC_CLAUDE5_FABLE, ANTHROPIC_CLAUDE4.7_OPUS,# ANTHROPIC_CLAUDE4.6_SONNET, GEMINI_3_PRO,diff --git a/skyvern/cli/llm_setup.py b/skyvern/cli/llm_setup.pyindex d85165615..b225199be 100644--- a/skyvern/cli/llm_setup.py+++ b/skyvern/cli/llm_setup.py@@ -149,6 +149,7 @@ def setup_llm_providers(env_path: Path | str | None = None) -> None:["ANTHROPIC_CLAUDE5_OPUS","ANTHROPIC_CLAUDE5.5_OPUS",+ "ANTHROPIC_CLAUDE5.5_SONNET","ANTHROPIC_CLAUDE5.1_FABLE","ANTHROPIC_CLAUDE5_FABLE","ANTHROPIC_CLAUDE4.7_OPUS",diff --git a/skyvern/config.py b/skyvern/config.pyindex da975bd3e..2ec0fa298 100644--- a/skyvern/config.py+++ b/skyvern/config.py@@ -588,17 +588,12 @@ class Settings(BaseSettings):TASK_V3_NAVIGATE_READINESS_TIMEOUT_MS: int = 20000# Workflows whose permanent id was born at or after this instant run their task blocks on Task V3# when the organization resolves to the self-serve billing tier (an unknown tier is not enrolled),- # bypassing WORKFLOW_TASK_V3_AB. None disables the rule (the OSS default). Setting it is not- # enough on its own: the rule fires only for runs whose TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT- # evaluation returns a conclusive true, so the cutoff stays inert until that flag enrols someone.- # Every off-state of that flag -- disabled, deleted, 0%, an excluding condition, an evaluation- # that raised, no flag provider at all -- leaves the run on the A/B, so there is no off-state that- # enrols. A naive value is read as UTC. Per-call platform workflows are excluded twice over -- by- # an auto_generated executing version, which covers the login, download_files, credential- # test-login and SDK endpoints, and by a per-call trigger kind, which covers the job recipe- # endpoints because those build a published definition. Enrolled runs are not randomized, so every- # per-arm read must exclude them by route_reason and read them against the unenrolled control cell- # instead.+ # bypassing WORKFLOW_TASK_V3_AB. None disables the rule (the OSS default), as does having no flag+ # provider; DISABLE_TASK_V3 still wins over it. A naive value is read as UTC. Per-call platform+ # workflows are excluded twice over -- by an auto_generated executing version, which covers the+ # login, download_files, credential test-login and SDK endpoints, and by a per-call trigger kind,+ # which covers the job recipe endpoints because those build a published definition. Enrolled runs+ # are not randomized, so every per-arm read must exclude them by route_reason.TASK_V3_DEFAULT_ENGINE_WORKFLOW_CUTOFF: datetime | None = None# VOLCENGINE (Doubao)diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.pyindex edce7d5fc..b2a851cc4 100644--- a/skyvern/forge/agent.py+++ b/skyvern/forge/agent.py@@ -3252,6 +3252,8 @@ class ForgeAgent:caller_known_urls=verdict_known_urls,label_secret_values=_label_secret_values,login_identifier_tokens=_login_identifier_tokens,+ # A block that completes on a download is not done by its one action.+ single_action_block=isinstance(task_block, ActionBlock) and not task_block.complete_on_download,)finally:if context and credential_parameter_key is not None:diff --git a/skyvern/forge/sdk/api/llm/api_handler_factory.py b/skyvern/forge/sdk/api/llm/api_handler_factory.pyindex 5fc19ff4f..e3a9fecdc 100644--- a/skyvern/forge/sdk/api/llm/api_handler_factory.py+++ b/skyvern/forge/sdk/api/llm/api_handler_factory.py@@ -1507,11 +1507,14 @@ class LLMAPIHandlerFactory:"anthropic/claude-opus-5","anthropic/claude-opus-5-5","bedrock/us.anthropic.claude-opus-5-5",+ "anthropic/claude-sonnet-5-5",+ "bedrock/global.anthropic.claude-sonnet-5-5","anthropic-claude-opus-4-8","anthropic-claude-fable-5","anthropic-claude-fable-5-1","anthropic-claude-opus-5","anthropic-claude-opus-5-5",+ "anthropic-claude-sonnet-5-5",}@staticmethoddiff --git a/skyvern/forge/sdk/api/llm/config_registry.py b/skyvern/forge/sdk/api/llm/config_registry.pyindex bf18c65cf..9e4380f8b 100644--- a/skyvern/forge/sdk/api/llm/config_registry.py+++ b/skyvern/forge/sdk/api/llm/config_registry.py@@ -23,8 +23,8 @@ GPT6_MODEL_NAMES: dict[str, str] = {}GPT6_REASONING_EFFORT: dict[str, str] = {"astra": "xhigh",- "sol": "xhigh",- "1_sol": "xhigh",+ "sol": "medium",+ "1_sol": "medium","luna": settings.GPT6_LUNA_REASONING_EFFORT,}XAI_GROK_4_5_MODEL = "xai/grok-4.5"@@ -709,6 +709,17 @@ if settings.ENABLE_ANTHROPIC:temperature=1,),)+ LLMConfigRegistry.register_config(+ "ANTHROPIC_CLAUDE5.5_SONNET",+ LLMConfig(+ "anthropic/claude-sonnet-5-5",+ ["ANTHROPIC_API_KEY"],+ supports_vision=True,+ add_assistant_prefix=False,+ max_completion_tokens=128000,+ temperature=1,+ ),+ )if settings.ENABLE_BEDROCK:# Supported through AWS IAM authenticationLLMConfigRegistry.register_config(@@ -861,6 +872,17 @@ if settings.ENABLE_BEDROCK:temperature=1,),)+ LLMConfigRegistry.register_config(+ "BEDROCK_ANTHROPIC_CLAUDE5.5_SONNET_INFERENCE_PROFILE",+ LLMConfig(+ "bedrock/global.anthropic.claude-sonnet-5-5",+ ["AWS_REGION"],+ supports_vision=True,+ add_assistant_prefix=False,+ max_completion_tokens=128000,+ temperature=1,+ ),+ )if settings.ENABLE_AZURE:diff --git a/skyvern/forge/sdk/experimentation/workflow_block_engine.py b/skyvern/forge/sdk/experimentation/workflow_block_engine.pyindex dde5c394e..4fdca7ee5 100644--- a/skyvern/forge/sdk/experimentation/workflow_block_engine.py+++ b/skyvern/forge/sdk/experimentation/workflow_block_engine.py@@ -24,7 +24,6 @@ LOG = structlog.get_logger()WORKFLOW_TASK_V3_AB_FLAG = "WORKFLOW_TASK_V3_AB"DISABLE_TASK_V3_FLAG = "DISABLE_TASK_V3"-TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT_FLAG = "TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT"# Trigger kinds whose run executes a workflow the platform minted for that one request rather than# one a customer built. The job-recipe endpoints are the whole set today: each call creates a fresh@@ -53,36 +52,6 @@ class WorkflowBlockEngineRouteReason(StrEnum):flag_error = "flag_error"-class NewWorkflowDefaultRollout(StrEnum):- """How ``TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT`` answered for a run the v3 default would enrol.-- Only ``enrolled`` -- a conclusive True -- lets the rule fire. ``not_enrolled`` is a conclusive- False: the flag is inactive, the run fell outside the percentage, or a condition excluded it.- ``undefined`` means the key never resolved at all: nobody created it, or local evaluation has no- snapshot row for it yet. ``error`` means the evaluation raised. The last three are logged apart- from each other because only ``not_enrolled`` is a randomized cell -- a read that wants this- rule's control must pin that value, not the boolean.- """-- enrolled = "enrolled"- not_enrolled = "not_enrolled"- undefined = "undefined"- error = "error"---# Every resolution but a conclusive True leaves the run on the A/B path, so every off-state of the-# flag -- inactive, deleted, 0%, a condition that excluded the run, an evaluation that raised -- turns-# the rule off. An inactive flag is the one that has to be safe: posthog's local evaluator answers a-# conclusive False for it (``_compute_flag_locally``, "if not active: return False"), which is the-# gesture an operator reaches for mid-incident. Derived from the enum so a resolution added later-# leaves the run on the A/B instead of enrolling it.-_NOT_ENROLLED_RESOLUTIONS = frozenset(NewWorkflowDefaultRollout) - {NewWorkflowDefaultRollout.enrolled}---def _rollout_enrols(rollout: NewWorkflowDefaultRollout | None) -> bool:- return rollout is not None and rollout not in _NOT_ENROLLED_RESOLUTIONS--def _arm_label(override: RunEngine | None) -> str:"""The arm both the routing line and the duration log report, derived once from the engine the runroutes on: only an explicit v3 override is treatment, so a future non-v3 override on that field@@ -111,7 +80,6 @@ class WorkflowBlockEngineArmDecision:route_reason: WorkflowBlockEngineRouteReason | None = Nonebilling_tier: BillingTier | None = None- new_workflow_default_rollout_resolution: NewWorkflowDefaultRollout | None = NoneNO_ARM_DECISION = WorkflowBlockEngineArmDecision()@@ -236,56 +204,6 @@ async def _ab_flag_puts_run_in_treatment()-async def _resolve_new_workflow_default_rollout(- provider: BaseExperimentationProvider,- *,- workflow_run_id: str,- organization_id: str | None,- workflow_permanent_id: str | None,- billing_tier: BillingTier,-) -> NewWorkflowDefaultRollout:- """How the rollout flag answered for a run the new-workflow v3 default would otherwise enrol.-- This flag is what enrols: the share it does not enrol continues down ``WORKFLOW_TASK_V3_AB``- exactly as if the rule did not exist, which is where this population's concurrent control comes- from. It is also the only lever that stops the rule for less than everybody -- the cutoff is a- setting and needs a restart, and a condition on ``WORKFLOW_TASK_V3_AB`` cannot reach a run that- never evaluates it. Turning it off de-enrols rather than forcing v1: an unenrolled run can still- be treated by the A/B, so ``DISABLE_TASK_V3`` is the lever for getting an organization off v3.-- ``resolve_feature_flag_strict`` rather than the boolean resolver, so an evaluation that raised is- labelled rather than collapsed: both PostHog providers swallow one into ``None`` and ``bool()`` it- to ``False``, which would report an error as a real "outside the percentage".-- Only a conclusive ``True`` enrols. ``False``, ``None`` and a raised evaluation all leave the run on- the A/B, so every off-gesture on this flag -- disable, delete, 0%, an excluding condition -- turns- the rule off, and the cutoff does nothing until the flag resolves ``True`` for someone. A- condition on it must be written on person properties: the arm-resolving processes evaluate- PostHog locally, and a cohort, group or flag-dependency condition resolves to ``None``, which- enrols nobody.- """- try:- resolved = await provider.resolve_feature_flag_strict(- TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT_FLAG,- workflow_run_id,- properties={- "organization_id": organization_id,- "workflow_permanent_id": workflow_permanent_id,- BILLING_TIER_PROPERTY: billing_tier.value,- },- )- except Exception:- LOG.warning(- "Failed to evaluate the new-workflow v3 default rollout; leaving this run on the A/B",- workflow_run_id=workflow_run_id,- exc_info=True,- )- return NewWorkflowDefaultRollout.error- if resolved is None:- return NewWorkflowDefaultRollout.undefined- return NewWorkflowDefaultRollout.enrolled if resolved else NewWorkflowDefaultRollout.not_enrolled--async def resolve_workflow_block_engine_arm(context: skyvern_context.SkyvernContext,*,@@ -308,11 +226,7 @@ async def resolve_workflow_block_engine_arm(A self-serve organization's workflow born at or after``settings.TASK_V3_DEFAULT_ENGINE_WORKFLOW_CUTOFF`` takes v3 without the percentage beingconsulted, so those runs are marked ``new_self_serve_workflow_default`` for every per-arm read to- exclude. ``TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT``, read only for the runs that rule would enrol,- is what enrols them; the share it leaves alone continues down the A/B, which is where this- population's concurrent control and its scoped kill come from. The rule fires only on a- conclusive True, so the cutoff is inert until the flag resolves True for someone, and disabling,- deleting or zeroing the flag turns the rule off.+ exclude. No flag gates the rule: ``DISABLE_TASK_V3`` or unsetting the cutoff turns it off.``workflow_status`` is the status of the version this run executes and ``trigger_type`` is howthe run was launched. Together they are what separates a workflow a customer keeps from the@@ -336,7 +250,6 @@ async def resolve_workflow_block_engine_arm(run_is_eligible = ineligibility_reason is Nonebilling_tier: BillingTier | None = Noneroute_reason = WorkflowBlockEngineRouteReason.ineligible- rollout: NewWorkflowDefaultRollout | None = Nonetry:if run_is_eligible:# The kill switch, shared with the dispatch gate via task_v3_disabled so both@@ -370,19 +283,8 @@ async def resolve_workflow_block_engine_arm(and await _workflow_is_new_for_v3_default(workflow_permanent_id, organization_id))if takes_new_workflow_default:- # Read only for the runs the rule would enrol, so the A/B population is never- # exposed to this flag and its bucketing is unchanged.- rollout = await _resolve_new_workflow_default_rollout(- provider,- workflow_run_id=workflow_run_id,- organization_id=organization_id,- workflow_permanent_id=workflow_permanent_id,- billing_tier=billing_tier,- )- if takes_new_workflow_default and _rollout_enrols(rollout):# A workflow born at or after the cutoff runs its task blocks on v3 by- # default, so the percentage knob is never consulted: the unenrolled share the- # A/B then routes to control is the only concurrent control these runs have.+ # default, so the percentage knob is never consulted.override = RunEngine.skyvern_v3route_reason = WorkflowBlockEngineRouteReason.new_self_serve_workflow_defaultelse:@@ -414,7 +316,6 @@ async def resolve_workflow_block_engine_arm(decision = WorkflowBlockEngineArmDecision(route_reason=route_reason,billing_tier=billing_tier,- new_workflow_default_rollout_resolution=rollout,)context.workflow_block_engine_override = overridecontext.workflow_block_engine_arm_decision = decision@@ -427,17 +328,6 @@ async def resolve_workflow_block_engine_arm(workflow_permanent_id=workflow_permanent_id,arm=_arm_label(override),route_reason=engine_arm_log_value(route_reason),- # True only for a run this rule enrolled, which is every run it treated: the rule's- # control cell is the unenrolled share the A/B then routed to control, so a read of the- # rule compares route_reason=new_self_serve_workflow_default against- # new_workflow_default_rollout_resolution=not_enrolled intersected with- # flag_bucket_control -- an unenrolled run re-enters the A/B and can be treated there.- new_workflow_default_rollout=_rollout_enrols(rollout),- # None whenever the rollout flag was not consulted. The three non-enrolling resolutions- # are indistinguishable in the boolean above, and only not_enrolled is a randomized cell,- # so both a check of whether the flag is answering at all and the rule's control cell read- # this field instead.- new_workflow_default_rollout_resolution=engine_arm_log_value(rollout),run_is_eligible=run_is_eligible,ineligibility_reason=ineligibility_reason,# None whenever the A/B was never consulted -- an ineligible run, or one the kill switchdiff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex 198f62cb5..3fb3c97ed 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -12919,9 +12919,6 @@ class WorkflowService:# is what the non-enterprise ramp steps on.route_reason=engine_arm_log_value(arm_decision.route_reason),billing_tier=engine_arm_log_value(arm_decision.billing_tier),- new_workflow_default_rollout_resolution=engine_arm_log_value(- arm_decision.new_workflow_default_rollout_resolution- ),)# Run minutes measure compute. A run finalized without ever reaching# `running` held no pod, and the created_at fallback above would bill itsdiff --git a/skyvern/forge/taskv3/engine.py b/skyvern/forge/taskv3/engine.pyindex efdedc2bd..4c519b0eb 100644--- a/skyvern/forge/taskv3/engine.py+++ b/skyvern/forge/taskv3/engine.py@@ -325,6 +325,7 @@ async def run_task_v3_agent_loop(unlisted_reask_criteria_untrusted: bool = False,# The workflow system prompt reads a page-derived value, so the re-ask shows it as untrusted data.unlisted_reask_instructions_untrusted: bool = False,+ single_action_block: bool = False,) -> LoopOutcome:"""Run one Task V3 task to completion against `page`, returning the loop outcome.@@ -633,6 +634,7 @@ async def run_task_v3_agent_loop(semantic_commit_stats=semantic_commit_stats,refuse_input_entry=refuse_input_entry,tool_trail=tool_trail,+ single_action_block=single_action_block,)finally:# The context outlives this run; a signal raised as the loop was cancelled must not firediff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.pyindex 261745d25..d96ff5b3d 100644--- a/skyvern/forge/taskv3/loop.py+++ b/skyvern/forge/taskv3/loop.py@@ -3175,6 +3175,9 @@ class LoopState:# has been submitted; entering one that has spent CREDENTIAL_SUBMIT_BUDGET is refused.credentials_entered: set[str] = field(default_factory=set)credential_submits: dict[str, int] = field(default_factory=dict)+ # A single-action block's completion is offered through the finish tool at most once: a guard that+ # holds a verdict only once would pass a second offer the model never saw it hold.+ block_completion_offered: bool = Falseasync def run_agent_tool_loop(@@ -3245,6 +3248,9 @@ async def run_agent_tool_loop(# author input, so every FILL_TOOLS call is refused at dispatch.refuse_input_entry: bool = False,tool_trail: ToolTrail | None = None,+ # A block whose contract is one action: once one succeeded, a follow-up the step cap refuses offers+ # finish(completed) instead of failing the block, as the step engine completes it after that step.+ single_action_block: bool = False,) -> LoopOutcome:tool_by_name = {tool.name: tool for tool in tools}st = LoopState(@@ -4158,6 +4164,32 @@ async def run_agent_tool_loop()step_cap_trip = f"Reached the maximum steps ({st.max_action_steps})"_append_skipped_tool_results(st.messages, tool_calls[idx:], "action-step budget reached")+ finish_spec = tool_by_name.get("finish")+ block_refusal: str | None = None+ if (+ single_action_block+ and st.billable_actions+ and finish_spec is not None+ and not st.block_completion_offered+ ):+ st.block_completion_offered = True+ block_reason = (+ f"performed the block's action ({st.billable_actions[0]}); "+ "a further action was past the block's step limit"+ )+ # Through the real handler, so every guard on a completed verdict still applies.+ try:+ block_finish = await finish_spec.handler({"status": "completed", "reason": block_reason})+ except Exception:+ LOG.warning("taskv3 block completion finish raised", exc_info=True)+ block_finish = ToolResult.error("")+ if activity is not None:+ activity.held_verdict_batch_skip = False+ if block_finish.status == "ok" and (block_finish.data or {}).get("status") == "completed":+ st.outcome = LoopOutcome("completed", block_reason)+ break+ if block_finish.status == "error":+ block_refusal = block_finish.content# Unlike the mid-batch max_tool_calls check above, the step gate is NOT special-cased# away once the final turn is granted: a billable dispatch on the granted turn still# hits it, which is the honest exit the grant exists to produce.@@ -4192,9 +4224,10 @@ async def run_agent_tool_loop(tool_calls_remaining=None if activity is None else activity.tool_calls_remaining,tokens_remaining=None if activity is None else activity.tokens_remaining,)- st.messages.append(- {"role": "user", "content": _budget_exhausted_observation(step_cap_trip, activity)}- )+ observation = _budget_exhausted_observation(step_cap_trip, activity)+ if block_refusal:+ observation += f"\n\nThe block's completion was not accepted: {block_refusal}"+ st.messages.append({"role": "user", "content": observation})break# Submit-shaped actions (the failure-evidence predicate, minus captcha) are reported BEFORE# dispatch, since after it the page may be the confirmation page. A failure here never failsdiff --git a/tests/unit/_workflow_block_engine_fakes.py b/tests/unit/_workflow_block_engine_fakes.pyindex 9126d6712..6db4b8447 100644--- a/tests/unit/_workflow_block_engine_fakes.py+++ b/tests/unit/_workflow_block_engine_fakes.py@@ -16,10 +16,7 @@ from skyvern.forge.sdk.core.skyvern_context import SkyvernContextfrom skyvern.forge.sdk.db.enums import WorkflowRunTriggerTypefrom skyvern.forge.sdk.experimentation.billing_tier import BillingTierfrom skyvern.forge.sdk.experimentation.providers import BaseExperimentationProvider-from skyvern.forge.sdk.experimentation.workflow_block_engine import (- TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT_FLAG,- resolve_workflow_block_engine_arm,-)+from skyvern.forge.sdk.experimentation.workflow_block_engine import resolve_workflow_block_engine_armfrom skyvern.forge.sdk.workflow.models.block import V3AbIneligibleReasonfrom skyvern.schemas.workflows import WorkflowStatusfrom tests.unit.test_agent_task_v3 import stub_workflow_block_engine_app@@ -34,11 +31,6 @@ class FakeExperimentationProvider(BaseExperimentationProvider):swallow it into ``None`` and ``bool()`` it to ``False``, so only ``_resolve_feature_flag_strict``can tell a failure from a real ``False``. A fake that raised from ``_is_feature_enabled`` wouldverify a shape no provider has, and would let a fail-safe that is inverted in production pass.-- ``False`` here is the answer an INACTIVE flag gives: posthog's local evaluator returns a- conclusive ``False`` for one before it reads any filter, so "disable the flag" and "roll it to 0%"- arrive as the same value, and a rule that fired on ``False`` would enrol everybody the moment an- operator switched the flag off."""def __init__(@@ -50,11 +42,6 @@ class FakeExperimentationProvider(BaseExperimentationProvider):) -> None:super().__init__()self.flags = dict(flags or {})- # The rule fires only on a conclusive True, so a fake that did not mention this flag would- # answer "undefined" and quietly take every enrolment test in this file off the rule and onto- # the A/B path, where control and an unenrolled run look identical. Tests that want the other- # resolutions say so, with a False here or with strict_error_flags/unresolvable_flags.- self.flags.setdefault(TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT_FLAG, True)self.calls: list[tuple[str, str, dict | None]] = []self.raise_error = raise_errorself.strict_error_flags = set(strict_error_flags or ())diff --git a/tests/unit/test_agent_task_v3.py b/tests/unit/test_agent_task_v3.pyindex 3cd0bca30..cd2c6d1f9 100644--- a/tests/unit/test_agent_task_v3.py+++ b/tests/unit/test_agent_task_v3.py@@ -4827,6 +4827,53 @@ async def test_execute_task_v3_failed_run_carries_failure_category(assert update_kwargs.get("failure_category")+ ("block_cls", "complete_on_download", "single_action"),+ [(ActionBlock, False, True), (ActionBlock, True, False), (TaskBlock, False, False)],+ ids=["action", "action_complete_on_download", "task"],+)+async def test_execute_task_v3_action_block_budget_exit_is_not_converted_after_the_loop(+ monkeypatch: pytest.MonkeyPatch, block_cls: type[BaseTaskBlock], complete_on_download: bool, single_action: bool+) -> None:+ # The loop alone offers an action block's completion, through the finish tool's guards; a step-cap exit it+ # returns means a guard refused that completion, so it stays failed. A download-completing block is not+ # done by its one action.+ outcome = LoopOutcome(+ status="budget_exhausted", reason="cap", cap_trip="Reached the maximum steps (1)", billable_actions=["click"]+ )+ overrides: dict[str, Any] = {"complete_on_download": True} if complete_on_download else {}+ _step, task, loop_mock, _post = await _run_execute_task_v3(+ monkeypatch,+ outcome,+ task_block=_make_block(block_cls, **overrides),+ data_extraction_goal=None,+ extracted_information_schema=None,+ )+ assert task.status == TaskStatus.failed+ assert loop_mock.call_args.kwargs["single_action_block"] is single_action+++async def test_execute_task_v3_action_block_completion_still_passes_the_completion_gate(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ outcome = LoopOutcome(+ status="completed",+ reason="performed the block's action (click); a further action was past the block's step limit",+ billable_actions=["click"],+ )+ _step, task, _loop_mock, _post = await _run_execute_task_v3(+ monkeypatch,+ outcome,+ task_block=_make_block(ActionBlock),+ completion_gate_vetoes=True,+ data_extraction_goal=None,+ extracted_information_schema=None,+ )+ assert task.status == TaskStatus.failed++@pytest.mark.asyncioasync def test_execute_task_v3_budget_exit_carries_typed_category_and_partial_output(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/unit/test_taskv3_engine.py b/tests/unit/test_taskv3_engine.pyindex e2a03731f..e6bc4a2e9 100644--- a/tests/unit/test_taskv3_engine.py+++ b/tests/unit/test_taskv3_engine.py@@ -242,6 +242,31 @@ async def test_engine_wires_budget_and_retry_defaults(monkeypatch: pytest.Monkeyassert captured["retryable_call_exceptions"] == (LLMProviderErrorRetryableTask,)[email protected]("single_action_block", [True, False])+async def test_engine_forwards_single_action_block_to_the_loop(+ monkeypatch: pytest.MonkeyPatch, single_action_block: bool+) -> None:+ from skyvern.forge.taskv3 import engine as engine_mod+ from skyvern.forge.taskv3.loop import LoopOutcome++ captured: dict[str, object] = {}++ async def _capture(**kwargs: object) -> LoopOutcome:+ captured.update(kwargs)+ return LoopOutcome(status="completed", reason="ok")++ monkeypatch.setattr(engine_mod, "run_agent_tool_loop", _capture)+ await run_task_v3_agent_loop(+ page_provider=_fixed_page_provider(_FakePage()),+ llm_caller=_ScriptedCaller([]),+ goal="x",+ single_action_block=single_action_block,+ )++ assert captured["single_action_block"] is single_action_block++def test_runaway_backstops_scale_with_action_step_budget() -> None:# No action-step budget -> the guards are the engine's fixed defaults.defaults = (DEFAULT_MAX_TURNS, DEFAULT_MAX_TOOL_CALLS, engine_mod.DEFAULT_MAX_TOKENS)diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.pyindex cad55f58f..7c81c127d 100644--- a/tests/unit/test_taskv3_loop.py+++ b/tests/unit/test_taskv3_loop.py@@ -995,6 +995,81 @@ async def test_spent_grant_caught_at_the_step_gate_reports_the_granting_cap() ->assert "turn budget" in outcome.reason[email protected]("single_action_block", [True, False], ids=["single_action", "multi_action"])[email protected]("cap", ["step_cap", "runaway"])[email protected]("acted", [True, False], ids=["acted", "no_action"])+async def test_single_action_block_completes_when_its_step_cap_refuses_a_follow_up(+ single_action_block: bool, cap: str, acted: bool+) -> None:+ # A single-action block's contract is one action; a follow-up its step cap refused is not the block+ # failing. Every other budget exit, and any block that never landed its action, stays budget_exhausted.+ click_calls: list[tuple[str, dict[str, Any]]] = []+ click = (_recording_tool if acted else _erroring_tool)("click", click_calls, billable=True)+ caps: dict[str, Any] = {"max_action_steps": 1} if cap == "step_cap" else {"max_turns": 1}+ script = [[("click", {})], [("click", {})], [("click", {})]]+ outcome, _ = await _run(script, [click, make_finish_tool()], single_action_block=single_action_block, **caps)++ if single_action_block and cap == "step_cap" and acted:+ assert outcome.status == "completed"+ assert "click" in outcome.reason+ assert outcome.cap_trip is None+ assert len(click_calls) == 1+ else:+ assert outcome.status == "budget_exhausted"+++async def test_single_action_block_completion_refused_by_a_finish_guard_stays_budget_exhausted() -> None:+ # The block's completion is offered through the finish tool, so a guard that would refuse the model's own+ # finish(completed) refuses it too, and the model is told why on its granted final turn.+ refusal = "the verification code step has not finished"++ async def blocker(status: str) -> str | None:+ return refusal if status == "completed" else None++ click_calls: list[tuple[str, dict[str, Any]]] = []+ click = _recording_tool("click", click_calls, billable=True)+ script = [[("click", {})], [("click", {})], [("click", {})]]+ outcome, caller = await _run(+ script,+ [click, make_finish_tool(verification_blocker=blocker)],+ single_action_block=True,+ max_action_steps=1,+ )++ assert outcome.status == "budget_exhausted"+ assert outcome.cap_trip == "Reached the maximum steps (1)"+ assert any(m.get("role") == "user" and refusal in str(m.get("content")) for m in caller.message_history)+++async def test_single_action_block_completion_is_offered_once_even_when_its_guard_clears() -> None:+ # A guard that refused the block's completion (e.g. a submission still pending) may clear by the granted+ # final turn; a second cap trip there must end budget_exhausted, not get a second completion offer.+ offers: list[str] = []++ async def blocker(status: str) -> str | None:+ if status != "completed":+ return None+ offers.append(status)+ return "the submission is still pending" if len(offers) == 1 else None++ click_calls: list[tuple[str, dict[str, Any]]] = []+ click = _recording_tool("click", click_calls, billable=True)+ script = [[("click", {})], [("click", {})], [("click", {})]]+ outcome, _ = await _run(+ script,+ [click, make_finish_tool(verification_blocker=blocker)],+ single_action_block=True,+ max_action_steps=1,+ )++ assert outcome.status == "budget_exhausted"+ assert outcome.cap_trip == "Reached the maximum steps (1)"+ assert len(offers) == 1++@pytest.mark.asyncioasync def test_step_gate_on_the_granted_turn_salvages_a_staged_finish_output() -> None:# The granted turn batches an over-cap action AND a finish: the refused action voids thediff --git a/tests/unit/test_workflow_block_engine.py b/tests/unit/test_workflow_block_engine.pyindex 18a15ead8..9207ad8c3 100644--- a/tests/unit/test_workflow_block_engine.py+++ b/tests/unit/test_workflow_block_engine.py@@ -23,9 +23,7 @@ from skyvern.forge.sdk.experimentation.billing_tier import BILLING_TIER_PROPERTYfrom skyvern.forge.sdk.experimentation.providers import BaseExperimentationProvider, NoOpExperimentationProviderfrom skyvern.forge.sdk.experimentation.workflow_block_engine import (DISABLE_TASK_V3_FLAG,- TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT_FLAG,WORKFLOW_TASK_V3_AB_FLAG,- NewWorkflowDefaultRollout,WorkflowBlockEngineRouteReason,_as_utc,resolve_workflow_block_engine_arm,@@ -1081,9 +1079,7 @@ async def test_new_self_serve_workflow_defaults_to_v3_without_consulting_the_ab_) -> None:# The whole point of the rule: the percentage knob is bypassed, so a flag sitting at 0% (or a# bucket that landed on control) cannot take a new self-serve workflow back to v1.- provider = FakeExperimentationProvider(- {WORKFLOW_TASK_V3_AB_FLAG: False, TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT_FLAG: True}- )+ provider = FakeExperimentationProvider({WORKFLOW_TASK_V3_AB_FLAG: False})run_id = "wr_new_self_serve_enrolled"resolution = await resolve_arm(scoped_context,@@ -1096,139 +1092,12 @@ async def test_new_self_serve_workflow_defaults_to_v3_without_consulting_the_ab_assert scoped_context.workflow_block_engine_override == RunEngine.skyvern_v3assert _make_block(TaskBlock, label="new_wf").resolve_engine(run_id) == RunEngine.skyvern_v3- # The percentage knob is still never consulted for an enrolled run.- assert consulted_flags(provider) == [DISABLE_TASK_V3_FLAG, TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT_FLAG]+ # Only the kill switch is read: no rollout flag and no percentage knob gate an eligible run.+ assert consulted_flags(provider) == [DISABLE_TASK_V3_FLAG]assert resolution.log["route_reason"] == WorkflowBlockEngineRouteReason.new_self_serve_workflow_default- assert resolution.log["new_workflow_default_rollout"] is True- assert resolution.log["new_workflow_default_rollout_resolution"] == NewWorkflowDefaultRollout.enrolledassert resolution.log["billing_tier"] == BillingTier.SELF_SERVE.value- ("ab_flag", "expected_override", "expected_reason"),- [- (True, RunEngine.skyvern_v3, WorkflowBlockEngineRouteReason.flag_bucket_treatment),- (False, None, WorkflowBlockEngineRouteReason.flag_bucket_control),- ],-)-async def test_an_unenrolled_new_workflow_is_bucketed_by_the_ab_as_if_the_rule_did_not_exist(- scoped_context: SkyvernContext,- v3_default_cutoff: datetime,- ab_flag: bool,- expected_override: RunEngine | None,- expected_reason: WorkflowBlockEngineRouteReason,-) -> None:- # A conclusive False is what an operator's fastest off-gesture produces: posthog's local evaluator- # answers False for an INACTIVE flag before it reads any filter, and the same value comes back for- # a run outside the percentage or excluded by a condition. Enrolling on it would put 100% of this- # population on v3 with the control cell zeroed at the exact moment someone switched the rollout- # off, and the log would read like a rule that was not firing. So False leaves the run in the- # ordinary bucketing, both ways -- which is also where this population's concurrent control and- # its scoped kill come from, the cutoff being a setting that needs a restart and a condition on- # WORKFLOW_TASK_V3_AB being unable to reach a run that never evaluates it.- provider = FakeExperimentationProvider(- {WORKFLOW_TASK_V3_AB_FLAG: ab_flag, TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT_FLAG: False}- )- resolution = await resolve_arm(- scoped_context,- provider,- workflow_run_id=f"wr_not_enrolled_{ab_flag}",- ineligibility_reason=None,- billing_tier=BillingTier.SELF_SERVE,- first_version_created_at=v3_default_cutoff.replace(tzinfo=None) + timedelta(days=1),- )-- assert scoped_context.workflow_block_engine_override == expected_override- assert resolution.log["route_reason"] == expected_reason- assert resolution.log["new_workflow_default_rollout"] is False- assert resolution.log["new_workflow_default_rollout_resolution"] == NewWorkflowDefaultRollout.not_enrolled- rollout_call = next(call for call in provider.calls if call[0] == TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT_FLAG)- # Bucketed per run, and carrying the two properties a scoped condition is written against: holding- # one organization or one workflow out of the rollout is what the runbook promises as the fast- # lever.- assert rollout_call[1] == f"wr_not_enrolled_{ab_flag}"- assert rollout_call[2] == {- "organization_id": "org_1",- "workflow_permanent_id": "wpid_1",- BILLING_TIER_PROPERTY: BillingTier.SELF_SERVE.value,- }---async def test_a_failing_rollout_evaluation_leaves_the_run_on_the_ab_path(- scoped_context: SkyvernContext, v3_default_cutoff: datetime-) -> None:- # An evaluation that raised is not an answer, and treating it as one would enrol a population- # whose fastest kill is the flag that just failed. It also must not be reported as a real- # "outside the percentage": the error resolution is what separates the two on the log. Only- # reachable through the strict resolver -- the boolean one swallows the error into None and- # bool()s it to False.- provider = FakeExperimentationProvider(- {WORKFLOW_TASK_V3_AB_FLAG: False}, strict_error_flags={TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT_FLAG}- )- resolution = await resolve_arm(- scoped_context,- provider,- workflow_run_id="wr_rollout_down",- ineligibility_reason=None,- billing_tier=BillingTier.SELF_SERVE,- first_version_created_at=v3_default_cutoff.replace(tzinfo=None) + timedelta(days=1),- )-- assert scoped_context.workflow_block_engine_override is None- assert resolution.log["route_reason"] == WorkflowBlockEngineRouteReason.flag_bucket_control- assert resolution.log["new_workflow_default_rollout"] is False- assert resolution.log["new_workflow_default_rollout_resolution"] == NewWorkflowDefaultRollout.error- assert WORKFLOW_TASK_V3_AB_FLAG in consulted_flags(provider)- # A rollout that stopped answering must not be silent: an operator reading a quiet- # new_self_serve_workflow_default needs this warning and the resolution field above to tell a- # broken evaluation from a rollout nobody enabled.- assert [call.kwargs.get("workflow_run_id") for call in resolution.warnings] == ["wr_rollout_down"]--- ("ab_flag", "expected_override", "expected_reason"),- [- (True, RunEngine.skyvern_v3, WorkflowBlockEngineRouteReason.flag_bucket_treatment),- (False, None, WorkflowBlockEngineRouteReason.flag_bucket_control),- ],-)-async def test_an_unresolvable_rollout_flag_leaves_the_run_on_the_ab_path(- scoped_context: SkyvernContext,- v3_default_cutoff: datetime,- ab_flag: bool,- expected_override: RunEngine | None,- expected_reason: WorkflowBlockEngineRouteReason,-) -> None:- # The arm-resolving processes evaluate PostHog locally against a snapshot, which answers None --- # not False, not an error -- for a flag key it has no row for; so does a cutoff set before anyone- # created the flag, and so does a condition local evaluation cannot answer. Enrolling on that- # would make the cutoff alone a 100%-v3 cohort with no concurrent control, and would bypass the- # organization exclusions this rollout's own conditions carry. So an unresolved flag leaves the- # run in the ordinary bucketing, both ways -- and the resolution field still separates "no flag"- # from a rollout that answered, which is what an operator reads after an enable.- provider = FakeExperimentationProvider(- {WORKFLOW_TASK_V3_AB_FLAG: ab_flag},- unresolvable_flags={TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT_FLAG},- )- resolution = await resolve_arm(- scoped_context,- provider,- workflow_run_id=f"wr_rollout_undefined_{ab_flag}",- ineligibility_reason=None,- billing_tier=BillingTier.SELF_SERVE,- first_version_created_at=v3_default_cutoff.replace(tzinfo=None) + timedelta(days=1),- )-- assert scoped_context.workflow_block_engine_override == expected_override- assert resolution.log["route_reason"] == expected_reason- assert resolution.log["new_workflow_default_rollout"] is False- assert resolution.log["new_workflow_default_rollout_resolution"] == NewWorkflowDefaultRollout.undefined- assert WORKFLOW_TASK_V3_AB_FLAG in consulted_flags(provider)--@pytest.mark.asyncioasync def test_a_new_version_of_an_older_workflow_is_not_a_new_workflow(scoped_context: SkyvernContext, v3_default_cutoff: datetime@@ -1251,7 +1120,6 @@ async def test_a_new_version_of_an_older_workflow_is_not_a_new_workflow(assert DISABLE_TASK_V3_FLAG in [flag for flag, _distinct_id, _properties in provider.calls]assert WORKFLOW_TASK_V3_AB_FLAG in [flag for flag, _distinct_id, _properties in provider.calls]assert resolution.log["route_reason"] == WorkflowBlockEngineRouteReason.flag_bucket_control- assert TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT_FLAG not in consulted_flags(provider)# Asserted here rather than inside the fake, whose AssertionError the rule's catch-all would# swallow into "not a new workflow": the birth timestamp is read once, scoped to this run's own# organization. The read itself is the min over every version of the id including deleted ones,@@ -1281,9 +1149,7 @@ async def test_a_per_call_auto_generated_workflow_is_never_a_new_workflow(assert scoped_context.workflow_block_engine_override is Noneassert WORKFLOW_TASK_V3_AB_FLAG in consulted_flags(provider)- assert TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT_FLAG not in consulted_flags(provider)assert resolution.log["route_reason"] == WorkflowBlockEngineRouteReason.flag_bucket_control- assert resolution.log["new_workflow_default_rollout_resolution"] is None# A status the rule cannot use must not pay for the workflow read either.resolution.birth_reads.assert_not_awaited()@@ -1318,9 +1184,7 @@ async def test_a_per_call_recipe_run_is_never_a_new_workflow(assert scoped_context.workflow_block_engine_override is Noneassert WORKFLOW_TASK_V3_AB_FLAG in consulted_flags(provider)- assert TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT_FLAG not in consulted_flags(provider)assert resolution.log["route_reason"] == WorkflowBlockEngineRouteReason.flag_bucket_control- assert resolution.log["new_workflow_default_rollout_resolution"] is None# A trigger the rule cannot use must not pay for the workflow read either.resolution.birth_reads.assert_not_awaited()@@ -1430,7 +1294,6 @@ async def test_only_the_self_serve_tier_gets_the_new_workflow_default(assert resolution.log["route_reason"] == WorkflowBlockEngineRouteReason.flag_bucket_treatment# A tier the rule cannot use must not pay for the workflow read either.resolution.birth_reads.assert_not_awaited()- assert TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT_FLAG not in consulted_flags(provider)@pytest.mark.asyncio@@ -1450,7 +1313,6 @@ async def test_kill_switch_wins_over_the_new_workflow_default(assert scoped_context.workflow_block_engine_override is Noneassert resolution.log["route_reason"] == WorkflowBlockEngineRouteReason.disabledresolution.birth_reads.assert_not_awaited()- assert TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT_FLAG not in consulted_flags(provider)@pytest.mark.asyncio@@ -1469,7 +1331,6 @@ async def test_no_cutoff_leaves_every_workflow_on_the_flag_path(scoped_context:assert scoped_context.workflow_block_engine_override is Noneassert resolution.log["route_reason"] == WorkflowBlockEngineRouteReason.flag_bucket_controlresolution.birth_reads.assert_not_awaited()- assert TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT_FLAG not in consulted_flags(provider)@pytest.mark.asyncio@@ -1492,7 +1353,6 @@ async def test_ineligible_run_is_never_defaulted_to_v3(assert provider.calls == []assert resolution.log["route_reason"] == WorkflowBlockEngineRouteReason.ineligibleresolution.birth_reads.assert_not_awaited()- assert TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT_FLAG not in consulted_flags(provider)@pytest.mark.asynciodiff --git a/tests/unit/test_workflow_run_minutes_gate.py b/tests/unit/test_workflow_run_minutes_gate.pyindex 47359e973..32d7bf360 100644--- a/tests/unit/test_workflow_run_minutes_gate.py+++ b/tests/unit/test_workflow_run_minutes_gate.py@@ -34,9 +34,7 @@ from skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.core.skyvern_context import SkyvernContextfrom skyvern.forge.sdk.experimentation.billing_tier import BillingTierfrom skyvern.forge.sdk.experimentation.workflow_block_engine import (- TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT_FLAG,WORKFLOW_TASK_V3_AB_FLAG,- NewWorkflowDefaultRollout,WorkflowBlockEngineRouteReason,)from skyvern.forge.sdk.schemas.tasks import Task, TaskStatus@@ -778,7 +776,6 @@ _V3_DEFAULT_CUTOFF = datetime(2026, 9, 15, tzinfo=UTC)"task_v3_ab_arm": "treatment","route_reason": WorkflowBlockEngineRouteReason.flag_bucket_treatment,"billing_tier": BillingTier.ENTERPRISE.value,- "new_workflow_default_rollout_resolution": None,},),(@@ -789,12 +786,11 @@ _V3_DEFAULT_CUTOFF = datetime(2026, 9, 15, tzinfo=UTC)"task_v3_ab_arm": "control","route_reason": WorkflowBlockEngineRouteReason.flag_bucket_control,"billing_tier": BillingTier.SELF_SERVE.value,- "new_workflow_default_rollout_resolution": None,},),(_V3_DEFAULT_CUTOFF,- {WORKFLOW_TASK_V3_AB_FLAG: False, TASK_V3_NEW_WORKFLOW_DEFAULT_ROLLOUT_FLAG: True},+ {WORKFLOW_TASK_V3_AB_FLAG: False},{"ineligibility_reason": None,"billing_tier": BillingTier.SELF_SERVE,@@ -804,7 +800,6 @@ _V3_DEFAULT_CUTOFF = datetime(2026, 9, 15, tzinfo=UTC)"task_v3_ab_arm": "treatment","route_reason": WorkflowBlockEngineRouteReason.new_self_serve_workflow_default,"billing_tier": BillingTier.SELF_SERVE.value,- "new_workflow_default_rollout_resolution": NewWorkflowDefaultRollout.enrolled,},),(@@ -822,7 +817,6 @@ _V3_DEFAULT_CUTOFF = datetime(2026, 9, 15, tzinfo=UTC)# collapsing the two would hide which of the ineligible/attribution-lost masses a# per-tier read is missing."billing_tier": None,- "new_workflow_default_rollout_resolution": None,},),],@@ -838,9 +832,9 @@ async def test_duration_log_carries_the_tier_and_route_reason_the_run_was_bucketexpected: dict[str, object],) -> None:# SKY-16122: a per-arm, per-tier outcome read has to come off one log line, so the duration log- # reports what resolve_workflow_block_engine_arm decided for the run — the route reason and the- # rollout resolution included, because the arm alone reads "treatment" for a bucketed run and for- # one the new-workflow default enrolled. Driven through the real resolver rather than a+ # reports what resolve_workflow_block_engine_arm decided for the run — the route reason included,+ # because the arm alone reads "treatment" for a bucketed run and for one the new-workflow default+ # enrolled. Driven through the real resolver rather than a# hand-pinned context, which is what makes a dropped pin -- or a finalizer that reads the tier# again instead of the bucketed one -- red here.from structlog.testing import capture_logs