File size: 12,018 Bytes
04bb755 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 | # Copyright (c) 2026 CrewHub. All rights reserved.
# Proprietary and confidential. See LICENSE for details.
"""Workflow CRUD service — create, update, clone, convert from crew."""
import uuid as _uuid
from typing import Optional
from uuid import UUID
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from src.core.exceptions import BadRequestError, ForbiddenError, NotFoundError
from src.models.agent import Agent
from src.models.skill import AgentSkill
from src.models.workflow import Workflow, WorkflowStep
from src.schemas.workflow import WorkflowCreate, WorkflowUpdate
class WorkflowService:
def __init__(self, db: AsyncSession):
self.db = db
# ------------------------------------------------------------------
# Helpers
# ------------------------------------------------------------------
def _step_load_options(self):
return [
selectinload(Workflow.steps)
.selectinload(WorkflowStep.agent)
.selectinload(Agent.skills),
selectinload(Workflow.steps)
.selectinload(WorkflowStep.agent)
.selectinload(Agent.owner),
selectinload(Workflow.steps).selectinload(WorkflowStep.skill),
]
async def _get_workflow_or_404(self, workflow_id: UUID) -> Workflow:
result = await self.db.execute(
select(Workflow)
.where(Workflow.id == workflow_id)
.options(*self._step_load_options())
)
wf = result.scalar_one_or_none()
if not wf:
raise NotFoundError("Workflow not found")
return wf
def _check_ownership(self, wf: Workflow, owner_id: UUID) -> None:
if wf.owner_id != owner_id:
raise ForbiddenError("You do not own this workflow")
async def _detect_cycle(self, workflow_id: UUID, sub_workflow_id: UUID) -> bool:
"""Walk the sub-workflow graph via BFS to detect cycles. Returns True if cycle found."""
visited = {workflow_id}
queue = [sub_workflow_id]
while queue:
current_id = queue.pop(0)
if current_id in visited:
return True
visited.add(current_id)
result = await self.db.execute(
select(WorkflowStep.sub_workflow_id)
.where(WorkflowStep.workflow_id == current_id)
.where(WorkflowStep.sub_workflow_id.isnot(None))
)
for (child_id,) in result:
queue.append(child_id)
return False
async def _validate_step_refs(self, steps: list) -> None:
if not steps:
return
# Filter out None values (sub-workflow steps have no agent/skill)
agent_ids = {s.agent_id for s in steps if s.agent_id is not None}
skill_ids = {s.skill_id for s in steps if s.skill_id is not None}
if agent_ids:
result = await self.db.execute(
select(Agent.id).where(Agent.id.in_(agent_ids))
)
found = {row[0] for row in result.all()}
missing = agent_ids - found
if missing:
raise NotFoundError(f"Agent(s) not found: {missing}")
if skill_ids:
result = await self.db.execute(
select(AgentSkill.id).where(AgentSkill.id.in_(skill_ids))
)
found = {row[0] for row in result.all()}
missing = skill_ids - found
if missing:
raise NotFoundError(f"Skill(s) not found: {missing}")
def _build_steps(self, workflow_id: UUID, steps: list) -> list[WorkflowStep]:
return [
WorkflowStep(
id=_uuid.uuid4(),
workflow_id=workflow_id,
agent_id=s.agent_id,
skill_id=s.skill_id,
sub_workflow_id=getattr(s, "sub_workflow_id", None),
step_group=s.step_group,
position=s.position,
input_mode=s.input_mode,
input_template=s.input_template,
label=s.label,
instructions=s.instructions,
)
for s in steps
]
# ------------------------------------------------------------------
# CRUD
# ------------------------------------------------------------------
async def create_workflow(self, owner_id: UUID, data: WorkflowCreate) -> Workflow:
await self._validate_step_refs(data.steps)
wf = Workflow(
owner_id=owner_id,
name=data.name,
description=data.description,
icon=data.icon,
is_public=data.is_public,
pattern_type=getattr(data, "pattern_type", "manual") or "manual",
supervisor_config=getattr(data, "supervisor_config", None),
max_total_credits=data.max_total_credits,
timeout_seconds=data.timeout_seconds,
step_timeout_seconds=data.step_timeout_seconds,
)
self.db.add(wf)
await self.db.flush()
for step_data in (data.steps or []):
if step_data.sub_workflow_id:
if wf.pattern_type == "manual":
raise BadRequestError("Manual workflows cannot contain sub-workflows")
if await self._detect_cycle(wf.id, step_data.sub_workflow_id):
raise BadRequestError("Circular sub-workflow reference detected")
for step in self._build_steps(wf.id, data.steps):
self.db.add(step)
await self.db.commit()
return await self._get_workflow_or_404(wf.id)
async def get_workflow(self, workflow_id: UUID) -> Workflow:
return await self._get_workflow_or_404(workflow_id)
async def list_my_workflows(self, owner_id: UUID, *, pattern_type: Optional[str] = None) -> tuple[list[Workflow], int]:
count_q = select(func.count()).select_from(Workflow).where(Workflow.owner_id == owner_id)
if pattern_type:
count_q = count_q.where(Workflow.pattern_type == pattern_type)
total = (await self.db.execute(count_q)).scalar_one()
q = (
select(Workflow)
.where(Workflow.owner_id == owner_id)
.options(*self._step_load_options())
.order_by(Workflow.updated_at.desc())
)
if pattern_type:
q = q.where(Workflow.pattern_type == pattern_type)
result = await self.db.execute(q)
workflows = list(result.scalars().unique().all())
return workflows, total
async def list_public_workflows(self, *, pattern_type: Optional[str] = None) -> tuple[list[Workflow], int]:
count_q = select(func.count()).select_from(Workflow).where(
Workflow.is_public == True # noqa: E712
)
if pattern_type:
count_q = count_q.where(Workflow.pattern_type == pattern_type)
total = (await self.db.execute(count_q)).scalar_one()
q = (
select(Workflow)
.where(Workflow.is_public == True) # noqa: E712
.options(*self._step_load_options())
.order_by(Workflow.created_at.desc())
)
if pattern_type:
q = q.where(Workflow.pattern_type == pattern_type)
result = await self.db.execute(q)
workflows = list(result.scalars().unique().all())
return workflows, total
async def update_workflow(
self, workflow_id: UUID, owner_id: UUID, data: WorkflowUpdate
) -> Workflow:
wf = await self._get_workflow_or_404(workflow_id)
self._check_ownership(wf, owner_id)
if data.name is not None:
wf.name = data.name
if data.description is not None:
wf.description = data.description
if data.icon is not None:
wf.icon = data.icon
if data.is_public is not None:
wf.is_public = data.is_public
if data.max_total_credits is not None:
wf.max_total_credits = data.max_total_credits if data.max_total_credits > 0 else None
if data.timeout_seconds is not None:
wf.timeout_seconds = data.timeout_seconds
if data.step_timeout_seconds is not None:
wf.step_timeout_seconds = data.step_timeout_seconds
if data.steps is not None:
await self._validate_step_refs(data.steps)
for step_data in (data.steps or []):
if step_data.sub_workflow_id:
if wf.pattern_type == "manual":
raise BadRequestError("Manual workflows cannot contain sub-workflows")
if await self._detect_cycle(wf.id, step_data.sub_workflow_id):
raise BadRequestError("Circular sub-workflow reference detected")
for s in wf.steps:
await self.db.delete(s)
await self.db.flush()
for step in self._build_steps(workflow_id, data.steps):
self.db.add(step)
await self.db.commit()
self.db.expire_all()
return await self._get_workflow_or_404(workflow_id)
async def delete_workflow(self, workflow_id: UUID, owner_id: UUID) -> None:
wf = await self._get_workflow_or_404(workflow_id)
self._check_ownership(wf, owner_id)
await self.db.delete(wf)
await self.db.commit()
# ------------------------------------------------------------------
# Clone
# ------------------------------------------------------------------
async def clone_workflow(self, workflow_id: UUID, owner_id: UUID) -> Workflow:
source = await self._get_workflow_or_404(workflow_id)
if not source.is_public and source.owner_id != owner_id:
raise ForbiddenError("Cannot clone a private workflow you don't own")
new_wf = Workflow(
owner_id=owner_id,
name=f"Copy of {source.name}",
description=source.description,
icon=source.icon,
is_public=False,
max_total_credits=source.max_total_credits,
timeout_seconds=source.timeout_seconds,
step_timeout_seconds=source.step_timeout_seconds,
)
self.db.add(new_wf)
await self.db.flush()
for s in source.steps:
self.db.add(WorkflowStep(
workflow_id=new_wf.id,
agent_id=s.agent_id,
skill_id=s.skill_id,
step_group=s.step_group,
position=s.position,
input_mode=s.input_mode,
input_template=s.input_template,
label=s.label,
instructions=s.instructions,
))
await self.db.commit()
return await self._get_workflow_or_404(new_wf.id)
# ------------------------------------------------------------------
# Convert from Crew
# ------------------------------------------------------------------
async def convert_from_crew(self, crew_id: UUID, owner_id: UUID) -> Workflow:
from src.services.crew_service import CrewService
crew_svc = CrewService(self.db)
crew = await crew_svc.get_crew(crew_id)
if not crew.is_public and crew.owner_id != owner_id:
raise ForbiddenError("Cannot convert a private crew you don't own")
wf = Workflow(
owner_id=owner_id,
name=f"{crew.name} (Workflow)",
description=crew.description,
icon=crew.icon,
is_public=False,
)
self.db.add(wf)
await self.db.flush()
for m in crew.members:
self.db.add(WorkflowStep(
workflow_id=wf.id,
agent_id=m.agent_id,
skill_id=m.skill_id,
step_group=0,
position=m.position,
input_mode="chain",
))
await self.db.commit()
return await self._get_workflow_or_404(wf.id)
|