Skip to content

Automate browser based workflows with AI

Add database schema and data layer for adaptive caching (1/8) (#4908)

pedrohsdbfcf9ef6cad0b
diff --git a/alembic/versions/2026_02_27_1200-700dfebe7c5f_add_adaptive_caching_tables.py b/alembic/versions/2026_02_27_1200-700dfebe7c5f_add_adaptive_caching_tables.py
new file mode 100644
index 000000000..2a35e36f7
--- /dev/null
+++ b/alembic/versions/2026_02_27_1200-700dfebe7c5f_add_adaptive_caching_tables.py
@@ -0,0 +1,100 @@
+"""add_adaptive_caching_tables
+
+Revision ID: 700dfebe7c5f
+Revises: dc37d888db44
+Create Date: 2026-02-27 12:00:00.000000+00:00
+
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = "700dfebe7c5f"
+down_revision: Union[str, None] = "dc37d888db44"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ # Add adaptive_caching and generate_script_on_terminal columns to workflows table
+ op.add_column(
+ "workflows",
+ sa.Column("adaptive_caching", sa.Boolean(), nullable=False, server_default=sa.false()),
+ )
+ op.add_column(
+ "workflows",
+ sa.Column("generate_script_on_terminal", sa.Boolean(), nullable=False, server_default=sa.false()),
+ )
+
+ # Add requires_agent column to script_blocks table
+ op.add_column(
+ "script_blocks",
+ sa.Column("requires_agent", sa.Boolean(), nullable=False, server_default=sa.false()),
+ )
+
+ # Create script_fallback_episodes table
+ op.create_table(
+ "script_fallback_episodes",
+ sa.Column("episode_id", sa.String(), nullable=False),
+ sa.Column("organization_id", sa.String(), nullable=False),
+ sa.Column("workflow_permanent_id", sa.String(), nullable=False),
+ sa.Column("workflow_run_id", sa.String(), nullable=False),
+ sa.Column("script_revision_id", sa.String(), nullable=True),
+ sa.Column("block_label", sa.String(), nullable=False),
+ sa.Column("fallback_type", sa.String(), nullable=False),
+ sa.Column("error_message", sa.UnicodeText(), nullable=True),
+ sa.Column("classify_result", sa.String(), nullable=True),
+ sa.Column("agent_actions", sa.JSON(), nullable=True),
+ sa.Column("page_url", sa.String(), nullable=True),
+ sa.Column("page_text_snapshot", sa.UnicodeText(), nullable=True),
+ sa.Column("fallback_succeeded", sa.Boolean(), nullable=True),
+ sa.Column("reviewed", sa.Boolean(), nullable=False, server_default=sa.false()),
+ sa.Column("reviewer_output", sa.UnicodeText(), nullable=True),
+ sa.Column("new_script_revision_id", sa.String(), nullable=True),
+ sa.Column("created_at", sa.DateTime(), nullable=False),
+ sa.Column("modified_at", sa.DateTime(), nullable=False),
+ sa.PrimaryKeyConstraint("episode_id"),
+ )
+ op.create_index(
+ "sfe_org_wpid_index",
+ "script_fallback_episodes",
+ ["organization_id", "workflow_permanent_id"],
+ )
+ op.create_index(
+ "sfe_org_created_at_index",
+ "script_fallback_episodes",
+ ["organization_id", "created_at"],
+ )
+
+ # Create script_branch_hits table
+ op.create_table(
+ "script_branch_hits",
+ sa.Column("organization_id", sa.String(), nullable=False),
+ sa.Column("workflow_permanent_id", sa.String(), nullable=False),
+ sa.Column("block_label", sa.String(), nullable=False),
+ sa.Column("branch_key", sa.String(), nullable=False),
+ sa.Column("hit_count", sa.Integer(), nullable=False, server_default=sa.text("1")),
+ sa.Column("first_hit_at", sa.DateTime(), nullable=False),
+ sa.Column("last_hit_at", sa.DateTime(), nullable=False),
+ sa.PrimaryKeyConstraint("organization_id", "workflow_permanent_id", "block_label", "branch_key"),
+ )
+ op.create_index(
+ "sbh_org_wpid_index",
+ "script_branch_hits",
+ ["organization_id", "workflow_permanent_id"],
+ )
+
+
+def downgrade() -> None:
+ op.drop_index("sbh_org_wpid_index", table_name="script_branch_hits")
+ op.drop_table("script_branch_hits")
+ op.drop_index("sfe_org_created_at_index", table_name="script_fallback_episodes")
+ op.drop_index("sfe_org_wpid_index", table_name="script_fallback_episodes")
+ op.drop_table("script_fallback_episodes")
+ op.drop_column("script_blocks", "requires_agent")
+ op.drop_column("workflows", "generate_script_on_terminal")
+ op.drop_column("workflows", "adaptive_caching")
diff --git a/skyvern/forge/sdk/core/skyvern_context.py b/skyvern/forge/sdk/core/skyvern_context.py
index 5c998e6a4..6994d34a3 100644
--- a/skyvern/forge/sdk/core/skyvern_context.py
+++ b/skyvern/forge/sdk/core/skyvern_context.py
@@ -53,6 +53,9 @@ class SkyvernContext:
script_run_parameters: dict[str, Any] = field(default_factory=dict)
script_mode: bool = False
ai_mode_override: str | None = None
+ script_llm_call_count: int = 0
+ last_classify_result: str | None = None
+ skip_complete_verification: bool = False
# magic link handling
# task_id is the key, page is the value
diff --git a/skyvern/forge/sdk/db/agent_db.py b/skyvern/forge/sdk/db/agent_db.py
index 39a2958eb..361fda8f9 100644
--- a/skyvern/forge/sdk/db/agent_db.py
+++ b/skyvern/forge/sdk/db/agent_db.py
@@ -20,7 +20,7 @@ from sqlalchemy import (
tuple_,
update,
)
-from sqlalchemy.dialects.postgresql import JSONB
+from sqlalchemy.dialects.postgresql import JSONB, insert
from sqlalchemy.exc import (
SQLAlchemyError,
)
@@ -56,6 +56,8 @@ from skyvern.forge.sdk.db.models import (
OutputParameterModel,
PersistentBrowserSessionModel,
ScriptBlockModel,
+ ScriptBranchHitModel,
+ ScriptFallbackEpisodeModel,
ScriptFileModel,
ScriptModel,
StepModel,
@@ -152,7 +154,15 @@ from skyvern.forge.sdk.workflow.models.workflow import (
WorkflowRunStatus,
)
from skyvern.schemas.runs import GeoTarget, ProxyLocation, ProxyLocationInput, RunEngine, RunType
-from skyvern.schemas.scripts import Script, ScriptBlock, ScriptFile, ScriptStatus, WorkflowScript
+from skyvern.schemas.scripts import (
+ Script,
+ ScriptBlock,
+ ScriptBranchHit,
+ ScriptFallbackEpisode,
+ ScriptFile,
+ ScriptStatus,
+ WorkflowScript,
+)
from skyvern.schemas.steps import AgentStepOutput
from skyvern.schemas.workflows import BlockStatus, BlockType, WorkflowStatus
from skyvern.webeye.actions.actions import Action
@@ -1798,6 +1808,8 @@ class AgentDB(BaseAlchemyDB):
run_with: str | None = None,
ai_fallback: bool = False,
cache_key: str | None = None,
+ adaptive_caching: bool = False,
+ generate_script_on_terminal: bool = False,
run_sequentially: bool = False,
sequential_key: str | None = None,
folder_id: str | None = None,
@@ -1821,6 +1833,8 @@ class AgentDB(BaseAlchemyDB):
run_with=run_with,
ai_fallback=ai_fallback,
cache_key=cache_key or DEFAULT_SCRIPT_RUN_ID,
+ adaptive_caching=adaptive_caching,
+ generate_script_on_terminal=generate_script_on_terminal,
run_sequentially=run_sequentially,
sequential_key=sequential_key,
folder_id=folder_id,
@@ -5960,6 +5974,24 @@ class AgentDB(BaseAlchemyDB):
).first()
return convert_to_script(script) if script else None
+ async def get_latest_script_version(self, script_id: str, organization_id: str) -> Script | None:
+ """Get the latest version of a script by script_id."""
+ try:
+ async with self.Session() as session:
+ script = (
+ await session.scalars(
+ select(ScriptModel)
+ .filter_by(script_id=script_id, organization_id=organization_id)
+ .filter(ScriptModel.deleted_at.is_(None))
+ .order_by(ScriptModel.version.desc())
+ .limit(1)
+ )
+ ).first()
+ return convert_to_script(script) if script else None
+ except SQLAlchemyError:
+ LOG.error("SQLAlchemyError", exc_info=True)
+ raise
+
async def create_script_file(
self,
script_revision_id: str,
@@ -6005,6 +6037,7 @@ class AgentDB(BaseAlchemyDB):
workflow_run_id: str | None = None,
workflow_run_block_id: str | None = None,
input_fields: list[str] | None = None,
+ requires_agent: bool = False,
) -> ScriptBlock:
"""Create a script block."""
async with self.Session() as session:
@@ -6018,6 +6051,7 @@ class AgentDB(BaseAlchemyDB):
workflow_run_id=workflow_run_id,
workflow_run_block_id=workflow_run_block_id,
input_fields=input_fields,
+ requires_agent=requires_agent,
)
session.add(script_block)
await session.commit()
@@ -6034,6 +6068,7 @@ class AgentDB(BaseAlchemyDB):
workflow_run_block_id: str | None = None,
clear_run_signature: bool = False,
input_fields: list[str] | None = None,
+ requires_agent: bool | None = None,
) -> ScriptBlock:
async with self.Session() as session:
script_block = (
@@ -6056,6 +6091,8 @@ class AgentDB(BaseAlchemyDB):
script_block.workflow_run_block_id = workflow_run_block_id
if input_fields is not None:
script_block.input_fields = input_fields
+ if requires_agent is not None:
+ script_block.requires_agent = requires_agent
await session.commit()
await session.refresh(script_block)
return convert_to_script_block(script_block)
@@ -6451,3 +6488,233 @@ class AgentDB(BaseAlchemyDB):
except Exception:
LOG.error("UnexpectedError", exc_info=True)
raise
+
+ # ── Script Fallback Episode CRUD ──────────────────────────────────
+
+ async def create_fallback_episode(
+ self,
+ organization_id: str,
+ workflow_permanent_id: str,
+ workflow_run_id: str,
+ block_label: str,
+ fallback_type: str,
+ script_revision_id: str | None = None,
+ error_message: str | None = None,
+ classify_result: str | None = None,
+ agent_actions: list | dict | None = None,
+ page_url: str | None = None,
+ page_text_snapshot: str | None = None,
+ ) -> ScriptFallbackEpisode:
+ try:
+ async with self.Session() as session:
+ episode = ScriptFallbackEpisodeModel(
+ organization_id=organization_id,
+ workflow_permanent_id=workflow_permanent_id,
+ workflow_run_id=workflow_run_id,
+ block_label=block_label,
+ fallback_type=fallback_type,
+ script_revision_id=script_revision_id,
+ error_message=sanitize_postgres_text(error_message) if error_message else None,
+ classify_result=sanitize_postgres_text(classify_result) if classify_result else None,
+ agent_actions=agent_actions,
+ page_url=sanitize_postgres_text(page_url) if page_url else None,
+ page_text_snapshot=sanitize_postgres_text(page_text_snapshot) if page_text_snapshot else None,
+ )
+ session.add(episode)
+ await session.commit()
+ await session.refresh(episode)
+ return ScriptFallbackEpisode.model_validate(episode)
+ except SQLAlchemyError:
+ LOG.error("SQLAlchemyError", exc_info=True)
+ raise
+
+ async def get_unreviewed_episodes(
+ self,
+ workflow_permanent_id: str,
+ organization_id: str,
+ limit: int = 100,
+ script_revision_id: str | None = None,
+ ) -> list[ScriptFallbackEpisode]:
+ try:
+ async with self.Session() as session:
+ query = (
+ select(ScriptFallbackEpisodeModel)
+ .filter_by(
+ organization_id=organization_id,
+ workflow_permanent_id=workflow_permanent_id,
+ reviewed=False,
+ )
+ .order_by(ScriptFallbackEpisodeModel.created_at.asc())
+ .limit(limit)
+ )
+ if script_revision_id:
+ query = query.filter_by(script_revision_id=script_revision_id)
+ episodes = (await session.scalars(query)).all()
+ return [ScriptFallbackEpisode.model_validate(e) for e in episodes]
+ except SQLAlchemyError:
+ LOG.error("SQLAlchemyError", exc_info=True)
+ raise
+
+ async def update_fallback_episode(
+ self,
+ episode_id: str,
+ organization_id: str,
+ agent_actions: list | dict | None = None,
+ fallback_succeeded: bool | None = None,
+ ) -> None:
+ try:
+ values: dict = {}
+ if agent_actions is not None:
+ values["agent_actions"] = agent_actions
+ if fallback_succeeded is not None:
+ values["fallback_succeeded"] = fallback_succeeded
+ if not values:
+ return
+ values["modified_at"] = datetime.utcnow()
+ async with self.Session() as session:
+ await session.execute(
+ update(ScriptFallbackEpisodeModel)
+ .where(ScriptFallbackEpisodeModel.episode_id == episode_id)
+ .where(ScriptFallbackEpisodeModel.organization_id == organization_id)
+ .values(**values)
+ )
+ await session.commit()
+ except SQLAlchemyError:
+ LOG.error("SQLAlchemyError", exc_info=True)
+ raise
+
+ async def delete_fallback_episode(
+ self,
+ episode_id: str,
+ organization_id: str,
+ ) -> None:
+ try:
+ async with self.Session() as session:
+ await session.execute(
+ delete(ScriptFallbackEpisodeModel)
+ .where(ScriptFallbackEpisodeModel.episode_id == episode_id)
+ .where(ScriptFallbackEpisodeModel.organization_id == organization_id)
+ )
+ await session.commit()
+ except SQLAlchemyError:
+ LOG.error("SQLAlchemyError", exc_info=True)
+ raise
+
+ async def mark_episode_reviewed(
+ self,
+ episode_id: str,
+ organization_id: str,
+ reviewer_output: str | None = None,
+ new_script_revision_id: str | None = None,
+ ) -> None:
+ try:
+ async with self.Session() as session:
+ await session.execute(
+ update(ScriptFallbackEpisodeModel)
+ .where(ScriptFallbackEpisodeModel.episode_id == episode_id)
+ .where(ScriptFallbackEpisodeModel.organization_id == organization_id)
+ .values(
+ reviewed=True,
+ reviewer_output=sanitize_postgres_text(reviewer_output) if reviewer_output else None,
+ new_script_revision_id=new_script_revision_id,
+ modified_at=datetime.utcnow(),
+ )
+ )
+ await session.commit()
+ except SQLAlchemyError:
+ LOG.error("SQLAlchemyError", exc_info=True)
+ raise
+
+ async def get_recent_reviewed_episodes(
+ self,
+ workflow_permanent_id: str,
+ organization_id: str,
+ limit: int = 20,
+ ) -> list[ScriptFallbackEpisode]:
+ """Return recently reviewed episodes for cross-run historical context.
+
+ These give the reviewer visibility into past failures and fixes so it can
+ avoid repeating the same mistakes.
+ """
+ try:
+ async with self.Session() as session:
+ query = (
+ select(ScriptFallbackEpisodeModel)
+ .filter_by(
+ organization_id=organization_id,
+ workflow_permanent_id=workflow_permanent_id,
+ reviewed=True,
+ )
+ .order_by(ScriptFallbackEpisodeModel.created_at.desc())
+ .limit(limit)
+ )
+ episodes = (await session.scalars(query)).all()
+ return [ScriptFallbackEpisode.model_validate(e) for e in episodes]
+ except SQLAlchemyError:
+ LOG.error("SQLAlchemyError", exc_info=True)
+ raise
+
+ async def record_branch_hit(
+ self,
+ organization_id: str,
+ workflow_permanent_id: str,
+ block_label: str,
+ branch_key: str,
+ ) -> None:
+ """Record a classify branch hit, upserting the hit count and last_hit_at."""
+ now = datetime.utcnow()
+ try:
+ async with self.Session() as session:
+ stmt = insert(ScriptBranchHitModel).values(
+ organization_id=organization_id,
+ workflow_permanent_id=workflow_permanent_id,
+ block_label=block_label,
+ branch_key=branch_key,
+ hit_count=1,
+ first_hit_at=now,
+ last_hit_at=now,
+ )
+ stmt = stmt.on_conflict_do_update(
+ index_elements=[
+ "organization_id",
+ "workflow_permanent_id",
+ "block_label",
+ "branch_key",
+ ],
+ set_={
+ "hit_count": ScriptBranchHitModel.hit_count + 1,
+ "last_hit_at": now,
+ },
+ )
+ await session.execute(stmt)
+ await session.commit()
+ except SQLAlchemyError:
+ LOG.error("SQLAlchemyError recording branch hit", exc_info=True)
+ raise
+
+ async def get_stale_branches(
+ self,
+ organization_id: str,
+ workflow_permanent_id: str,
+ stale_days: int = 90,
+ limit: int = 200,
+ ) -> list[ScriptBranchHit]:
+ """Get branches that haven't been accessed in stale_days days."""
+ cutoff = datetime.utcnow() - timedelta(days=stale_days)
+ try:
+ async with self.Session() as session:
+ query = (
+ select(ScriptBranchHitModel)
+ .filter_by(
+ organization_id=organization_id,
+ workflow_permanent_id=workflow_permanent_id,
+ )
+ .filter(ScriptBranchHitModel.last_hit_at < cutoff)
+ .order_by(ScriptBranchHitModel.last_hit_at.asc())
+ .limit(limit)
+ )
+ results = (await session.scalars(query)).all()
+ return [ScriptBranchHit.model_validate(r) for r in results]
+ except SQLAlchemyError:
+ LOG.error("SQLAlchemyError", exc_info=True)
+ raise
diff --git a/skyvern/forge/sdk/db/id.py b/skyvern/forge/sdk/db/id.py
index ad0582c4f..29c7efcd4 100644
--- a/skyvern/forge/sdk/db/id.py
+++ b/skyvern/forge/sdk/db/id.py
@@ -71,6 +71,7 @@ WORKFLOW_TEMPLATE_PREFIX = "wt"
ORGANIZATION_BILLING_PREFIX = "ob"
WORKFLOW_COPILOT_CHAT_PREFIX = "wcc"
WORKFLOW_COPILOT_CHAT_MESSAGE_PREFIX = "wccm"
+SCRIPT_FALLBACK_EPISODE_PREFIX = "sfe"
def generate_workflow_id() -> str:
@@ -278,6 +279,11 @@ def generate_workflow_copilot_chat_message_id() -> str:
return f"{WORKFLOW_COPILOT_CHAT_MESSAGE_PREFIX}_{int_id}"
+def generate_script_fallback_episode_id() -> str:
+ int_id = generate_id()
+ return f"{SCRIPT_FALLBACK_EPISODE_PREFIX}_{int_id}"
+
+
############# Helper functions below ##############
def generate_id() -> int:
"""
diff --git a/skyvern/forge/sdk/db/models.py b/skyvern/forge/sdk/db/models.py
index 807e4ac2f..c7bde78b2 100644
--- a/skyvern/forge/sdk/db/models.py
+++ b/skyvern/forge/sdk/db/models.py
@@ -41,6 +41,7 @@ from skyvern.forge.sdk.db.id import (
generate_output_parameter_id,
generate_persistent_browser_session_id,
generate_script_block_id,
+ generate_script_fallback_episode_id,
generate_script_file_id,
generate_script_id,
generate_script_revision_id,
@@ -282,6 +283,8 @@ class WorkflowModel(Base):
run_with = Column(String, nullable=True) # 'agent' or 'code'
ai_fallback = Column(Boolean, default=False, nullable=False)
cache_key = Column(String, nullable=True)
+ adaptive_caching = Column(Boolean, default=False, nullable=False, server_default=sqlalchemy.false())
+ generate_script_on_terminal = Column(Boolean, default=False, nullable=False, server_default=sqlalchemy.false())
run_sequentially = Column(Boolean, nullable=True)
sequential_key = Column(String, nullable=True)
folder_id = Column(String, ForeignKey("folders.folder_id", ondelete="SET NULL"), nullable=True)
@@ -1094,6 +1097,7 @@ class ScriptBlockModel(Base):
workflow_run_id = Column(String, nullable=True)
workflow_run_block_id = Column(String, nullable=True)
input_fields = Column(JSON, nullable=True)
+ requires_agent = Column(Boolean, nullable=False, server_default=sqlalchemy.false())
created_at = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)
modified_at = Column(DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow, nullable=False)
@@ -1137,3 +1141,56 @@ class WorkflowCopilotChatMessageModel(Base):
onupdate=datetime.datetime.utcnow,
nullable=False,
)
+
+
+class ScriptFallbackEpisodeModel(Base):
+ __tablename__ = "script_fallback_episodes"
+ __table_args__ = (
+ Index("sfe_org_wpid_index", "organization_id", "workflow_permanent_id"),
+ Index("sfe_org_created_at_index", "organization_id", "created_at"),
+ )
+
+ episode_id = Column(String, primary_key=True, default=generate_script_fallback_episode_id)
+ organization_id = Column(String, nullable=False)
+ workflow_permanent_id = Column(String, nullable=False)
+ workflow_run_id = Column(String, nullable=False)
+ script_revision_id = Column(String, nullable=True)
+ block_label = Column(String, nullable=False)
+ fallback_type = Column(String, nullable=False) # "element", "full_block", or "conditional_agent"
+ error_message = Column(UnicodeText, nullable=True)
+ classify_result = Column(String, nullable=True)
+ agent_actions = Column(JSON, nullable=True)
+ page_url = Column(String, nullable=True)
+ page_text_snapshot = Column(UnicodeText, nullable=True)
+ fallback_succeeded = Column(Boolean, nullable=True) # None for legacy/element episodes
+ reviewed = Column(Boolean, default=False, nullable=False, server_default=sqlalchemy.false())
+ reviewer_output = Column(UnicodeText, nullable=True)
+ new_script_revision_id = Column(String, nullable=True)
+
+ created_at = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)
+ modified_at = Column(
+ DateTime,
+ default=datetime.datetime.utcnow,
+ onupdate=datetime.datetime.utcnow,
+ nullable=False,
+ )
+
+
+class ScriptBranchHitModel(Base):
+ """Tracks which classify branches are accessed during cached script execution.
+
+ Used for TTL-based branch pruning — branches not accessed for a long time
+ can be removed by the script reviewer.
+ """
+
+ __tablename__ = "script_branch_hits"
+ __table_args__ = (Index("sbh_org_wpid_index", "organization_id", "workflow_permanent_id"),)
+
+ organization_id = Column(String, primary_key=True)
+ workflow_permanent_id = Column(String, primary_key=True)
+ block_label = Column(String, primary_key=True)
+ branch_key = Column(String, primary_key=True) # The classify result string (e.g., "success", "error")
+
+ hit_count = Column(Integer, default=1, nullable=False)
+ first_hit_at = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)
+ last_hit_at = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)
diff --git a/skyvern/forge/sdk/db/utils.py b/skyvern/forge/sdk/db/utils.py
index 2f0fdcd82..b3326a5eb 100644
--- a/skyvern/forge/sdk/db/utils.py
+++ b/skyvern/forge/sdk/db/utils.py
@@ -377,6 +377,8 @@ def convert_to_workflow(
run_with=workflow_model.run_with,
ai_fallback=workflow_model.ai_fallback,
cache_key=workflow_model.cache_key,
+ adaptive_caching=workflow_model.adaptive_caching,
+ generate_script_on_terminal=workflow_model.generate_script_on_terminal,
run_sequentially=workflow_model.run_sequentially,
sequential_key=workflow_model.sequential_key,
folder_id=workflow_model.folder_id,
@@ -688,6 +690,7 @@ def convert_to_script_block(script_block_model: ScriptBlockModel) -> ScriptBlock
workflow_run_id=script_block_model.workflow_run_id,
workflow_run_block_id=script_block_model.workflow_run_block_id,
input_fields=script_block_model.input_fields,
+ requires_agent=script_block_model.requires_agent,
created_at=script_block_model.created_at,
modified_at=script_block_model.modified_at,
deleted_at=script_block_model.deleted_at,
diff --git a/skyvern/forge/sdk/workflow/models/workflow.py b/skyvern/forge/sdk/workflow/models/workflow.py
index d2667698f..e3d3f7fc9 100644
--- a/skyvern/forge/sdk/workflow/models/workflow.py
+++ b/skyvern/forge/sdk/workflow/models/workflow.py
@@ -102,6 +102,8 @@ class Workflow(BaseModel):
run_with: str | None = None
ai_fallback: bool = False
cache_key: str | None = None
+ adaptive_caching: bool = False
+ generate_script_on_terminal: bool = False
run_sequentially: bool | None = None
sequential_key: str | None = None
folder_id: str | None = None
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.py
index 701da3376..49271b74e 100644
--- a/skyvern/forge/sdk/workflow/service.py
+++ b/skyvern/forge/sdk/workflow/service.py
@@ -2032,6 +2032,8 @@ class WorkflowService:
run_sequentially: bool = False,
sequential_key: str | None = None,
folder_id: str | None = None,
+ adaptive_caching: bool = False,
+ generate_script_on_terminal: bool = False,
) -> Workflow:
try:
return await app.DATABASE.create_workflow(
@@ -2057,6 +2059,8 @@ class WorkflowService:
run_sequentially=run_sequentially,
sequential_key=sequential_key,
folder_id=folder_id,
+ adaptive_caching=adaptive_caching,
+ generate_script_on_terminal=generate_script_on_terminal,
)
except IntegrityError as e:
if "uc_org_permanent_id_version" in str(e) and workflow_permanent_id:
@@ -3636,6 +3640,7 @@ class WorkflowService:
run_sequentially=request.run_sequentially,
sequential_key=request.sequential_key,
folder_id=existing_latest_workflow.folder_id,
+ adaptive_caching=request.adaptive_caching,
)
else:
# NOTE: it's only potential, as it may be immediately deleted!
@@ -3660,6 +3665,7 @@ class WorkflowService:
run_sequentially=request.run_sequentially,
sequential_key=request.sequential_key,
folder_id=request.folder_id,
+ adaptive_caching=request.adaptive_caching,
)
# Keeping track of the new workflow id to delete it if an error occurs during the creation process
new_workflow_id = potential_workflow.workflow_id
diff --git a/skyvern/schemas/scripts.py b/skyvern/schemas/scripts.py
index 5042ceffe..c2a3b1e19 100644
--- a/skyvern/schemas/scripts.py
+++ b/skyvern/schemas/scripts.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import base64
from datetime import datetime
from enum import StrEnum
+from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
@@ -138,6 +139,7 @@ class ScriptBlock(BaseModel):
workflow_run_id: str | None = None
workflow_run_block_id: str | None = None
input_fields: list[str] | None = None
+ requires_agent: bool = False # When True, block must run via agent even in code mode
created_at: datetime
modified_at: datetime
deleted_at: datetime | None = None
@@ -189,3 +191,38 @@ class ClearCacheResponse(BaseModel):
deleted_count: int = Field(..., description="Number of cached entries deleted")
message: str = Field(..., description="Status message")
+
+
+class ScriptFallbackEpisode(BaseModel):
+ model_config = ConfigDict(from_attributes=True)
+
+ episode_id: str
+ organization_id: str
+ workflow_permanent_id: str
+ workflow_run_id: str
+ script_revision_id: str | None = None
+ block_label: str
+ fallback_type: Literal["element", "full_block", "conditional_agent"]
+ error_message: str | None = None
+ classify_result: str | None = None
+ agent_actions: list | dict | None = None
+ page_url: str | None = None
+ page_text_snapshot: str | None = None
+ fallback_succeeded: bool | None = None
+ reviewed: bool = False
+ reviewer_output: str | None = None
+ new_script_revision_id: str | None = None
+ created_at: datetime
+ modified_at: datetime
+
+
+class ScriptBranchHit(BaseModel):
+ model_config = ConfigDict(from_attributes=True)
+
+ organization_id: str
+ workflow_permanent_id: str
+ block_label: str
+ branch_key: str
+ hit_count: int = 1
+ first_hit_at: datetime
+ last_hit_at: datetime
diff --git a/skyvern/schemas/workflows.py b/skyvern/schemas/workflows.py
index 80b43fea3..fd55d015c 100644
--- a/skyvern/schemas/workflows.py
+++ b/skyvern/schemas/workflows.py
@@ -1017,6 +1017,8 @@ class WorkflowCreateYAMLRequest(BaseModel):
run_with: str | None = None
ai_fallback: bool = False
cache_key: str | None = "default"
+ adaptive_caching: bool = False
+ generate_script_on_terminal: bool = False
run_sequentially: bool = False
sequential_key: str | None = None
folder_id: str | None = None