Skip to content

Automate browser based workflows with AI

SKY-10673: add code-first Copilot code block preflight (#6410)

Andrew Neilson1843917f925e
diff --git a/docs/changelog.mdx b/docs/changelog.mdx
index e6017e786..d2c619799 100644
--- a/docs/changelog.mdx
+++ b/docs/changelog.mdx
@@ -52,6 +52,7 @@ keywords:
- **Feature Preview Section in Settings** — A new "Feature Preview" panel in account settings lets you opt into upcoming features before they are fully released. ([#6318](https://github.com/Skyvern-AI/skyvern/pull/6318))
- **Filter Workflows by Tags** — The `GET /workflows` API now accepts a `?tags=` query parameter to filter results by tag. ([#6334](https://github.com/Skyvern-AI/skyvern/pull/6334))
- **Workflow Schedules in Open Source** — Self-hosted Skyvern deployments now support workflow schedules, previously a cloud-only feature. ([#6344](https://github.com/Skyvern-AI/skyvern/pull/6344))
+- **Claude Opus 4.8 Support** — Added Claude Opus 4.8 as a selectable model for both direct Anthropic and AWS Bedrock inference paths. ([#6409](https://github.com/Skyvern-AI/skyvern/pull/6409))
## Improvements
diff --git a/fern/docs/changelog.mdx b/fern/docs/changelog.mdx
index 94eb10249..252120b00 100644
--- a/fern/docs/changelog.mdx
+++ b/fern/docs/changelog.mdx
@@ -35,6 +35,7 @@ mode: custom
- **Feature Preview Section in Settings** — A new "Feature Preview" panel in account settings lets you opt into upcoming features before they are fully released. ([#6318](https://github.com/Skyvern-AI/skyvern/pull/6318))
- **Filter Workflows by Tags** — The `GET /workflows` API now accepts a `?tags=` query parameter to filter results by tag. ([#6334](https://github.com/Skyvern-AI/skyvern/pull/6334))
- **Workflow Schedules in Open Source** — Self-hosted Skyvern deployments now support workflow schedules, previously a cloud-only feature. ([#6344](https://github.com/Skyvern-AI/skyvern/pull/6344))
+- **Claude Opus 4.8 Support** — Added Claude Opus 4.8 as a selectable model for both direct Anthropic and AWS Bedrock inference paths. ([#6409](https://github.com/Skyvern-AI/skyvern/pull/6409))
## Improvements
diff --git a/skyvern/config.py b/skyvern/config.py
index 1445ce3dc..9615ad40f 100644
--- a/skyvern/config.py
+++ b/skyvern/config.py
@@ -107,6 +107,7 @@ class Settings(BaseSettings):
BROWSER_SCREENSHOT_TIMEOUT_MS: int = 20000
BROWSER_LOADING_TIMEOUT_MS: int = 60000
BROWSER_SCRAPING_BUILDING_ELEMENT_TREE_TIMEOUT_MS: int = 60 * 1000 # 1 minute
+ CODE_BLOCK_EXECUTION_TIMEOUT_SECONDS: int = 300
OPTION_LOADING_TIMEOUT_MS: int = 600000
MAX_STEPS_PER_RUN: int = 10
MAX_STEPS_PER_TASK_V2: int = 25
diff --git a/skyvern/forge/sdk/copilot/code_block_preflight.py b/skyvern/forge/sdk/copilot/code_block_preflight.py
new file mode 100644
index 000000000..3c54a0baf
--- /dev/null
+++ b/skyvern/forge/sdk/copilot/code_block_preflight.py
@@ -0,0 +1,228 @@
+"""Static preflight checks for generated Workflow Copilot code blocks."""
+
+from __future__ import annotations
+
+import ast
+import keyword
+import re
+import tempfile
+import textwrap
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Iterable
+
+
+@dataclass(frozen=True)
+class CodeBlockPreflightDiagnostic:
+ code: str
+ message: str
+
+
+_ANSI_ESCAPE_RE = re.compile(r"\x1b\[[0-9;]*m|\x1b\([AB]")
+_MYPY_ERROR_RE = re.compile(r"^(?P<path>.*?):(?P<line>\d+): (?P<severity>error): (?P<message>.*)$")
+_LOCATOR_NOT_CALLABLE_RE = re.compile(r'"Locator" not callable\s+\[operator\]')
+
+
+def preflight_code_block(
+ code: str,
+ *,
+ parameter_keys: Iterable[str] = (),
+) -> list[CodeBlockPreflightDiagnostic]:
+ """Run typed snippet checks for code-block Python.
+
+ This is intentionally best-effort while the checker dependency remains a
+ dev/local dependency. Security/sandbox validation still runs separately and
+ must not depend on this helper being available.
+ """
+
+ diagnostics = _static_ast_diagnostics(code)
+ if diagnostics:
+ return diagnostics
+
+ try:
+ from mypy import api as mypy_api
+ except ImportError:
+ return []
+
+ source = _build_typed_module(code, parameter_keys=parameter_keys)
+ with tempfile.TemporaryDirectory(prefix="skyvern-code-block-preflight-") as tmpdir:
+ path = Path(tmpdir) / "code_block.py"
+ path.write_text(source, encoding="utf-8")
+ stdout, stderr, status = mypy_api.run(
+ [
+ str(path),
+ "--config-file=/dev/null",
+ "--no-error-summary",
+ "--show-error-codes",
+ "--ignore-missing-imports",
+ "--no-incremental",
+ "--cache-dir=/dev/null",
+ ]
+ )
+ if status == 0:
+ return []
+
+ return _parse_mypy_output(stdout)
+
+
+def _static_ast_diagnostics(code: str) -> list[CodeBlockPreflightDiagnostic]:
+ try:
+ tree = ast.parse(_build_typed_module(code, parameter_keys=()))
+ except SyntaxError:
+ return []
+
+ diagnostics: list[CodeBlockPreflightDiagnostic] = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ wizard_step_diagnostic = _wizard_step_selector_diagnostic(node)
+ if wizard_step_diagnostic is not None:
+ diagnostics.append(wizard_step_diagnostic)
+ continue
+ evaluate_diagnostic = _page_evaluate_diagnostic(node)
+ if evaluate_diagnostic is not None:
+ diagnostics.append(evaluate_diagnostic)
+ continue
+ regex_diagnostic = _regex_literal_diagnostic(node)
+ if regex_diagnostic is not None:
+ diagnostics.append(regex_diagnostic)
+ return diagnostics
+
+
+def _wizard_step_selector_diagnostic(node: ast.Call) -> CodeBlockPreflightDiagnostic | None:
+ func = node.func
+ if not isinstance(func, ast.Attribute) or func.attr != "locator" or not node.args:
+ return None
+
+ selector = node.args[0]
+ if not isinstance(selector, ast.Constant) or not isinstance(selector.value, str):
+ return None
+ normalized_selector = selector.value.lower()
+ if "data-next-step" not in normalized_selector and "data-step" not in normalized_selector:
+ return None
+ if "button" not in normalized_selector:
+ return None
+
+ return CodeBlockPreflightDiagnostic(
+ code="AMBIGUOUS_WIZARD_STEP_SELECTOR",
+ message=(
+ "Code block targets a wizard step button by metadata selector only. Step metadata can match "
+ "both forward and back controls under Playwright strict mode. Target the visible semantic control "
+ "instead, such as `page.get_by_role('button', name='Continue')`, or narrow the locator to visible "
+ "button text before clicking."
+ ),
+ )
+
+
+def _page_evaluate_diagnostic(node: ast.Call) -> CodeBlockPreflightDiagnostic | None:
+ func = node.func
+ if not isinstance(func, ast.Attribute) or func.attr != "evaluate":
+ return None
+ if len(node.args) <= 2:
+ return None
+ return CodeBlockPreflightDiagnostic(
+ code="PLAYWRIGHT_API_MISMATCH",
+ message=(
+ "Code block calls Playwright `evaluate` with too many positional arguments. "
+ "In Playwright Python, pass at most the JavaScript expression and one serialized arg; "
+ "pack multiple values into a dict or list before calling evaluate."
+ ),
+ )
+
+
+_RE_LITERAL_FUNCTIONS = frozenset(
+ {
+ "compile",
+ "search",
+ "match",
+ "fullmatch",
+ "findall",
+ "finditer",
+ "split",
+ "sub",
+ }
+)
+
+
+def _regex_literal_diagnostic(node: ast.Call) -> CodeBlockPreflightDiagnostic | None:
+ func = node.func
+ if (
+ not isinstance(func, ast.Attribute)
+ or func.attr not in _RE_LITERAL_FUNCTIONS
+ or not isinstance(func.value, ast.Name)
+ or func.value.id != "re"
+ or not node.args
+ ):
+ return None
+
+ pattern = node.args[0]
+ if not isinstance(pattern, ast.Constant) or not isinstance(pattern.value, str):
+ return None
+
+ try:
+ re.compile(pattern.value)
+ except re.error as exc:
+ return CodeBlockPreflightDiagnostic(
+ code="INVALID_REGEX_LITERAL",
+ message=(
+ f"Code block contains an invalid regex literal for `re.{func.attr}`: {exc}. "
+ "Fix the pattern or avoid regex when simple string checks are enough."
+ ),
+ )
+ return None
+
+
+def _build_typed_module(code: str, *, parameter_keys: Iterable[str]) -> str:
+ parameter_declarations = "\n".join(
+ f"{key}: Any" for key in dict.fromkeys(parameter_keys) if _valid_python_identifier(key)
+ )
+ indented_code = textwrap.indent(textwrap.dedent(code).strip() or "pass", " ")
+ if parameter_declarations:
+ parameter_declarations += "\n"
+ return (
+ "from __future__ import annotations\n"
+ "from typing import Any\n"
+ "from types import SimpleNamespace\n"
+ "import asyncio\n"
+ "import html\n"
+ "import json\n"
+ "import re\n"
+ "from asyncio import sleep\n"
+ "from playwright.async_api import Page\n\n"
+ "page: Page\n"
+ f"{parameter_declarations}"
+ "\n"
+ "async def __code_block__() -> object:\n"
+ f"{indented_code}\n"
+ " return {}\n"
+ )
+
+
+def _valid_python_identifier(value: str) -> bool:
+ return value.isidentifier() and not keyword.iskeyword(value) and not value.startswith("__")
+
+
+def _parse_mypy_output(output: str) -> list[CodeBlockPreflightDiagnostic]:
+ diagnostics: list[CodeBlockPreflightDiagnostic] = []
+ for line in output.splitlines():
+ match = _MYPY_ERROR_RE.match(_ANSI_ESCAPE_RE.sub("", line))
+ if not match:
+ continue
+ message = match.group("message")
+ diagnostic = _diagnostic_from_mypy_message(message)
+ if diagnostic is not None:
+ diagnostics.append(diagnostic)
+ return diagnostics
+
+
+def _diagnostic_from_mypy_message(message: str) -> CodeBlockPreflightDiagnostic | None:
+ if _LOCATOR_NOT_CALLABLE_RE.search(message):
+ return CodeBlockPreflightDiagnostic(
+ code="PLAYWRIGHT_API_MISMATCH",
+ message=(
+ "Code block calls a Playwright Locator as a function. In Playwright Python, locator properties "
+ "such as `.first` and `.last` are not methods; use the property value before waiting, filling, "
+ "or clicking."
+ ),
+ )
+ return None
diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.py
index 3a0a48a57..a77b56c0d 100644
--- a/skyvern/forge/sdk/copilot/runtime.py
+++ b/skyvern/forge/sdk/copilot/runtime.py
@@ -25,6 +25,7 @@ from skyvern.cli.core.session_manager import (
unregister_copilot_session,
)
from skyvern.forge import app
+from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy
from skyvern.forge.sdk.copilot.screenshot_utils import ScreenshotEntry
from skyvern.forge.sdk.copilot.tracing_setup import copilot_span
from skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerificationEvidence
@@ -172,7 +173,7 @@ class AgentContext:
canonical_was_persisted_due_to_param_change: bool = False
allow_untested_workflow_draft: bool = False
request_policy: RequestPolicy | None = None
- block_authoring_policy: Any = "standard"
+ block_authoring_policy: BlockAuthoringPolicy = BlockAuthoringPolicy.STANDARD
effective_workflow_proxy_location: Any | None = None
copilot_run_start_monotonic: float | None = None
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 071cac752..71a90cf0f 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -6,7 +6,9 @@ import asyncio
import codecs
import copy
import csv
+import html
import json
+import keyword
import os
import re
import smtplib
@@ -3460,20 +3462,34 @@ class CodeBlock(Block):
"tuple": tuple,
"set": set,
"bool": bool,
+ "isinstance": isinstance,
+ "enumerate": enumerate,
+ "any": any,
+ "all": all,
+ "max": max,
+ "min": min,
+ "sum": sum,
+ "sorted": sorted,
"sleep": asyncio.sleep,
"asyncio": SimpleNamespace(sleep=asyncio.sleep),
"re": SimpleNamespace(
match=re.match,
search=re.search,
findall=re.findall,
+ finditer=re.finditer,
+ fullmatch=re.fullmatch,
sub=re.sub,
compile=re.compile,
split=re.split,
+ escape=re.escape,
+ I=re.I,
+ S=re.S,
IGNORECASE=re.IGNORECASE,
MULTILINE=re.MULTILINE,
DOTALL=re.DOTALL,
),
"json": SimpleNamespace(dumps=json.dumps, loads=json.loads),
+ "html": SimpleNamespace(escape=html.escape),
"Exception": Exception,
}
@@ -3484,21 +3500,45 @@ class CodeBlock(Block):
# user code so it can block dunder identifiers like __capture_locals.
self.is_safe_code(code)
code = textwrap.indent(textwrap.dedent(code), " ")
- full_code = f"""
-async def wrapper():
-{code}
- return __capture_locals()
-"""
runtime_variables: dict[str, Callable[[], Awaitable[dict[str, Any]]]] = {}
safe_vars = self.build_safe_vars()
+ parameter_defaults: dict[str, Any] = {}
if parameters:
for key, value in parameters.items():
if key not in safe_vars:
safe_vars[key] = value
+ if key.isidentifier() and not keyword.iskeyword(key) and not key.startswith("__"):
+ parameter_defaults[key] = value
+ default_args = ", ".join(f"{key}=__param_defaults[{key!r}]" for key in parameter_defaults)
+ full_code = f"""
+async def wrapper({default_args}):
+{code}
+ return __capture_locals()
+"""
safe_vars["page"] = page
safe_vars["__capture_locals"] = locals
+ safe_vars["__param_defaults"] = parameter_defaults
exec(full_code, safe_vars, runtime_variables)
- return runtime_variables["wrapper"]
+ user_function = runtime_variables["wrapper"]
+ if not parameter_defaults:
+ return user_function
+
+ excluded_parameter_keys = frozenset(parameter_defaults)
+
+ async def filtered_user_function() -> dict[str, Any]:
+ result = await user_function()
+ return {key: value for key, value in result.items() if key not in excluded_parameter_keys}
+
+ return filtered_user_function
+
+ @staticmethod
+ async def execute_user_function_with_timeout(
+ user_function: Callable[[], Awaitable[dict[str, Any]]],
+ timeout_seconds: int,
+ ) -> dict[str, Any]:
+ if timeout_seconds <= 0:
+ return await user_function()
+ return await asyncio.wait_for(user_function(), timeout=timeout_seconds)
def get_all_parameters(
self,
@@ -3603,7 +3643,10 @@ async def wrapper():
try:
user_function = self.generate_async_user_function(self.code, page, parameter_values)
- result = await user_function()
+ result = await self.execute_user_function_with_timeout(
+ user_function,
+ settings.CODE_BLOCK_EXECUTION_TIMEOUT_SECONDS,
+ )
except InsecureCodeDetected as e:
return await self.build_block_result(
success=False,
@@ -3613,6 +3656,18 @@ async def wrapper():
workflow_run_block_id=workflow_run_block_id,
organization_id=organization_id,
)
+ except asyncio.TimeoutError:
+ return await self.build_block_result(
+ success=False,
+ failure_reason=(
+ "Failed to execute code block. Reason: TimeoutError: code block exceeded "
+ f"{settings.CODE_BLOCK_EXECUTION_TIMEOUT_SECONDS} seconds"
+ ),
+ output_parameter_value=None,
+ status=BlockStatus.failed,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ )
except Exception as e:
exc = CustomizedCodeException(e)
return await self.build_block_result(
diff --git a/tests/unit/test_code_block_sandbox.py b/tests/unit/test_code_block_sandbox.py
index 1ec5be63d..0f9b7f2a1 100644
--- a/tests/unit/test_code_block_sandbox.py
+++ b/tests/unit/test_code_block_sandbox.py
@@ -7,11 +7,15 @@ Verifies that the CodeBlock safety layer:
"""
import asyncio
+from datetime import datetime, timezone
import pytest
+from skyvern.config import settings
from skyvern.forge.sdk.workflow.exceptions import InsecureCodeDetected
from skyvern.forge.sdk.workflow.models.block import CodeBlock
+from skyvern.forge.sdk.workflow.models.parameter import OutputParameter, ParameterType
+from skyvern.schemas.workflows import BlockStatus
# ---------------------------------------------------------------------------
# is_safe_code — rejection tests
@@ -359,6 +363,22 @@ class TestIsSafeCodeAcceptsLegitimateCode:
def test_for_loop(self) -> None:
CodeBlock.is_safe_code("for i in range(10):\n x = i")
+ def test_enumerate_loop(self) -> None:
+ CodeBlock.is_safe_code("for i, value in enumerate(values):\n x = i")
+
+ def test_exposes_safe_iteration_and_regex_aliases(self) -> None:
+ safe_vars = CodeBlock.build_safe_vars()
+
+ assert safe_vars["enumerate"] is enumerate
+ assert safe_vars["isinstance"] is isinstance
+ assert safe_vars["any"] is any
+ assert safe_vars["all"] is all
+ assert safe_vars["max"] is max
+ assert safe_vars["min"] is min
+ assert safe_vars["sum"] is sum
+ assert safe_vars["sorted"] is sorted
+ assert safe_vars["re"].I == safe_vars["re"].IGNORECASE
+
def test_try_except(self) -> None:
CodeBlock.is_safe_code("try:\n x = 1\nexcept Exception:\n x = 0")
@@ -411,7 +431,25 @@ class TestBuildSafeVars:
def test_expected_builtins_present(self) -> None:
safe_vars = CodeBlock.build_safe_vars()
- expected = {"len", "range", "str", "int", "float", "dict", "list", "tuple", "set", "bool"}
+ expected = {
+ "len",
+ "range",
+ "str",
+ "int",
+ "float",
+ "dict",
+ "list",
+ "tuple",
+ "set",
+ "bool",
+ "isinstance",
+ "any",
+ "all",
+ "max",
+ "min",
+ "sum",
+ "sorted",
+ }
for name in expected:
assert name in safe_vars, f"{name} missing from safe_vars"
@@ -424,6 +462,12 @@ class TestBuildSafeVars:
assert not hasattr(safe_vars["json"], "decoder")
assert not hasattr(safe_vars["json"], "encoder")
+ def test_html_is_restricted_namespace(self) -> None:
+ safe_vars = CodeBlock.build_safe_vars()
+ assert safe_vars["html"].escape("<RBT>") == "&lt;RBT&gt;"
+ assert not hasattr(safe_vars["html"], "unescape")
+ assert not hasattr(safe_vars["html"], "entities")
+
def test_re_is_restricted_namespace(self) -> None:
safe_vars = CodeBlock.build_safe_vars()
assert hasattr(safe_vars["re"], "match")
@@ -521,6 +565,17 @@ result = stdout.decode()
assert safe_vars["asyncio"] is not asyncio_mod
assert not hasattr(safe_vars["asyncio"], "create_subprocess_shell")
+ def test_runtime_re_namespace_has_common_safe_regex_helpers(self) -> None:
+ """Generated code can use normal safe regex idioms without importing re."""
+ safe_vars = CodeBlock.build_safe_vars()
+ re_helper = safe_vars["re"]
+
+ assert re_helper.escape("a+b") == "a\\+b"
+ assert re_helper.search("a.*b", "a\nb", re_helper.S)
+ assert re_helper.findall("a", "A", re_helper.I) == ["A"]
+ assert re_helper.fullmatch(r"\d+", "123")
+ assert [match.group(0) for match in re_helper.finditer("a", "aba")] == ["a", "a"]
+
# ---------------------------------------------------------------------------
# generate_async_user_function — integration tests
@@ -538,6 +593,7 @@ class TestGenerateAsyncUserFunctionIntegration:
@staticmethod
def _exec_user_code(code: str, page: object = None, parameters: dict | None = None):
"""Build and return the async wrapper using CodeBlock's actual method."""
+ import keyword
import textwrap
if page is None:
@@ -546,21 +602,36 @@ class TestGenerateAsyncUserFunctionIntegration:
page = MagicMock()
indented = textwrap.indent(code, " ")
- full_code = f"""
-async def wrapper():
-{indented}
- return __capture_locals()
-"""
runtime_variables: dict = {}
safe_vars = CodeBlock.build_safe_vars()
+ parameter_defaults: dict = {}
if parameters:
for key, value in parameters.items():
if key not in safe_vars:
safe_vars[key] = value
+ if key.isidentifier() and not keyword.iskeyword(key) and not key.startswith("__"):
+ parameter_defaults[key] = value
+ default_args = ", ".join(f"{key}=__param_defaults[{key!r}]" for key in parameter_defaults)
+ full_code = f"""
+async def wrapper({default_args}):
+{indented}
+ return __capture_locals()
+"""
safe_vars["page"] = page
safe_vars["__capture_locals"] = locals
+ safe_vars["__param_defaults"] = parameter_defaults
exec(full_code, safe_vars, runtime_variables)
- return runtime_variables["wrapper"]
+ user_function = runtime_variables["wrapper"]
+ if not parameter_defaults:
+ return user_function
+
+ excluded_parameter_keys = frozenset(parameter_defaults)
+
+ async def filtered_user_function() -> dict:
+ result = await user_function()
+ return {key: value for key, value in result.items() if key not in excluded_parameter_keys}
+
+ return filtered_user_function
@pytest.mark.asyncio
async def test_safe_code_runs_successfully(self) -> None:
@@ -569,6 +640,12 @@ async def wrapper():
result = await fn()
assert result["x"] == 3
+ @pytest.mark.asyncio
+ async def test_safe_code_with_isinstance_shape_check(self) -> None:
+ fn = self._exec_user_code("value = {'downloads': 123}\nok = isinstance(value, dict)")
+ result = await fn()
+ assert result["ok"] is True
+
@pytest.mark.asyncio
async def test_safe_code_with_json(self) -> None:
fn = self._exec_user_code('x = json.dumps({"a": 1})')
@@ -582,6 +659,77 @@ async def wrapper():
result = await fn()
assert isinstance(result, dict)
+ @pytest.mark.asyncio
+ async def test_user_function_timeout_bounds_execution(self) -> None:
+ """A stuck code block must fail promptly instead of holding a workflow run open."""
+ fn = self._exec_user_code("await sleep(10)")
+ with pytest.raises(asyncio.TimeoutError):
+ await CodeBlock.execute_user_function_with_timeout(fn, timeout_seconds=1)
+
+ @pytest.mark.asyncio
+ async def test_user_function_timeout_can_be_disabled(self) -> None:
+ fn = self._exec_user_code("await sleep(0)\ncompleted = True")
+ result = await CodeBlock.execute_user_function_with_timeout(fn, timeout_seconds=0)
+ assert result["completed"] is True
+
+ @pytest.mark.asyncio
+ async def test_execute_uses_configured_code_block_timeout(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ class FakeBrowserState:
+ async def get_working_page(self) -> object:
+ return object()
+
+ class FakeWorkflowRunContext:
+ values: dict[str, object] = {}
+ secrets: dict[str, object] = {}
+ include_secrets_in_templates = False
+ workflow_title = "Test Workflow"
+ workflow_id = "w_test"
+ workflow_permanent_id = "wpid_test"
+ workflow_run_id = "wrid_test"
+ browser_session_id = None
+ workflow_run_outputs: list[object] = []
+
+ def get_block_metadata(self, label: str | None) -> dict[str, object]:
+ return {}
+
+ def build_workflow_run_summary(self) -> str:
+ return ""
+
+ async def validate_code_block(*args: object, **kwargs: object) -> None:
+ return None
+
+ async def get_browser_state(*args: object, **kwargs: object) -> FakeBrowserState:
+ return FakeBrowserState()
+
+ async def record_output(*args: object, **kwargs: object) -> None:
+ return None
+
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.block.app.AGENT_FUNCTION.validate_code_block",
+ validate_code_block,
+ )
+ monkeypatch.setattr(CodeBlock, "get_or_create_browser_state", get_browser_state)
+ monkeypatch.setattr(CodeBlock, "get_workflow_run_context", lambda *args: FakeWorkflowRunContext())
+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", record_output)
+
+ now = datetime.now(timezone.utc)
+ output_parameter = OutputParameter(
+ parameter_type=ParameterType.OUTPUT,
+ key="test_code_output",
+ description="test output",
+ output_parameter_id="op_test_code",
+ workflow_id="w_test",
+ created_at=now,
+ modified_at=now,
+ )
+ block = CodeBlock(label="test_code", code="value = 'ok'", output_parameter=output_parameter)
+ result = await block.execute(workflow_run_id="wrid_test", workflow_run_block_id="")
+
+ assert settings.CODE_BLOCK_EXECUTION_TIMEOUT_SECONDS > 0
+ assert result.success is True
+ assert result.status == BlockStatus.completed
+ assert result.output_parameter_value == {"value": "ok"}
+
def test_poc_blocked_at_is_safe_code_gate(self) -> None:
"""The PoC payload is rejected before exec() is ever called."""
malicious_code = "proc = await asyncio.create_subprocess_shell('id')"
@@ -630,6 +778,28 @@ async def wrapper():
# json should still be the safe SimpleNamespace, not os
assert result["x"] == '{"a": 1}'
+ @pytest.mark.asyncio
+ async def test_parameter_can_be_normalized_with_same_local_name(self) -> None:
+ """Workflow parameters are usable without leaking wrapper defaults into output."""
+ fn = self._exec_user_code(
+ "person_name = person_name.strip()\nnormalized = person_name.upper()",
+ parameters={"person_name": " Noor Assi "},
+ )
+ result = await fn()
+
+ assert "person_name" not in result
+ assert result["normalized"] == "NOOR ASSI"
+
+ @pytest.mark.asyncio
+ async def test_parameter_defaults_do_not_leak_into_implicit_output(self) -> None:
+ fn = self._exec_user_code(
+ "visible = public_value.upper()",
+ parameters={"public_value": "ok", "secret_token": "sensitive"},
+ )
+ result = await fn()
+
+ assert result == {"visible": "OK"}
+
@pytest.mark.asyncio
async def test_parameters_cannot_override_builtins(self) -> None:
"""A parameter named __builtins__ must not re-enable builtins."""