Skip to content

Automate browser based workflows with AI

Upgrade mcp to 1.30.0 in the lockfile (SKY-18400) (#8922)

Shuchang Zhengbed2561a8c29
diff --git a/.env.example b/.env.example
index 40d7bf77f..c94b1f5ef 100644
--- a/.env.example
+++ b/.env.example
@@ -268,7 +268,7 @@ SKYVERN_AUTH_BITWARDEN_CLIENT_SECRET=your-client-secret-here
# GCP_CREDENTIAL_VAULT_PREFIX=skyvern-cred-
# =============================================================================
-# HEADLESS GHOST BLOG (server/build and public scopes)
+# HEADLESS GHOST BLOG (server/build scope)
# =============================================================================
# GHOST_URL: server/build only. Approved bases are https://skyvern.ghost.io/ghost
# (root install) and https://skyvern.ghost.io/blog/ghost (the old /blog subdirectory install).
@@ -276,9 +276,6 @@ GHOST_URL=
# GHOST_CONTENT_API_KEY: server/build only. Ghost Content API key; exactly 26
# hexadecimal characters. Rotate in Ghost Admin and the deployment environment together.
GHOST_CONTENT_API_KEY=
-# VITE_PUBLIC_GHOST_CONTENT_API_KEY: public browser build only. This is the
-# same 26-hex Content API key, never an Admin key. It is readable by visitors.
-VITE_PUBLIC_GHOST_CONTENT_API_KEY=
# GHOST_ADMIN_API_KEY: server-only preview credential. Format is id:64 hex
# characters. Rotate in Ghost Admin and the deployment environment together.
GHOST_ADMIN_API_KEY=
diff --git a/skyvern/cli/mcp_tools/blocks.py b/skyvern/cli/mcp_tools/blocks.py
index 3a533e55d..45473422f 100644
--- a/skyvern/cli/mcp_tools/blocks.py
+++ b/skyvern/cli/mcp_tools/blocks.py
@@ -413,9 +413,10 @@ def _code_block_runtime_topic() -> dict[str, str]:
safe_vars = CodeBlock.build_safe_vars()
builtin_names = sorted(name for name in safe_vars["__builtins__"] if not name.startswith("__"))
shims = {name: sorted(vars(value)) for name, value in safe_vars.items() if isinstance(value, SimpleNamespace)}
- helpers = sorted(name for name in safe_vars if name != "__builtins__" and name not in shims)
+ helpers = sorted(name for name in safe_vars if not name.startswith("__") and name not in shims)
lines = [
- "Names a code block's Python may use. Imports are blocked; the runtime binds everything listed here.",
+ "Names a code block's Python may use. The runtime binds everything listed here. The only importable "
+ "modules are the shims below; `import re` binds the shim, and any other import is rejected.",
"",
"Builtins: " + ", ".join(builtin_names),
"",
diff --git a/skyvern/forge/request_logging.py b/skyvern/forge/request_logging.py
index 58af11ca6..44c14d5e4 100644
--- a/skyvern/forge/request_logging.py
+++ b/skyvern/forge/request_logging.py
@@ -73,6 +73,8 @@ _SENSITIVE_ENDPOINT_PATTERNS = (
re.compile(r"^POST /oauth/(?:token|consent|callback)$"),
# Marketplace service routes return freshly minted client secrets.
re.compile(r"^POST /(?:api/)?v1/marketplace(?:/.*)?$"),
+ # Skyplane authority calls carry runtime capabilities, tool arguments, agent feedback text and delivered files.
+ re.compile(r"^[^ ]+ /api/v1/skyplane(?:/.*)?$"),
)
_MAX_BODY_LENGTH = 1000
_READ_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index 46a40149d..af6d5ae84 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -3318,11 +3318,7 @@ def _build_max_turns_exit_result(ctx: CopilotContext, global_llm_context: str |
def _build_cancelled_exit_result(ctx: CopilotContext, global_llm_context: str | None) -> AgentResult:
- if ctx.copilot_total_timeout_exceeded:
- LOG.info("Copilot cancellation resolved as total timeout")
- result = _build_timeout_exit_result(ctx, global_llm_context)
- else:
- result = _build_cancel_exit_result(ctx, global_llm_context)
+ result = _build_cancel_exit_result(ctx, global_llm_context)
result.cancellation_iteration = ctx.copilot_turn_cancelled_iteration
outcome = getattr(ctx, "latest_recorded_build_test_outcome", None)
recorded = outcome if isinstance(outcome, RecordedBuildTestOutcome) else None
diff --git a/skyvern/forge/sdk/copilot/code_block_preflight.py b/skyvern/forge/sdk/copilot/code_block_preflight.py
index 4779f813a..ed796c854 100644
--- a/skyvern/forge/sdk/copilot/code_block_preflight.py
+++ b/skyvern/forge/sdk/copilot/code_block_preflight.py
@@ -12,9 +12,7 @@ import tempfile
import textwrap
import unicodedata
from dataclasses import dataclass
-from functools import cache
from pathlib import Path
-from types import SimpleNamespace
from typing import Callable, Iterable, Iterator, Mapping
from jinja2 import StrictUndefined, TemplateSyntaxError, UndefinedError
@@ -24,7 +22,6 @@ from jinja2.sandbox import SandboxedEnvironment
from skyvern.forge.sdk.copilot.code_block_security import CodeBlockSecurityError, author_time_code_security_errors
from skyvern.forge.sdk.copilot.code_block_synthesis import is_root_locator_selector
from skyvern.forge.sdk.workflow.models._jinja import _json_finalize, _json_type_filter
-from skyvern.forge.sdk.workflow.models.block import CodeBlock
from skyvern.utils.strings import join_phrases
from skyvern.utils.templating import get_missing_variables
@@ -282,137 +279,6 @@ _TABLE_ROW_TAG_SELECTOR_RE = re.compile(r"(?<![a-z0-9_-])tr(?![a-z0-9_-])")
_TABLE_ROW_ROLE_SELECTOR_RE = re.compile(r"\[role\s*=\s*(['\"]?)row\1\]")
-@cache
-def _sandbox_shim_surface() -> dict[str, frozenset[str]]:
- return {
- name: frozenset(vars(value))
- for name, value in CodeBlock.build_safe_vars().items()
- if isinstance(value, SimpleNamespace)
- }
-
-
-def strip_redundant_sandbox_imports(code: str) -> tuple[str, list[str]]:
- """Remove top-level imports the runtime sandbox already injects.
-
- A module import is removed only when the runtime sandbox provides the same
- name as a ``SimpleNamespace`` helper and every attribute the code reads on
- that name is present on the injected helper. Aliased imports, submodule
- imports, from-imports, compound-line imports, non-sandbox modules, imports
- whose used surface exceeds the injected helper, and bare uses of the name as
- a value are all left in place so ``CodeBlock.is_safe_code`` still rejects
- them with immediate author-time feedback.
- """
-
- try:
- tree = ast.parse(code)
- except SyntaxError:
- return code, []
-
- shim_surface = _sandbox_shim_surface()
- attribute_use = _module_attribute_use(tree)
- bare_use = _module_bare_use(tree)
-
- removable_spans: list[tuple[int, int]] = []
- stripped_modules: list[str] = []
- occupied_lines = _occupied_line_numbers(tree)
- for node in tree.body:
- if not isinstance(node, ast.Import):
- continue
- candidate_modules = _strippable_module_names(node, shim_surface, attribute_use, bare_use)
- if candidate_modules is None:
- continue
- if node.end_lineno is None:
- continue
- if _line_span_shares_other_statement(node, occupied_lines):
- continue
- removable_spans.append((node.lineno, node.end_lineno))
- stripped_modules.extend(candidate_modules)
-
- if not removable_spans:
- return code, []
-
- sanitized = _remove_line_spans(code, removable_spans)
- try:
- ast.parse(sanitized)
- except SyntaxError:
- return code, []
- return sanitized, stripped_modules
-
-
-def _strippable_module_names(
- node: ast.Import,
- shim_surface: dict[str, frozenset[str]],
- attribute_use: dict[str, set[str]],
- bare_use: set[str],
-) -> list[str] | None:
- modules: list[str] = []
- for alias in node.names:
- if alias.asname is not None or "." in alias.name:
- return None
- if alias.name not in shim_surface:
- return None
- if alias.name in bare_use:
- return None
- if not attribute_use.get(alias.name, set()).issubset(shim_surface[alias.name]):
- return None
- modules.append(alias.name)
- return modules or None
-
-
-def _module_attribute_use(tree: ast.AST) -> dict[str, set[str]]:
- usage: dict[str, set[str]] = {}
- for node in ast.walk(tree):
- if (
- isinstance(node, ast.Attribute)
- and isinstance(node.value, ast.Name)
- and isinstance(node.value.ctx, ast.Load)
- ):
- usage.setdefault(node.value.id, set()).add(node.attr)
- return usage
-
-
-def _module_bare_use(tree: ast.AST) -> set[str]:
- # id() of each ast.Attribute value Name is stable across both walks of the same parsed tree.
- attribute_base_names: set[int] = set()
- for node in ast.walk(tree):
- if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name):
- attribute_base_names.add(id(node.value))
- bare: set[str] = set()
- for node in ast.walk(tree):
- if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load) and id(node) not in attribute_base_names:
- bare.add(node.id)
- return bare
-
-
-def _occupied_line_numbers(tree: ast.AST) -> dict[int, set[int]]:
- lines: dict[int, set[int]] = {}
- for node in ast.iter_child_nodes(tree):
- if not isinstance(node, ast.stmt):
- continue
- if node.lineno is None or node.end_lineno is None:
- continue
- for line in range(node.lineno, node.end_lineno + 1):
- lines.setdefault(line, set()).add(id(node))
- return lines
-
-
-def _line_span_shares_other_statement(node: ast.Import, occupied_lines: dict[int, set[int]]) -> bool:
- if node.end_lineno is None:
- return True
- for line in range(node.lineno, node.end_lineno + 1):
- if any(owner != id(node) for owner in occupied_lines.get(line, set())):
- return True
- return False
-
-
-def _remove_line_spans(code: str, spans: list[tuple[int, int]]) -> str:
- drop_lines: set[int] = set()
- for start, end in spans:
- drop_lines.update(range(start, end + 1))
- kept = [line for index, line in enumerate(code.splitlines(keepends=True), start=1) if index not in drop_lines]
- return "".join(kept)
-
-
def preflight_code_block(
code: str,
*,
@@ -557,6 +423,7 @@ def _static_ast_diagnostics(code: str) -> list[CodeBlockPreflightDiagnostic]:
if diagnostic.code not in _ADVISORY_DIAGNOSTIC_CODES
),
]
+ re_modules, re_functions = _re_bindings(tree)
for node in ast.walk(tree):
if not isinstance(node, ast.Call):
continue
@@ -564,7 +431,7 @@ def _static_ast_diagnostics(code: str) -> list[CodeBlockPreflightDiagnostic]:
if evaluate_diagnostic is not None:
diagnostics.append(evaluate_diagnostic)
continue
- regex_diagnostic = _regex_literal_diagnostic(node)
+ regex_diagnostic = _regex_literal_diagnostic(node, re_modules, re_functions)
if regex_diagnostic is not None:
diagnostics.append(regex_diagnostic)
@@ -1103,15 +970,29 @@ _RE_LITERAL_FUNCTIONS = frozenset(
)
-def _regex_literal_diagnostic(node: ast.Call) -> CodeBlockPreflightDiagnostic | None:
+def _re_bindings(tree: ast.AST) -> tuple[frozenset[str], dict[str, str]]:
+ """Names bound to the `re` module, and names a from-import bound to one of its functions."""
+ modules = {"re"}
+ functions: dict[str, str] = {}
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ modules.update(alias.asname or alias.name for alias in node.names if alias.name == "re")
+ elif isinstance(node, ast.ImportFrom) and node.module == "re" and not node.level:
+ functions.update({alias.asname or alias.name: alias.name for alias in node.names})
+ return frozenset(modules), functions
+
+
+def _regex_literal_diagnostic(
+ node: ast.Call, re_modules: frozenset[str], re_functions: dict[str, str]
+) -> 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
- ):
+ if isinstance(func, ast.Attribute) and isinstance(func.value, ast.Name) and func.value.id in re_modules:
+ function_name = func.attr
+ elif isinstance(func, ast.Name) and func.id in re_functions:
+ function_name = re_functions[func.id]
+ else:
+ return None
+ if function_name not in _RE_LITERAL_FUNCTIONS or not node.args:
return None
pattern = node.args[0]
@@ -1124,7 +1005,7 @@ def _regex_literal_diagnostic(node: ast.Call) -> CodeBlockPreflightDiagnostic |
return CodeBlockPreflightDiagnostic(
code="INVALID_REGEX_LITERAL",
message=(
- f"Code block contains an invalid regex literal for `re.{func.attr}`: {exc}. "
+ f"Code block contains an invalid regex literal for `re.{function_name}`: {exc}. "
"Fix the pattern or avoid regex when simple string checks are enough."
),
)
diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.py
index 7f023be6b..b6e738ed9 100644
--- a/skyvern/forge/sdk/copilot/enforcement.py
+++ b/skyvern/forge/sdk/copilot/enforcement.py
@@ -364,21 +364,14 @@ def _elapsed_run_seconds(ctx: Any, start_time: float) -> float:
return now - start_time - pause_seconds - question_seconds - active_wait_seconds
-def _mark_copilot_total_timeout_if_elapsed(ctx: Any, start_time: float, iteration: int) -> None:
- elapsed = _elapsed_run_seconds(ctx, start_time)
- if elapsed >= TOTAL_TIMEOUT_SECONDS:
- _mark_copilot_total_timeout(ctx, elapsed_seconds=elapsed, iteration=iteration)
-
-
def _record_copilot_cancellation(ctx: Any, start_time: float, iteration: int) -> None:
- """Record a cancellation raised at a model-call boundary, whatever the elapsed budget.
+ """Record a cancellation raised at a model-call boundary; the turn deadline never arrives as a cancellation.
Synchronous and never raising, so the caller's ``raise`` re-raises the original
cancellation neither masked nor delayed.
"""
try:
elapsed = _elapsed_run_seconds(ctx, start_time)
- _mark_copilot_total_timeout_if_elapsed(ctx, start_time, iteration)
ctx.copilot_turn_cancelled_iteration = iteration
LOG.warning(
"copilot_turn_cancelled",
diff --git a/skyvern/forge/sdk/copilot/tools/frontier.py b/skyvern/forge/sdk/copilot/tools/frontier.py
index 276babc32..5d119f9ba 100644
--- a/skyvern/forge/sdk/copilot/tools/frontier.py
+++ b/skyvern/forge/sdk/copilot/tools/frontier.py
@@ -684,9 +684,7 @@ def _code_block_opens_on_static_url(block: _HasCode) -> bool:
body = ast.parse(textwrap.dedent(code)).body
except (SyntaxError, ValueError, RecursionError, MemoryError):
return False
- if not body:
- return False
- first = body[0]
+ first = next((statement for statement in body if not isinstance(statement, ast.Import | ast.ImportFrom)), None)
if not (isinstance(first, ast.Expr) and isinstance(first.value, ast.Await)):
return False
call = first.value.value
diff --git a/skyvern/forge/sdk/db/repositories/workflow_runs.py b/skyvern/forge/sdk/db/repositories/workflow_runs.py
index 6bb0a9ce4..bc45454c1 100644
--- a/skyvern/forge/sdk/db/repositories/workflow_runs.py
+++ b/skyvern/forge/sdk/db/repositories/workflow_runs.py
@@ -3021,7 +3021,7 @@ class WorkflowRunsRepository(BaseRepository):
)
return query.where(or_(error_code_in_tasks, error_code_in_blocks))
- @db_operation("get_workflow_runs")
+ @db_operation("get_workflow_runs", expected_errors=(RunsListSearchCanceled,))
async def get_workflow_runs(
self,
organization_id: str,
@@ -3033,6 +3033,12 @@ class WorkflowRunsRepository(BaseRepository):
error_code: str | None = None,
) -> list[WorkflowRun]:
async with self.Session() as session:
+ statement_timeout_seconds: float | None = None
+ if _is_bounded_runs_list_read(session, search_key):
+ # Start after checkout so pool wait does not consume the connection-hold budget.
+ await session.connection()
+ statement_timeout_seconds = RUNS_LIST_STATEMENT_TIMEOUT_SECONDS
+ await apply_statement_timeout(session, statement_timeout_seconds)
db_page = page - 1 # offset logic is 0 based
query = (
@@ -3070,7 +3076,16 @@ class WorkflowRunsRepository(BaseRepository):
query = query.limit(page_size).offset(db_page * page_size)
- workflow_runs = (await session.execute(query)).all()
+ try:
+ workflow_runs = (await session.execute(query)).all()
+ except StatementError as exc:
+ if not search_key or not is_statement_timeout(exc):
+ raise
+ exc.hide_parameters = True
+ raise RunsListSearchCanceled(
+ indexed_search=is_indexed_runs_list_search_key(search_key),
+ statement_timeout_seconds=statement_timeout_seconds,
+ ) from exc
return [
convert_to_workflow_run(run, workflow_title=title, debug_enabled=self.debug_enabled)
diff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.py
index 0a325ff0a..d22e367a3 100644
--- a/skyvern/forge/sdk/routes/agent_protocol.py
+++ b/skyvern/forge/sdk/routes/agent_protocol.py
@@ -5338,14 +5338,33 @@ async def get_workflow_runs(
- Combined: `?status=failed&error_code=LOGIN_FAILED&search_key=my_credential`
"""
analytics.capture("skyvern-oss-agent-workflow-runs-get")
- return await app.WORKFLOW_SERVICE.get_workflow_runs(
- organization_id=current_org.organization_id,
- page=page,
- page_size=page_size,
- status=status,
- search_key=search_key,
- error_code=error_code,
- )
+ try:
+ return await app.WORKFLOW_SERVICE.get_workflow_runs(
+ organization_id=current_org.organization_id,
+ page=page,
+ page_size=page_size,
+ status=status,
+ search_key=search_key,
+ error_code=error_code,
+ )
+ except RunsListSearchCanceled as exc:
+ LOG.warning(
+ "runs_list_statement_timeout",
+ organization_id=current_org.organization_id,
+ # Names, never values: a search term can carry customer data.
+ filters=_runs_list_filter_names(
+ status=status,
+ search_key=search_key,
+ error_code=error_code,
+ ),
+ page=page,
+ page_size=page_size,
+ statement_timeout_seconds=exc.statement_timeout_seconds,
+ )
+ raise _runs_list_timeout_error(
+ indexed_search=exc.indexed_search,
+ search_detail=_RUNS_LIST_SEARCH_TIMEOUT_DETAIL,
+ ) from exc
_WORKFLOW_RUNS_BY_ID_DESCRIPTION = (
diff --git a/skyvern/forge/sdk/workflow/code_block_safety.py b/skyvern/forge/sdk/workflow/code_block_safety.py
index 152c0fe19..5d9886155 100644
--- a/skyvern/forge/sdk/workflow/code_block_safety.py
+++ b/skyvern/forge/sdk/workflow/code_block_safety.py
@@ -98,6 +98,9 @@ BLOCKED_ATTRS: frozenset[str] = frozenset(
"get_type_hints",
}
)
+# The names module_shims binds; importing one binds its shim and loads nothing.
+SANDBOX_IMPORTABLE_MODULES: frozenset[str] = frozenset({"asyncio", "datetime", "html", "json", "re"})
+SANDBOX_MODULES_GLOBAL = "__codeblock_modules__"
ALLOWED_SCRIPT_ATTRS: frozenset[str] = frozenset(
{"format", "listdir", "makedirs", "rmdir", "stderr", "stdin", "stdout"}
)
@@ -381,6 +384,56 @@ def _normalized_import_root(module_name: str) -> str:
return module_name.lstrip("_")
+def sandbox_import_error(node: ast.Import | ast.ImportFrom) -> str | None:
+ """Why a CodeBlock may not run this import, or None when it names a module the sandbox already provides."""
+ if isinstance(node, ast.Import):
+ modules = [alias.name for alias in node.names]
+ else:
+ modules = ["." * node.level + (node.module or "")]
+ for module in modules:
+ if module not in SANDBOX_IMPORTABLE_MODULES:
+ importable = ", ".join(sorted(SANDBOX_IMPORTABLE_MODULES))
+ return f"Not allowed to import module '{module}'; code blocks can import only {importable}"
+ for alias in node.names:
+ if isinstance(node, ast.ImportFrom) and (
+ alias.name == "*" or alias.name.startswith("_") or alias.name in BLOCKED_ATTRS
+ ):
+ return f"Not allowed to import '{alias.name}'"
+ if alias.asname is not None and alias.asname.startswith("__"):
+ return "Not allowed to access private methods or attributes"
+ return None
+
+
+class BindSandboxModuleImports(ast.NodeTransformer):
+ """Rewrites each import sandbox_import_error admits into an assignment from SANDBOX_MODULES_GLOBAL, recording
+ the names those imports bind."""
+
+ def __init__(self) -> None:
+ self.bound_names: set[str] = set()
+
+ def visit_Import(self, node: ast.Import) -> list[ast.stmt]:
+ self.bound_names.update(alias.asname or alias.name for alias in node.names)
+ return [
+ _bind_sandbox_name(alias.asname or alias.name, _sandbox_module(alias.name), node) for alias in node.names
+ ]
+
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> list[ast.stmt]:
+ self.bound_names.update(alias.asname or alias.name for alias in node.names)
+ module = _sandbox_module(node.module or "")
+ return [
+ _bind_sandbox_name(alias.asname or alias.name, ast.Attribute(module, alias.name, ast.Load()), node)
+ for alias in node.names
+ ]
+
+
+def _sandbox_module(name: str) -> ast.expr:
+ return ast.Subscript(ast.Name(SANDBOX_MODULES_GLOBAL, ast.Load()), ast.Constant(name), ast.Load())
+
+
+def _bind_sandbox_name(name: str, value: ast.expr, node: ast.stmt) -> ast.stmt:
+ return ast.copy_location(ast.Assign([ast.Name(name, ast.Store())], value), node)
+
+
def _is_self_or_super(node: ast.expr) -> bool:
return (isinstance(node, ast.Name) and node.id == "self") or (
isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "super"
@@ -671,13 +724,15 @@ def _validate_tree(
if isinstance(node, ast.ImportFrom) and any(alias.name == "*" for alias in node.names):
raise error_factory("Wildcard imports are not allowed")
if blocked_imports is None:
- raise error_factory("Not allowed to import modules")
- for module_name in _import_roots(node):
- if _normalized_import_root(module_name) in blocked_imports:
- raise error_factory(f"Not allowed to import module '{module_name}'")
- for module_path in _import_paths(node):
- if module_path in blocked_import_paths:
- raise error_factory(f"Not allowed to import module '{module_path}'")
+ if (reason := sandbox_import_error(node)) is not None:
+ raise error_factory(reason)
+ else:
+ for module_name in _import_roots(node):
+ if _normalized_import_root(module_name) in blocked_imports:
+ raise error_factory(f"Not allowed to import module '{module_name}'")
+ for module_path in _import_paths(node):
+ if module_path in blocked_import_paths:
+ raise error_factory(f"Not allowed to import module '{module_path}'")
if isinstance(node, ast.ImportFrom):
for alias in node.names:
if (
@@ -749,7 +804,7 @@ def is_safe_code(
*,
error_factory: Callable[[str], Exception] = InsecureCodeDetected,
) -> None:
- """Reject imports, private members, and known escape hatches.
+ """Reject imports of anything but the sandbox's own modules, private members, and known escape hatches.
Leaves bare builtin names like `globals`/`locals` unblocked here; the caller decides
whether and how those (and any other) builtins are bound in the dict it execs the
diff --git a/skyvern/forge/sdk/workflow/exceptions.py b/skyvern/forge/sdk/workflow/exceptions.py
index 127a237a6..37c4efa93 100644
--- a/skyvern/forge/sdk/workflow/exceptions.py
+++ b/skyvern/forge/sdk/workflow/exceptions.py
@@ -212,6 +212,14 @@ class CodeBlockTemplateSyntaxError(WorkflowDefinitionValidationException):
)
+class CodeBlockInsecureCodeError(WorkflowDefinitionValidationException):
+ def __init__(self, block_label: str, reason: str) -> None:
+ super().__init__(
+ f"Code block '{block_label}' can't run: {reason}",
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
+ )
+
+
class InvalidWaitBlockTime(WorkflowDefinitionValidationException):
def __init__(self, block_label: str, wait_sec: int, max_sec: int) -> None:
super().__init__(
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 63bbd5177..47fbb2674 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -225,6 +225,7 @@ from skyvern.forge.sdk.workflow.code_block_authorized_files import (
unbound_attach_authorized_file,
)
from skyvern.forge.sdk.workflow.code_block_safety import BLOCKED_ATTRS as CODE_BLOCK_BLOCKED_ATTRS
+from skyvern.forge.sdk.workflow.code_block_safety import SANDBOX_MODULES_GLOBAL, BindSandboxModuleImports
from skyvern.forge.sdk.workflow.code_block_safety import is_safe_code as _shared_is_safe_code
from skyvern.forge.sdk.workflow.code_block_safety import json_safe_default, module_shims, safe_builtins
from skyvern.forge.sdk.workflow.constants import OUTPUT_PARAMETER_MAX_VALUE_BYTES
@@ -6793,6 +6794,7 @@ class CodeBlock(Block):
def build_safe_vars() -> dict[str, Any]:
# Builtins live under __builtins__ rather than as globals so a workflow parameter can shadow
# a builtin name by normal scoping, matching codeblock_runtime.build_safe_vars.
+ shims = module_shims()
return {
"__builtins__": {
**safe_builtins(),
@@ -6802,7 +6804,8 @@ class CodeBlock(Block):
},
"print": print,
"sleep": asyncio.sleep,
- **module_shims(),
+ **shims,
+ SANDBOX_MODULES_GLOBAL: shims,
"ErrorCode": ErrorCode,
"otp": _code_block_otp_builtin,
"solve_captcha": _bind_code_block_solve_captcha(None, None),
@@ -6947,12 +6950,25 @@ class CodeBlock(Block):
full_code = f"""
async def wrapper({default_args}):
{code}
- return {{key: value for key, value in __capture_locals().items() if key not in __param_defaults}}
+ return {{
+ key: value
+ for key, value in __capture_locals().items()
+ if key not in __param_defaults and not __codeblock_sandbox_binding(key, value)
+ }}
"""
safe_vars["__capture_locals"] = locals
safe_vars["__param_defaults"] = parameter_defaults
+ # A name an import bound would otherwise reach the output as an unserializable placeholder.
+ sandbox_binding_ids = {
+ id(member) for shim in safe_vars[SANDBOX_MODULES_GLOBAL].values() for member in (shim, *vars(shim).values())
+ }
+ import_binder = BindSandboxModuleImports()
+ safe_vars["__codeblock_sandbox_binding"] = lambda key, value: (
+ key in import_binder.bound_names and id(value) in sandbox_binding_ids
+ )
# Compile under a recognizable filename so tracebacks map back to user code lines.
- compiled_code = compile(full_code, CODE_BLOCK_FILENAME, "exec")
+ tree = import_binder.visit(ast.parse(full_code, filename=CODE_BLOCK_FILENAME))
+ compiled_code = compile(ast.fix_missing_locations(tree), CODE_BLOCK_FILENAME, "exec")
inline_exec_context = skyvern_context.current()
LOG.info(
"codeblock.inline_exec_entered",
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.py
index cd722b10f..2857e6c57 100644
--- a/skyvern/forge/sdk/workflow/service.py
+++ b/skyvern/forge/sdk/workflow/service.py
@@ -13,7 +13,7 @@ import textwrap
import time
import unicodedata
import uuid
-from collections import deque
+from collections import Counter, deque
from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Sequence
from contextlib import asynccontextmanager, suppress
from dataclasses import dataclass, field
@@ -24,6 +24,7 @@ from http import HTTPStatus
from typing import Any, Literal, NamedTuple, TypeVar, cast, overload
import structlog
+from jinja2 import TemplateSyntaxError
from jinja2 import meta as jinja2_meta
from pydantic import BaseModel
from sqlalchemy import select, update
@@ -168,6 +169,7 @@ from skyvern.forge.sdk.workflow.browser_profile_key import (
build_workflow_browser_session_storage_key,
render_browser_profile_key,
)
+from skyvern.forge.sdk.workflow.code_block_safety import is_safe_code
from skyvern.forge.sdk.workflow.context_manager import (
WorkflowRunContext,
jinja_sandbox_env,
@@ -184,9 +186,11 @@ from skyvern.forge.sdk.workflow.credential_selection import (
)
from skyvern.forge.sdk.workflow.exceptions import (
BlockEngineNotEnabledError,
+ CodeBlockInsecureCodeError,
InvalidWorkflowDefinition,
WorkflowVersionConflict,
)
+from skyvern.forge.sdk.workflow.models._jinja import mask_jinja_in_python_comments
from skyvern.forge.sdk.workflow.models.block import (
_ENGINE_INERT_BLOCK_TYPES,
BaseTaskBlock,
@@ -10660,6 +10664,49 @@ class WorkflowService:
if isinstance(block, CodeBlock):
block.validate_code_template()
+ @staticmethod
+ def _validate_new_code_block_safety(
+ workflow_definition: WorkflowDefinition, prior_definition: WorkflowDefinition | None
+ ) -> None:
+ """Reject new code the runner's static check always refuses; each copy of code already in the prior version
+ stays saveable, so a flagged block in a branch that never runs cannot wedge later saves. Code with Jinja
+ statements, or that does not parse once its Jinja values are stood in for, is left to the runner's check."""
+ prior_code: Counter[str] = Counter(
+ block.code
+ for block in (get_all_blocks(prior_definition.blocks) if prior_definition is not None else [])
+ if isinstance(block, CodeBlock)
+ )
+ for block in get_all_blocks(workflow_definition.blocks):
+ if not isinstance(block, CodeBlock):
+ continue
+ if prior_code[block.code] > 0:
+ prior_code[block.code] -= 1
+ continue
+ try:
+ checked_code = WorkflowService._code_with_jinja_values_as_names(block.code)
+ if checked_code is not None:
+ is_safe_code(checked_code, error_factory=partial(CodeBlockInsecureCodeError, block.label))
+ except (SyntaxError, ValueError, RecursionError, MemoryError, TemplateSyntaxError):
+ continue
+
+ @staticmethod
+ def _code_with_jinja_values_as_names(code: str) -> str | None:
+ """The code with each `{{ }}` value replaced by a plain name, which is what the expression's rendered value
+ is to the static check; None when the code has Jinja statements or comments."""
+ parts: list[str] = []
+ in_value = False
+ for _, token_type, value in jinja_sandbox_env.lex(mask_jinja_in_python_comments(code)[0]):
+ if token_type == "data":
+ parts.append(value)
+ elif token_type == "variable_begin":
+ in_value = True
+ parts.append("jinja_value")
+ elif token_type == "variable_end":
+ in_value = False
+ elif not in_value:
+ return None
+ return "".join(parts)
+
async def create_workflow(
self,
organization_id: str,
@@ -16631,6 +16678,7 @@ class WorkflowService:
workflow_definition.validate()
self.validate_workflow_block_graph(workflow_definition)
self._validate_payload_templates(workflow_definition)
+ self._validate_new_code_block_safety(workflow_definition, None)
await encrypt_workflow_definition_secrets(workflow_definition, organization_id)
cdp_connect_headers = merge_masked_headers(request.cdp_connect_headers, None)
@@ -16865,6 +16913,11 @@ class WorkflowService:
# Reject workflow_trigger.payload entries with malformed Jinja2 (matches runtime PayloadTemplateRenderError)
self._validate_payload_templates(built_definition)
+ if validate_code_block_templates:
+ self._validate_new_code_block_safety(
+ built_definition,
+ existing_latest_workflow.workflow_definition if existing_latest_workflow else None,
+ )
saved_workflow = await self.update_workflow_definition(
workflow_id=allocated_workflow.workflow_id,
diff --git a/skyvern/services/task_v2_service.py b/skyvern/services/task_v2_service.py
index f333c674c..4bd0d53fd 100644
--- a/skyvern/services/task_v2_service.py
+++ b/skyvern/services/task_v2_service.py
@@ -1994,8 +1994,9 @@ def _build_compute_code(gathered: list[dict], snippet: str) -> str:
def _assert_compute_code_safe(code: str) -> None:
"""Validate that compute code is data-only, bounded, and ends with the output contract."""
- # is_safe_code blocks imports/dunders/blocked-attrs but not the browser/async/regex/exec names
- # the sandbox exposes, not unbounded loops, not the .format dunder escape, and not a guarded or
+ # is_safe_code blocks dunders/blocked-attrs but admits imports of the sandbox modules (an alias would
+ # carry a forbidden name past the bare-name check), and does not block the browser/async/regex/exec
+ # names the sandbox exposes, unbounded loops, the .format dunder escape, or a guarded or
# nested return that falls through to captured locals. Raise InsecureCodeDetected (caught by the
# regenerate loop) on violation.
# CodeBlock.execute Jinja-renders the whole code string before exec, and CODE blocks resolve
@@ -2010,6 +2011,8 @@ def _assert_compute_code_safe(code: str) -> None:
raise InsecureCodeDetected("compute code must be synchronous (no await/async)")
if isinstance(node, (ast.While,)):
raise InsecureCodeDetected("compute code may not use while loops")
+ if isinstance(node, (ast.Import, ast.ImportFrom)):
+ raise InsecureCodeDetected("compute code may not import modules")
if isinstance(node, ast.Name) and node.id in _COMPUTE_FORBIDDEN_NAMES:
raise InsecureCodeDetected(f"compute code may not reference '{node.id}'")
if isinstance(node, ast.Attribute) and node.attr in _COMPUTE_FORBIDDEN_ATTRS:
diff --git a/tests/unit/test_code_block_sandbox.py b/tests/unit/test_code_block_sandbox.py
index 1c4ad0260..8e69a0259 100644
--- a/tests/unit/test_code_block_sandbox.py
+++ b/tests/unit/test_code_block_sandbox.py
@@ -258,22 +258,64 @@ def datetime_facade_defects(namespace: SimpleNamespace, sandbox_builtins: Mappin
# ---------------------------------------------------------------------------
-class TestIsSafeCodeRejectsImports:
- def test_import_os(self) -> None:
- with pytest.raises(InsecureCodeDetected, match="import"):
- CodeBlock.is_safe_code("import os")
-
- def test_import_subprocess(self) -> None:
- with pytest.raises(InsecureCodeDetected, match="import"):
- CodeBlock.is_safe_code("import subprocess")
-
- def test_from_import(self) -> None:
- with pytest.raises(InsecureCodeDetected, match="import"):
- CodeBlock.is_safe_code("from os import system")
-
- def test_import_asyncio(self) -> None:
- with pytest.raises(InsecureCodeDetected, match="import"):
- CodeBlock.is_safe_code("import asyncio")
+class TestIsSafeCodeImports:
+ @pytest.mark.parametrize(
+ "code",
+ [
+ "import os",
+ "import subprocess",
+ "from os import system",
+ "import re, os",
+ "import datetime.timezone",
+ "from . import re",
+ "from re import *",
+ "from re import _compile",
+ "import re as __builtins__",
+ "from json import loads as __capture_locals",
+ ],
+ )
+ def test_rejects_imports_beyond_the_sandbox_modules(self, code: str) -> None:
+ with pytest.raises(InsecureCodeDetected, match="import|private"):
+ CodeBlock.is_safe_code(code)
+
+ @pytest.mark.parametrize(
+ "code",
+ [
+ "import asyncio",
+ "import re",
+ "import json as j",
+ "from datetime import date, timedelta",
+ "from html import escape",
+ ],
+ )
+ def test_admits_imports_of_the_sandbox_modules(self, code: str) -> None:
+ CodeBlock.is_safe_code(code)
+
+ @pytest.mark.asyncio
+ async def test_an_admitted_import_binds_the_sandbox_shim(self) -> None:
+ code = """
+import re
+import json as j
+from datetime import date, timedelta
+
+def next_day():
+ import datetime
+ return datetime.date(2026, 1, 1) + timedelta(days=1)
+
+return [re.search("b", "abc").group(0), j.dumps([1]), date(2026, 1, 1).isoformat(), next_day().isoformat()]
+"""
+ now = datetime.now(UTC)
+ output_parameter = OutputParameter(
+ parameter_type=ParameterType.OUTPUT,
+ key="imports_output",
+ output_parameter_id="op_imports",
+ workflow_id="w_test",
+ created_at=now,
+ modified_at=now,
+ )
+ block = CodeBlock(label="imports", code=code, output_parameter=output_parameter)
+ result = await block.generate_async_user_function(code, MagicMock(), parameters={"datetime": "param"})()
+ assert result == ["b", "[1]", "2026-01-01", "2026-01-02"]
class TestIsSafeCodeRejectsDunderAccess:
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index bffaf4d99..8a667a0a3 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -7727,7 +7727,6 @@ class TestCopilotConfig:
pytest.param(SimpleNamespace(final_output="", new_items=[]), id="empty"),
pytest.param(RuntimeError("provider unavailable"), id="failed"),
pytest.param(CopilotTotalTimeoutError(), id="reply_timed_out"),
- pytest.param(asyncio.CancelledError(), id="user_stopped_during_reply"),
],
)
async def test_budget_expiry_reply_that_fails_keeps_the_typed_no_report_fact(
@@ -7749,6 +7748,26 @@ class TestCopilotConfig:
assert outcome.budget_expiry_report_produced is False
assert outcome.tool_calls == ["update_and_run_blocks"]
+ @pytest.mark.asyncio
+ async def test_stop_during_the_budget_expiry_reply_is_saved_as_a_stop(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ self._record_run_still_going(monkeypatch)
+ run = await _run_tool_bearing_empty_completion_turn(
+ monkeypatch,
+ asyncio.CancelledError(),
+ attempts=(_EnforcementAttempt(error=CopilotTotalTimeoutError()),),
+ during_attempt=self._hit_hard_backstop,
+ )
+
+ assert run.result.cancelled is True
+ assert run.result.user_response == ""
+ outcome = run.result.turn_outcome
+ assert outcome is not None
+ assert outcome.terminal_reason == "timeout"
+ assert outcome.budget_expired is True
+ assert outcome.budget_expiry_report_produced is None
+
@staticmethod
def _withheld_reply(*reason_codes: OutputPolicyReason, user_response: str = "") -> OutputGuardrailTripwireTriggered:
guardrail_result = MagicMock()
diff --git a/tests/unit/test_copilot_budget_drain.py b/tests/unit/test_copilot_budget_drain.py
index 16d6559c9..07c29eaca 100644
--- a/tests/unit/test_copilot_budget_drain.py
+++ b/tests/unit/test_copilot_budget_drain.py
@@ -48,6 +48,7 @@ from skyvern.forge.sdk.copilot.tools.run_execution import (
hydrate_prior_run_packet,
recorded_open_step_runs,
)
+from skyvern.forge.sdk.copilot.turn_outcome import CANCEL_TERMINAL_REASON
from skyvern.forge.sdk.schemas.copilot_turn_outcome import ResponseKind, TurnOutcome
from skyvern.forge.sdk.schemas.workflow_copilot import (
WorkflowCopilotChatHistoryMessage,
@@ -988,10 +989,14 @@ async def test_stop_still_cancels_the_active_build_test(
with pytest.raises(asyncio.CancelledError):
await turn
left_run_ids = _saved_left_run_ids(ctx)
+ saved = agent_module._build_cancelled_exit_result(ctx, None)
await settle_cancelled_tools()
assert left_run_ids == []
- assert ctx.copilot_total_timeout_exceeded is (elapsed_at_stop >= 900)
+ assert saved.cancelled is True
+ assert saved.turn_outcome is not None
+ assert saved.turn_outcome.terminal_reason == CANCEL_TERMINAL_REASON
+ assert not saved.turn_outcome.budget_expired
assert owned.cancel_writes == [OWNED_RUN_ID]
assert owned.row.status == "canceled"
assert harness["executor_cancelled"] is not dispatch_to_worker
diff --git a/tests/unit/test_copilot_code_block_synthesis.py b/tests/unit/test_copilot_code_block_synthesis.py
index b125d2cf9..11053b758 100644
--- a/tests/unit/test_copilot_code_block_synthesis.py
+++ b/tests/unit/test_copilot_code_block_synthesis.py
@@ -1912,6 +1912,17 @@ class TestPreflightSurfacesSyntaxError:
diagnostics = preflight_code_block(result.code, parameter_keys=())
assert not any(d.code == "SYNTAX_ERROR" for d in diagnostics)
+ @pytest.mark.parametrize(
+ "code",
+ [
+ 'm = re.search("(", "abc")',
+ 'import re as rx\nm = rx.search("(", "abc")',
+ 'from re import search as s\nm = s("(", "abc")',
+ ],
+ )
+ def test_invalid_regex_literal_is_caught_however_re_is_bound(self, code: str) -> None:
+ assert "INVALID_REGEX_LITERAL" in [d.code for d in preflight_code_block(code, parameter_keys=())]
+
def test_unparseable_block_surfaces_syntax_diagnostic(self) -> None:
# A malformed block must be caught at authoring time, not swallowed into a silent run-time failure.
diagnostics = preflight_code_block('await page.goto("unterminated)\n', parameter_keys=())
diff --git a/tests/unit/test_copilot_enforcement_pruning.py b/tests/unit/test_copilot_enforcement_pruning.py
index de0322176..c4452463a 100644
--- a/tests/unit/test_copilot_enforcement_pruning.py
+++ b/tests/unit/test_copilot_enforcement_pruning.py
@@ -9,7 +9,6 @@ These cover three regressions observed in trace 019d7b5c884dff0ff648680b9f31f715
from __future__ import annotations
import json
-import time
from copy import deepcopy
from types import SimpleNamespace
from typing import Any
@@ -33,7 +32,6 @@ from skyvern.forge.sdk.copilot.enforcement import (
NUDGE_SENTINEL,
TOTAL_TIMEOUT_SECONDS,
_mark_copilot_total_timeout,
- _mark_copilot_total_timeout_if_elapsed,
_prune_input_list,
_recover_from_context_overflow,
_summarize_tool_output,
@@ -1401,30 +1399,6 @@ def test_deadline_flag_still_written_when_fingerprint_is_suppressed() -> None:
assert ctx.copilot_total_timeout_exceeded is True
[email protected]("iteration", [0, 5, 11])
-def test_cancel_site_helper_threads_iteration_into_the_fingerprint(iteration: int) -> None:
- ctx = _deadline_ctx()
- start_time = time.monotonic() - (TOTAL_TIMEOUT_SECONDS + 5.0)
-
- with capture_logs() as logs:
- _mark_copilot_total_timeout_if_elapsed(ctx, start_time, iteration)
-
- events = _deadline_events(logs)
- assert len(events) == 1
- assert events[0]["iteration"] == iteration
- assert events[0]["elapsed_seconds"] >= TOTAL_TIMEOUT_SECONDS
-
-
-def test_cancel_site_helper_is_silent_before_the_deadline() -> None:
- ctx = _deadline_ctx()
-
- with capture_logs() as logs:
- _mark_copilot_total_timeout_if_elapsed(ctx, time.monotonic(), 2)
-
- assert _deadline_events(logs) == []
- assert ctx.copilot_total_timeout_exceeded is False
-
-
def test_total_timeout_override_binds_on_settings_and_defaults_unset() -> None:
unset = Settings(_env_file=None, WORKFLOW_COPILOT_TOTAL_TIMEOUT_SECONDS=None)
overridden = Settings(_env_file=None, WORKFLOW_COPILOT_TOTAL_TIMEOUT_SECONDS=300)
diff --git a/tests/unit/test_copilot_frontier.py b/tests/unit/test_copilot_frontier.py
index 458ebc1ef..b27efbd01 100644
--- a/tests/unit/test_copilot_frontier.py
+++ b/tests/unit/test_copilot_frontier.py
@@ -1357,8 +1357,12 @@ def _static_goto_code() -> str:
@pytest.mark.parametrize(
"code",
- [None, 'await page.goto(url="https://example.com/orders")\n'],
- ids=["synthesized_indented", "url_keyword"],
+ [
+ None,
+ 'await page.goto(url="https://example.com/orders")\n',
+ 'import re\nawait page.goto("https://example.com/orders")\n',
+ ],
+ ids=["synthesized_indented", "url_keyword", "after_import"],
)
def test_plan_frontier_head_code_block_with_static_goto_starts_initial(code: str | None) -> None:
code = code or _static_goto_code()
diff --git a/tests/unit/test_copilot_model_telemetry.py b/tests/unit/test_copilot_model_telemetry.py
index b40248f59..7b94dcf68 100644
--- a/tests/unit/test_copilot_model_telemetry.py
+++ b/tests/unit/test_copilot_model_telemetry.py
@@ -36,11 +36,17 @@ from structlog.testing import capture_logs
from skyvern.cli.mcp_tools.blocks import skyvern_block_schema
from skyvern.forge.sdk.copilot import agent as copilot_agent_module
from skyvern.forge.sdk.copilot import cache_envelope as cache_envelope_module
+from skyvern.forge.sdk.copilot import enforcement as enforcement_module
from skyvern.forge.sdk.copilot import model_telemetry as model_telemetry_module
from skyvern.forge.sdk.copilot.browser_ablation import CopilotEvalMode
from skyvern.forge.sdk.copilot.cache_envelope import CacheableSystemInstructions
from skyvern.forge.sdk.copilot.config import CopilotConfig
-from skyvern.forge.sdk.copilot.enforcement import NUDGE_SENTINEL, SCREENSHOT_SENTINEL, _prune_input_list
+from skyvern.forge.sdk.copilot.enforcement import (
+ NUDGE_SENTINEL,
+ SCREENSHOT_SENTINEL,
+ CopilotTotalTimeoutError,
+ _prune_input_list,
+)
from skyvern.forge.sdk.copilot.llm_errors import is_retriable_llm_error
from skyvern.forge.sdk.copilot.mcp_adapter import _copilot_to_call_tool_result
from skyvern.forge.sdk.copilot.model_telemetry import (
@@ -1312,9 +1318,10 @@ async def test_browser_ablation_timeout_reports_active_model_and_browser_work(
if fallback_enabled and attempt_count == 1:
raise FakeRateLimitError("rate limit")
ctx = cast(copilot_agent_module.CopilotContext, kwargs["ctx"])
- ctx.copilot_total_timeout_exceeded = True
+ ctx.budget_expiry_state.hard_backstop_reached = True
+ enforcement_module._mark_copilot_total_timeout(ctx, elapsed_seconds=990.0, iteration=0)
ctx.eval_tool_activity = [{"tool_name": "navigate_browser", "success": True}]
- raise asyncio.CancelledError
+ raise CopilotTotalTimeoutError
monkeypatch.setattr(
"skyvern.forge.sdk.copilot.agent._resolve_live_browser_session_id", AsyncMock(return_value=None)
diff --git a/tests/unit/test_copilot_runner_deadline.py b/tests/unit/test_copilot_runner_deadline.py
index 52a9e5683..f48709125 100644
--- a/tests/unit/test_copilot_runner_deadline.py
+++ b/tests/unit/test_copilot_runner_deadline.py
@@ -253,19 +253,21 @@ async def _cancel_at_boundary(
return logs, stream_calls["n"]
[email protected]("elapsed", [588.0, TOTAL_TIMEOUT_SECONDS + 50.0])
@pytest.mark.parametrize("boundary", ["first", "overflow", "retry"])
@pytest.mark.asyncio
-async def test_sub_budget_cancellation_records_once_at_every_model_call_boundary(
+async def test_a_cancellation_records_once_at_every_model_call_boundary_and_never_as_the_deadline(
monkeypatch: pytest.MonkeyPatch,
boundary: str,
+ elapsed: float,
) -> None:
ctx = _cancellation_ctx()
- logs, stream_calls = await _cancel_at_boundary(monkeypatch, boundary=boundary, elapsed=588.0, ctx=ctx)
+ logs, stream_calls = await _cancel_at_boundary(monkeypatch, boundary=boundary, elapsed=elapsed, ctx=ctx)
events = _cancellation_events(logs)
assert len(events) == 1
- assert 588.0 <= events[0]["elapsed_seconds"] < TOTAL_TIMEOUT_SECONDS
+ assert events[0]["elapsed_seconds"] >= elapsed
assert events[0]["iteration"] == 0
assert events[0]["deadline_exceeded"] is False
assert _deadline_events(logs) == []
@@ -275,41 +277,6 @@ async def test_sub_budget_cancellation_records_once_at_every_model_call_boundary
assert stream_calls == 2, "the retry boundary must run after an overflow recovery"
-async def test_over_budget_cancellation_records_the_deadline_beside_the_cancellation(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- ctx = _cancellation_ctx()
-
- logs, _ = await _cancel_at_boundary(monkeypatch, boundary="first", elapsed=950.0, ctx=ctx)
-
- events = _cancellation_events(logs)
- assert len(events) == 1
- assert events[0]["elapsed_seconds"] >= TOTAL_TIMEOUT_SECONDS
- assert events[0]["deadline_exceeded"] is True
- assert len(_deadline_events(logs)) == 1
- assert ctx.copilot_total_timeout_exceeded is True
-
-
-async def test_a_broken_recorder_neither_masks_nor_delays_the_cancellation(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- def exploding_mark(ctx: Any, start_time: float, iteration: int) -> None:
- raise RuntimeError("recorder is broken")
-
- monkeypatch.setattr(
- "skyvern.forge.sdk.copilot.enforcement._mark_copilot_total_timeout_if_elapsed",
- exploding_mark,
- )
- ctx = _cancellation_ctx()
-
- logs, _ = await _cancel_at_boundary(monkeypatch, boundary="first", elapsed=588.0, ctx=ctx)
-
- assert _cancellation_events(logs) == []
- assert any(entry.get("event") == "Failed to record a copilot turn cancellation" for entry in logs)
-
-
@pytest.mark.asyncio
async def test_deadline_event_names_the_operation_still_open_when_the_budget_expires(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/test_request_logging.py b/tests/unit/test_request_logging.py
index 0a6fb81e7..fb04b103e 100644
--- a/tests/unit/test_request_logging.py
+++ b/tests/unit/test_request_logging.py
@@ -622,6 +622,14 @@ class TestSanitizeBody:
result = _sanitize_body(request, b'{"code": "4/0Adeu...", "state": "nonce"}', "application/json")
assert result == REDACTED
+ @pytest.mark.parametrize("path", ["/api/v1/skyplane/authority/session", "/api/v1/skyplane/authority/feedback"])
+ def test_skyplane_authority_request_and_response_are_fully_redacted(self, path: str) -> None:
+ request = _make_request("POST", path)
+ body = '{"job_capability":"cap-secret","summary":"customer text","details":"more customer text"}'
+
+ assert _sanitize_body(request, body.encode(), "application/json") == REDACTED
+ assert _sanitize_response_body(request, body, "application/json") == REDACTED
+
def test_non_sensitive_endpoint_request_preserved(self) -> None:
request = _make_request("GET", "/v1/tasks")
result = _sanitize_body(request, b'{"user": "alice"}', "application/json")
diff --git a/tests/unit/test_task_v2_compute_task.py b/tests/unit/test_task_v2_compute_task.py
index 6a85663c0..cefd19aa2 100644
--- a/tests/unit/test_task_v2_compute_task.py
+++ b/tests/unit/test_task_v2_compute_task.py
@@ -253,6 +253,16 @@ class TestComputeCodeSafety:
with pytest.raises(InsecureCodeDetected):
task_v2_service._assert_compute_code_safe(code)
+ @pytest.mark.parametrize(
+ "snippet",
+ ['import re as rx\nreturn {"output": rx.findall("a", "a")}', 'from re import findall\nreturn {"output": 1}'],
+ )
+ def test_sandbox_module_import_rejected(self, snippet: str) -> None:
+ code = task_v2_service._build_compute_code(GATHERED, snippet)
+ CodeBlock.is_safe_code(code) # is_safe_code admits sandbox-module imports
+ with pytest.raises(InsecureCodeDetected, match="import"):
+ task_v2_service._assert_compute_code_safe(code)
+
def test_await_rejected(self) -> None:
code = task_v2_service._build_compute_code(GATHERED, PAGE_SNIPPET)
with pytest.raises(InsecureCodeDetected):
diff --git a/tests/unit/test_workflow_browser_profile_id.py b/tests/unit/test_workflow_browser_profile_id.py
index 3b0d616e8..f6318e991 100644
--- a/tests/unit/test_workflow_browser_profile_id.py
+++ b/tests/unit/test_workflow_browser_profile_id.py
@@ -723,6 +723,7 @@ def _make_workflow_update_service(
pin_saved_session_ip=existing_pin_saved_session_ip,
webhook_callback_url=existing_webhook_callback_url,
created_by=existing_created_by,
+ workflow_definition=WorkflowDefinition(parameters=[], blocks=[]),
)
potential_workflow = SimpleNamespace(workflow_id="wf_new")
updated_workflow = SimpleNamespace(
diff --git a/tests/unit/workflow/test_code_block_template_validation.py b/tests/unit/workflow/test_code_block_template_validation.py
index 773444379..c2fe051a5 100644
--- a/tests/unit/workflow/test_code_block_template_validation.py
+++ b/tests/unit/workflow/test_code_block_template_validation.py
@@ -6,7 +6,11 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from skyvern.config import settings
-from skyvern.forge.sdk.workflow.exceptions import BlockEngineNotEnabledError, CodeBlockTemplateSyntaxError
+from skyvern.forge.sdk.workflow.exceptions import (
+ BlockEngineNotEnabledError,
+ CodeBlockInsecureCodeError,
+ CodeBlockTemplateSyntaxError,
+)
from skyvern.forge.sdk.workflow.models.block import CodeBlock, ForLoopBlock, TaskBlock
from skyvern.forge.sdk.workflow.models.parameter import OutputParameter
from skyvern.forge.sdk.workflow.models.workflow import WorkflowDefinition
@@ -48,6 +52,40 @@ def test_save_validator_allows_syntactically_valid_undefined_reference() -> None
WorkflowService._validate_code_block_templates(_definition([_code_block("code", "value = {{ future_value }}")]))
+def test_save_rejects_new_code_the_runner_always_refuses() -> None:
+ prior = _definition([_code_block("legacy", "import os\nvalue = 1")])
+ renamed_legacy = _code_block("renamed", "import os\nvalue = 1")
+ sandbox_import = _code_block("shim", "import re\nvalue = re.escape('a')")
+ jinja_statement = _code_block("jinja", "{% if flag %}value = 1{% endif %}")
+ # Each value renders to a literal before the runner checks it, so the expression itself is not code.
+ jinja_values = _code_block(
+ "jinja_values",
+ "price = {{ '{:.2f}'.format(total) }}\ndoc_id = {{ api_output._id | tojson }}\nurl = \"{{ base }}/x\"",
+ )
+ too_deep = _code_block("too_deep", "x = " + "-" * 20000 + "1")
+ WorkflowService._validate_new_code_block_safety(
+ _definition([renamed_legacy, sandbox_import, jinja_statement, jinja_values, too_deep]), prior
+ )
+ # The exemption covers each prior copy once, so duplicating a grandfathered block does not grandfather the copy.
+ copied_legacy = _code_block("legacy_copy", "import os\nvalue = 1")
+ with pytest.raises(CodeBlockInsecureCodeError, match="'legacy_copy'"):
+ WorkflowService._validate_new_code_block_safety(_definition([renamed_legacy, copied_legacy]), prior)
+ # The runtime render masks Jinja inside Python comments, so a commented tag must not hide the import.
+ commented_tag = _code_block("commented_tag", "# wrap in {% if flag %} later\nimport os")
+ with pytest.raises(CodeBlockInsecureCodeError, match="commented_tag"):
+ WorkflowService._validate_new_code_block_safety(_definition([commented_tag]), None)
+
+ nested = _code_block("nested_code", 'import subprocess\nurl = "{{ base }}/x"')
+ loop = ForLoopBlock(label="loop", loop_blocks=[nested], output_parameter=_output_parameter("loop"))
+ with pytest.raises(CodeBlockInsecureCodeError) as excinfo:
+ WorkflowService._validate_new_code_block_safety(_definition([renamed_legacy, loop]), prior)
+
+ assert excinfo.value.status_code == 422
+ assert str(excinfo.value).startswith(
+ "Code block 'nested_code' can't run: Not allowed to import module 'subprocess'"
+ )
+
+
def test_save_validator_rejects_unknown_jinja_filter() -> None:
definition = _definition([_code_block("code", "value = {{ future_value | missing_filter }}")])
diff --git a/uv.lock b/uv.lock
index eeb5ff5da..8fd435a57 100644
--- a/uv.lock
+++ b/uv.lock
@@ -3654,7 +3654,7 @@ wheels = [
[[package]]
name = "mcp"
-version = "1.28.1"
+version = "1.30.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "anyio" },
@@ -3672,9 +3672,9 @@ dependencies = [
{ name = "typing-inspection" },
{ name = "uvicorn", marker = "sys_platform != 'emscripten'" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/6e/77/9450b8f251a13affb6281997d0523c4615f8a8b35d0b21ff30db3a5aac9d/mcp-1.28.1.tar.gz", hash = "sha256:d51e36a5f5644faea4f85ea649bfffa6bc6c26770d42798ad6a3de3d2ba69683", size = 638501, upload-time = "2026-06-26T12:57:29.093Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/ba/93/0142dc84a666daf8ad51a34268f34c12fd6fda4f3810c4be2504eecc8212/mcp-1.30.0.tar.gz", hash = "sha256:445414625fce5c295faa505bb11bacece661ab6f4028d57c935db57820b7a3e4", size = 680511, upload-time = "2026-09-07T14:34:15.845Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/e2/5e/d118fce19f87a2e7d8101c35c8ae0ec289098a4df0ff244cec23e415aca0/mcp-1.28.1-py3-none-any.whl", hash = "sha256:2726bca5e7193f61c5dde8b12500a6de2d9acf6d1a1c0be9e8c2e706437991df", size = 222620, upload-time = "2026-06-26T12:57:27.218Z" },
+ { url = "https://files.pythonhosted.org/packages/f5/f4/e58bc33317c92a0203664daaf00bf6f41166cc0149e5d6870a03f7cd004a/mcp-1.30.0-py3-none-any.whl", hash = "sha256:666edb5009503e1047c9d60346a756f94b261f05cc2625f23d41c728ffc484d0", size = 234581, upload-time = "2026-09-07T14:34:14.266Z" },
]
[[package]]