Skip to content

Automate browser based workflows with AI

feat: add fallback episode API endpoints (#4997)

pedrohsdbff24144a3e12
diff --git a/skyvern/forge/sdk/db/agent_db.py b/skyvern/forge/sdk/db/agent_db.py
index bfb4825dc..0fd81dc31 100644
--- a/skyvern/forge/sdk/db/agent_db.py
+++ b/skyvern/forge/sdk/db/agent_db.py
@@ -6040,6 +6040,32 @@ class AgentDB(BaseAlchemyDB):
LOG.error("UnexpectedError", exc_info=True)
raise
+ async def get_script_versions(
+ self,
+ script_id: str,
+ organization_id: str,
+ ) -> list[Script]:
+ """Get all versions of a script, ordered by version DESC."""
+ try:
+ async with self.Session() as session:
+ query = (
+ select(ScriptModel)
+ .filter(
+ ScriptModel.script_id == script_id,
+ ScriptModel.organization_id == organization_id,
+ ScriptModel.deleted_at.is_(None),
+ )
+ .order_by(ScriptModel.version.desc())
+ )
+ result = await session.scalars(query)
+ return [convert_to_script(row) for row in result.all()]
+ except SQLAlchemyError:
+ LOG.error("SQLAlchemyError", exc_info=True)
+ raise
+ except Exception:
+ LOG.error("UnexpectedError", exc_info=True)
+ raise
+
async def get_script_revision(self, script_revision_id: str, organization_id: str) -> Script | None:
async with self.Session() as session:
script = (
@@ -6677,6 +6703,94 @@ class AgentDB(BaseAlchemyDB):
LOG.error("SQLAlchemyError", exc_info=True)
raise
+ async def get_fallback_episodes(
+ self,
+ organization_id: str,
+ workflow_permanent_id: str,
+ page: int = 1,
+ page_size: int = 20,
+ workflow_run_id: str | None = None,
+ block_label: str | None = None,
+ reviewed: bool | None = None,
+ fallback_type: str | None = None,
+ ) -> list[ScriptFallbackEpisode]:
+ try:
+ async with self.Session() as session:
+ query = select(ScriptFallbackEpisodeModel).filter(
+ ScriptFallbackEpisodeModel.organization_id == organization_id,
+ ScriptFallbackEpisodeModel.workflow_permanent_id == workflow_permanent_id,
+ )
+ if workflow_run_id is not None:
+ query = query.filter(ScriptFallbackEpisodeModel.workflow_run_id == workflow_run_id)
+ if block_label is not None:
+ query = query.filter(ScriptFallbackEpisodeModel.block_label == block_label)
+ if reviewed is not None:
+ query = query.filter(ScriptFallbackEpisodeModel.reviewed == reviewed)
+ if fallback_type is not None:
+ query = query.filter(ScriptFallbackEpisodeModel.fallback_type == fallback_type)
+
+ offset = (page - 1) * page_size
+ query = query.order_by(ScriptFallbackEpisodeModel.created_at.desc()).limit(page_size).offset(offset)
+
+ result = await session.scalars(query)
+ return [ScriptFallbackEpisode.model_validate(row) for row in result.all()]
+ except SQLAlchemyError:
+ LOG.error("SQLAlchemyError", exc_info=True)
+ raise
+
+ async def get_fallback_episodes_count(
+ self,
+ organization_id: str,
+ workflow_permanent_id: str,
+ workflow_run_id: str | None = None,
+ block_label: str | None = None,
+ reviewed: bool | None = None,
+ fallback_type: str | None = None,
+ ) -> int:
+ try:
+ async with self.Session() as session:
+ query = (
+ select(func.count())
+ .select_from(ScriptFallbackEpisodeModel)
+ .filter(
+ ScriptFallbackEpisodeModel.organization_id == organization_id,
+ ScriptFallbackEpisodeModel.workflow_permanent_id == workflow_permanent_id,
+ )
+ )
+ if workflow_run_id is not None:
+ query = query.filter(ScriptFallbackEpisodeModel.workflow_run_id == workflow_run_id)
+ if block_label is not None:
+ query = query.filter(ScriptFallbackEpisodeModel.block_label == block_label)
+ if reviewed is not None:
+ query = query.filter(ScriptFallbackEpisodeModel.reviewed == reviewed)
+ if fallback_type is not None:
+ query = query.filter(ScriptFallbackEpisodeModel.fallback_type == fallback_type)
+
+ result = await session.scalar(query)
+ return result or 0
+ except SQLAlchemyError:
+ LOG.error("SQLAlchemyError", exc_info=True)
+ raise
+
+ async def get_fallback_episode(
+ self,
+ episode_id: str,
+ organization_id: str,
+ ) -> ScriptFallbackEpisode | None:
+ try:
+ async with self.Session() as session:
+ query = select(ScriptFallbackEpisodeModel).filter(
+ ScriptFallbackEpisodeModel.episode_id == episode_id,
+ ScriptFallbackEpisodeModel.organization_id == organization_id,
+ )
+ result = await session.scalar(query)
+ if result:
+ return ScriptFallbackEpisode.model_validate(result)
+ return None
+ except SQLAlchemyError:
+ LOG.error("SQLAlchemyError", exc_info=True)
+ raise
+
async def mark_episode_reviewed(
self,
episode_id: str,
diff --git a/skyvern/forge/sdk/routes/scripts.py b/skyvern/forge/sdk/routes/scripts.py
index fc56223fb..f3c43771d 100644
--- a/skyvern/forge/sdk/routes/scripts.py
+++ b/skyvern/forge/sdk/routes/scripts.py
@@ -14,11 +14,15 @@ from skyvern.schemas.scripts import (
CreateScriptRequest,
CreateScriptResponse,
DeployScriptRequest,
+ FallbackEpisodeListResponse,
Script,
ScriptBlocksRequest,
ScriptBlocksResponse,
ScriptCacheKeyValuesResponse,
+ ScriptFallbackEpisode,
ScriptStatus,
+ ScriptVersionListResponse,
+ ScriptVersionSummary,
)
from skyvern.services import script_service, workflow_script_service
@@ -248,6 +252,69 @@ async def get_script(
return script
+@base_router.get(
+ "/scripts/{script_id}/versions",
+ include_in_schema=False,
+ response_model=ScriptVersionListResponse,
+)
+@base_router.get(
+ "/scripts/{script_id}/versions/",
+ include_in_schema=False,
+ response_model=ScriptVersionListResponse,
+)
+async def get_script_versions(
+ script_id: str = Path(..., description="The script ID"),
+ current_org: Organization = Depends(org_auth_service.get_current_org),
+) -> ScriptVersionListResponse:
+ """List all versions of a script."""
+ scripts = await app.DATABASE.get_script_versions(
+ script_id=script_id,
+ organization_id=current_org.organization_id,
+ )
+ versions = [
+ ScriptVersionSummary(
+ version=s.version,
+ script_revision_id=s.script_revision_id,
+ created_at=s.created_at,
+ run_id=s.run_id,
+ )
+ for s in scripts
+ ]
+ return ScriptVersionListResponse(versions=versions)
+
+
+@base_router.get(
+ "/scripts/{script_id}/versions/{version}",
+ include_in_schema=False,
+ response_model=ScriptBlocksResponse,
+)
+@base_router.get(
+ "/scripts/{script_id}/versions/{version}/",
+ include_in_schema=False,
+ response_model=ScriptBlocksResponse,
+)
+async def get_script_version_code(
+ script_id: str = Path(..., description="The script ID"),
+ version: int = Path(..., description="The version number"),
+ current_org: Organization = Depends(org_auth_service.get_current_org),
+) -> ScriptBlocksResponse:
+ """Get a specific version's code blocks."""
+ script = await app.DATABASE.get_script(
+ script_id=script_id,
+ organization_id=current_org.organization_id,
+ version=version,
+ )
+ if not script:
+ raise HTTPException(status_code=404, detail="Script version not found")
+
+ return await get_script_blocks_response(
+ script_revision_id=script.script_revision_id,
+ organization_id=current_org.organization_id,
+ workflow_permanent_id=script_id,
+ include_main_script=True,
+ )
+
+
@base_router.get(
"/scripts",
response_model=list[Script],
@@ -699,3 +766,91 @@ async def clear_workflow_cache(
deleted_count=deleted_count,
message=f"Successfully cleared {deleted_count} database record(s) and {cache_cleared_count} in-memory cache entry(s) for workflow {workflow_permanent_id}",
)
+
+
+@base_router.get(
+ "/workflows/{workflow_permanent_id}/fallback-episodes",
+ include_in_schema=False,
+ response_model=FallbackEpisodeListResponse,
+)
+@base_router.get(
+ "/workflows/{workflow_permanent_id}/fallback-episodes/",
+ include_in_schema=False,
+ response_model=FallbackEpisodeListResponse,
+)
+async def get_fallback_episodes(
+ workflow_permanent_id: str = Path(..., description="The workflow permanent ID"),
+ current_org: Organization = Depends(org_auth_service.get_current_org),
+ page: int = Query(1, ge=1, description="Page number"),
+ page_size: int = Query(20, ge=1, le=100, description="Page size"),
+ workflow_run_id: str | None = Query(None, description="Filter by workflow run ID"),
+ block_label: str | None = Query(None, description="Filter by block label"),
+ reviewed: bool | None = Query(None, description="Filter by reviewed status"),
+ fallback_type: str | None = Query(None, description="Filter by fallback type"),
+) -> FallbackEpisodeListResponse:
+ # Verify workflow exists
+ workflow = await app.DATABASE.get_workflow_by_permanent_id(
+ workflow_permanent_id=workflow_permanent_id,
+ organization_id=current_org.organization_id,
+ )
+ if not workflow:
+ raise HTTPException(status_code=404, detail="Workflow not found")
+
+ episodes = await app.DATABASE.get_fallback_episodes(
+ organization_id=current_org.organization_id,
+ workflow_permanent_id=workflow_permanent_id,
+ page=page,
+ page_size=page_size,
+ workflow_run_id=workflow_run_id,
+ block_label=block_label,
+ reviewed=reviewed,
+ fallback_type=fallback_type,
+ )
+ total_count = await app.DATABASE.get_fallback_episodes_count(
+ organization_id=current_org.organization_id,
+ workflow_permanent_id=workflow_permanent_id,
+ workflow_run_id=workflow_run_id,
+ block_label=block_label,
+ reviewed=reviewed,
+ fallback_type=fallback_type,
+ )
+ return FallbackEpisodeListResponse(
+ episodes=episodes,
+ page=page,
+ page_size=page_size,
+ total_count=total_count,
+ )
+
+
+@base_router.get(
+ "/workflows/{workflow_permanent_id}/fallback-episodes/{episode_id}",
+ include_in_schema=False,
+ response_model=ScriptFallbackEpisode,
+)
+@base_router.get(
+ "/workflows/{workflow_permanent_id}/fallback-episodes/{episode_id}/",
+ include_in_schema=False,
+ response_model=ScriptFallbackEpisode,
+)
+async def get_fallback_episode(
+ workflow_permanent_id: str = Path(..., description="The workflow permanent ID"),
+ episode_id: str = Path(..., description="The episode ID"),
+ current_org: Organization = Depends(org_auth_service.get_current_org),
+) -> ScriptFallbackEpisode:
+ # Verify workflow exists
+ workflow = await app.DATABASE.get_workflow_by_permanent_id(
+ workflow_permanent_id=workflow_permanent_id,
+ organization_id=current_org.organization_id,
+ )
+ if not workflow:
+ raise HTTPException(status_code=404, detail="Workflow not found")
+
+ episode = await app.DATABASE.get_fallback_episode(
+ episode_id=episode_id,
+ organization_id=current_org.organization_id,
+ )
+ if not episode:
+ raise HTTPException(status_code=404, detail="Fallback episode not found")
+ if episode.workflow_permanent_id != workflow_permanent_id:
+ raise HTTPException(status_code=404, detail="Fallback episode not found")
+ return episode
diff --git a/skyvern/schemas/scripts.py b/skyvern/schemas/scripts.py
index 4da872022..49530c412 100644
--- a/skyvern/schemas/scripts.py
+++ b/skyvern/schemas/scripts.py
@@ -128,6 +128,19 @@ class Script(BaseModel):
deleted_at: datetime | None = Field(default=None, description="Timestamp when the script was soft deleted")
+class ScriptVersionSummary(BaseModel):
+ model_config = ConfigDict(from_attributes=True)
+
+ version: int
+ script_revision_id: str
+ created_at: datetime
+ run_id: str | None = None
+
+
+class ScriptVersionListResponse(BaseModel):
+ versions: list[ScriptVersionSummary]
+
+
class ScriptBlock(BaseModel):
script_block_id: str
organization_id: str
@@ -217,6 +230,13 @@ class ScriptFallbackEpisode(BaseModel):
modified_at: datetime
+class FallbackEpisodeListResponse(BaseModel):
+ episodes: list[ScriptFallbackEpisode]
+ page: int
+ page_size: int
+ total_count: int
+
+
class ScriptBranchHit(BaseModel):
model_config = ConfigDict(from_attributes=True)
diff --git a/skyvern/services/script_service.py b/skyvern/services/script_service.py
index c8d554833..c43eb0066 100644
--- a/skyvern/services/script_service.py
+++ b/skyvern/services/script_service.py
@@ -1,3 +1,4 @@
+import ast
import asyncio
import base64
import hashlib
@@ -2199,7 +2200,7 @@ def render_template(template: str, data: dict[str, Any] | None = None) -> str:
def render_list(template: str, data: dict[str, Any] | None = None) -> list[str]:
rendered_value = render_template(template, data)
- list_value = eval(rendered_value)
+ list_value = ast.literal_eval(rendered_value)
if isinstance(list_value, list):
return list_value
else:
diff --git a/tests/unit/test_render_list.py b/tests/unit/test_render_list.py
new file mode 100644
index 000000000..3cc3b42f6
--- /dev/null
+++ b/tests/unit/test_render_list.py
@@ -0,0 +1,64 @@
+import pytest
+
+from skyvern.services.script_service import render_list
+
+
+class TestRenderListBlocksExploits:
+ """render_list() must reject all non-literal expressions."""
+
+ @pytest.mark.parametrize(
+ "payload,description",
+ [
+ ("__import__('os').system('id')", "OS command execution"),
+ ("__import__('os').popen('cat /etc/passwd').read()", "File read via popen"),
+ ("__import__('subprocess').check_output(['whoami'])", "Subprocess execution"),
+ ("__import__('os').environ", "Environment variable access"),
+ ("open('/etc/passwd').read()", "Direct file read"),
+ ("(lambda: __import__('os').system('id'))()", "Lambda-wrapped execution"),
+ ("eval('1+1')", "Nested eval"),
+ ("exec('import os')", "exec() call"),
+ (
+ "[x for x in ().__class__.__bases__[0].__subclasses__() if 'warning' in str(x)][0]()._module.__builtins__['__import__']('os').system('id')",
+ "Class hierarchy escape",
+ ),
+ ],
+ )
+ def test_rejects_malicious_input(self, payload: str, description: str) -> None:
+ with pytest.raises((ValueError, SyntaxError, TypeError)):
+ render_list(payload)
+
+ def test_rejects_function_calls(self) -> None:
+ with pytest.raises((ValueError, SyntaxError)):
+ render_list("print('hello')")
+
+
+class TestRenderListNormalUsage:
+ """Legitimate render_list() inputs must still parse correctly."""
+
+ def test_list_of_strings(self) -> None:
+ result = render_list("['[email protected]', '[email protected]']")
+ assert result == ["[email protected]", "[email protected]"]
+
+ def test_single_string_wrapped_in_list(self) -> None:
+ result = render_list("'[email protected]'")
+ assert result == ["[email protected]"]
+
+ def test_list_of_numbers(self) -> None:
+ result = render_list("[1, 2, 3]")
+ assert result == [1, 2, 3]
+
+ def test_empty_list(self) -> None:
+ result = render_list("[]")
+ assert result == []
+
+ def test_nested_list(self) -> None:
+ result = render_list("[['a', 'b'], ['c']]")
+ assert result == [["a", "b"], ["c"]]
+
+ def test_jinja_template_rendering(self) -> None:
+ result = render_list("['{{ name }}']", data={"name": "alice"})
+ assert result == ["alice"]
+
+ def test_jinja_template_resolves_to_list_literal(self) -> None:
+ result = render_list("{{ items }}", data={"items": "['a', 'b']"})
+ assert result == ["a", "b"]