File size: 10,523 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
# Copyright (c) 2026 CrewHub. All rights reserved.
# Proprietary and confidential. See LICENSE for details.
"""Workflow API routes."""

from uuid import UUID

from typing import Optional

from fastapi import APIRouter, Depends, Header, Query, Request
from fastapi.security import HTTPBearer
from sqlalchemy.ext.asyncio import AsyncSession

from src.core.auth import get_current_user, resolve_db_user_id

_bearer_optional = HTTPBearer(auto_error=False)
from src.database import get_db
from src.schemas.workflow import (
    WorkflowCreate,
    WorkflowListResponse,
    WorkflowResponse,
    WorkflowRunListResponse,
    WorkflowRunRequest,
    WorkflowRunResponse,
    WorkflowUpdate,
)
from src.services.workflow_execution import WorkflowExecutionService
from src.services.workflow_service import WorkflowService

router = APIRouter(prefix="/workflows", tags=["workflows"])


# --- Public endpoints (before {id} to avoid path collision) ---

@router.get("/public", response_model=WorkflowListResponse)
async def list_public_workflows(
    pattern_type: Optional[str] = Query(None, pattern=r"^(manual|hierarchical|supervisor)$"),
    db: AsyncSession = Depends(get_db),
) -> WorkflowListResponse:
    service = WorkflowService(db)
    workflows, total = await service.list_public_workflows(pattern_type=pattern_type)
    return WorkflowListResponse(workflows=workflows, total=total)


# --- Authenticated endpoints ---

@router.get("/", response_model=WorkflowListResponse)
async def list_my_workflows(
    pattern_type: Optional[str] = Query(None, pattern=r"^(manual|hierarchical|supervisor)$"),
    db: AsyncSession = Depends(get_db),
    owner_id: UUID = Depends(resolve_db_user_id),
) -> WorkflowListResponse:
    service = WorkflowService(db)
    workflows, total = await service.list_my_workflows(owner_id, pattern_type=pattern_type)
    return WorkflowListResponse(workflows=workflows, total=total)


@router.post("/", response_model=WorkflowResponse, status_code=201)
async def create_workflow(
    data: WorkflowCreate,
    db: AsyncSession = Depends(get_db),
    owner_id: UUID = Depends(resolve_db_user_id),
) -> WorkflowResponse:
    service = WorkflowService(db)
    return await service.create_workflow(owner_id, data)


@router.get("/{workflow_id}", response_model=WorkflowResponse)
async def get_workflow(
    workflow_id: UUID,
    request: Request,
    db: AsyncSession = Depends(get_db),
    credentials=Depends(_bearer_optional),
    x_api_key: str | None = Header(None, alias="X-API-Key"),
) -> WorkflowResponse:
    service = WorkflowService(db)
    workflow = await service.get_workflow(workflow_id)
    # Allow public workflows; restrict private to owner only
    if not workflow.is_public:
        from src.core.exceptions import NotFoundError, UnauthorizedError
        try:
            current_user = await get_current_user(
                request=request,
                credentials=credentials,
                x_api_key=x_api_key,
            )
            owner_id = await resolve_db_user_id(current_user)
        except (UnauthorizedError, Exception):
            raise NotFoundError("Workflow not found")
        if workflow.owner_id != owner_id:
            raise NotFoundError("Workflow not found")
    return workflow


@router.put("/{workflow_id}", response_model=WorkflowResponse)
async def update_workflow(
    workflow_id: UUID,
    data: WorkflowUpdate,
    db: AsyncSession = Depends(get_db),
    owner_id: UUID = Depends(resolve_db_user_id),
) -> WorkflowResponse:
    service = WorkflowService(db)
    return await service.update_workflow(workflow_id, owner_id, data)


@router.delete("/{workflow_id}", status_code=204)
async def delete_workflow(
    workflow_id: UUID,
    db: AsyncSession = Depends(get_db),
    owner_id: UUID = Depends(resolve_db_user_id),
) -> None:
    service = WorkflowService(db)
    await service.delete_workflow(workflow_id, owner_id)


@router.post("/{workflow_id}/clone", response_model=WorkflowResponse, status_code=201)
async def clone_workflow(
    workflow_id: UUID,
    db: AsyncSession = Depends(get_db),
    owner_id: UUID = Depends(resolve_db_user_id),
) -> WorkflowResponse:
    service = WorkflowService(db)
    return await service.clone_workflow(workflow_id, owner_id)


@router.post("/{workflow_id}/run", response_model=WorkflowRunResponse)
async def run_workflow(
    workflow_id: UUID,
    data: WorkflowRunRequest,
    db: AsyncSession = Depends(get_db),
    owner_id: UUID = Depends(resolve_db_user_id),
) -> WorkflowRunResponse:
    engine = WorkflowExecutionService(db)
    return await engine.execute_workflow(workflow_id, owner_id, data.message)


@router.get("/{workflow_id}/runs", response_model=WorkflowRunListResponse)
async def list_workflow_runs(
    workflow_id: UUID,
    db: AsyncSession = Depends(get_db),
    owner_id: UUID = Depends(resolve_db_user_id),
) -> WorkflowRunListResponse:
    from sqlalchemy import func, select
    from sqlalchemy.orm import selectinload
    from src.models.workflow import WorkflowRun

    count_q = (
        select(func.count())
        .select_from(WorkflowRun)
        .where(WorkflowRun.workflow_id == workflow_id, WorkflowRun.user_id == owner_id)
    )
    total = (await db.execute(count_q)).scalar_one()

    q = (
        select(WorkflowRun)
        .where(WorkflowRun.workflow_id == workflow_id, WorkflowRun.user_id == owner_id)
        .options(selectinload(WorkflowRun.step_runs))
        .order_by(WorkflowRun.created_at.desc())
        .limit(50)
    )
    result = await db.execute(q)
    runs = list(result.scalars().unique().all())
    return WorkflowRunListResponse(runs=runs, total=total)


# --- Run-level endpoints ---

@router.get("/runs/{run_id}/output")
async def get_workflow_run_output(
    run_id: UUID,
    db: AsyncSession = Depends(get_db),
    user_id: UUID = Depends(resolve_db_user_id),
) -> dict:
    """Get workflow run output in a clean format for external consumption."""
    from sqlalchemy import select
    from sqlalchemy.orm import selectinload
    from src.models.workflow import WorkflowRun

    result = await db.execute(
        select(WorkflowRun)
        .where(WorkflowRun.id == run_id)
        .options(selectinload(WorkflowRun.step_runs), selectinload(WorkflowRun.workflow))
    )
    run = result.scalar_one_or_none()
    if not run:
        from src.core.exceptions import NotFoundError
        raise NotFoundError("Workflow run not found")
    if run.user_id != user_id and not (run.workflow and run.workflow.is_public):
        from src.core.exceptions import ForbiddenError
        raise ForbiddenError("Not authorized to view this workflow run")

    snapshot = run.workflow_snapshot or {}
    snapshot_steps = snapshot.get("steps", [])

    def step_label(step_id):
        if step_id:
            sid = str(step_id)
            for s in snapshot_steps:
                if s.get("id") == sid:
                    agent = s.get("agent_name", "")
                    skill = s.get("skill_name", "")
                    return f"{agent} · {skill}" if agent and skill else agent or "Unknown"
        return "Unknown"

    # Build per-step outputs sorted by group then position
    step_outputs = []
    sorted_srs = sorted(run.step_runs, key=lambda sr: (sr.step_group, getattr(sr, 'id', '')))
    for sr in sorted_srs:
        step_outputs.append({
            "step_run_id": str(sr.id),
            "step_group": sr.step_group,
            "label": step_label(sr.step_id),
            "status": sr.status,
            "output_text": sr.output_text,
            "error": sr.error,
            "credits_charged": float(sr.credits_charged) if sr.credits_charged else None,
        })

    # Build combined final output (only completed steps)
    completed_outputs = [
        sr.output_text for sr in sorted_srs
        if sr.status == "completed" and sr.output_text
    ]
    final_output = "\n\n---\n\n".join(completed_outputs) if completed_outputs else None

    return {
        "run_id": str(run.id),
        "workflow_id": str(run.workflow_id),
        "status": run.status,
        "input_message": run.input_message,
        "final_output": final_output,
        "step_outputs": step_outputs,
        "total_credits_charged": float(run.total_credits_charged) if run.total_credits_charged else None,
        "created_at": run.created_at.isoformat() if run.created_at else None,
        "completed_at": run.completed_at.isoformat() if run.completed_at else None,
    }


@router.get("/runs/{run_id}", response_model=WorkflowRunResponse)
async def get_workflow_run(
    run_id: UUID,
    db: AsyncSession = Depends(get_db),
    user_id: UUID = Depends(resolve_db_user_id),
) -> WorkflowRunResponse:
    from sqlalchemy import select
    from sqlalchemy.orm import selectinload
    from src.models.workflow import WorkflowRun

    result = await db.execute(
        select(WorkflowRun)
        .where(WorkflowRun.id == run_id)
        .options(selectinload(WorkflowRun.step_runs), selectinload(WorkflowRun.workflow))
    )
    run = result.scalar_one_or_none()
    if not run:
        from src.core.exceptions import NotFoundError
        raise NotFoundError("Workflow run not found")
    if run.user_id != user_id and not (run.workflow and run.workflow.is_public):
        from src.core.exceptions import ForbiddenError
        raise ForbiddenError("Not authorized to view this workflow run")
    return run


@router.post("/runs/{run_id}/cancel", response_model=WorkflowRunResponse)
async def cancel_workflow_run(
    run_id: UUID,
    db: AsyncSession = Depends(get_db),
    user_id: UUID = Depends(resolve_db_user_id),
) -> WorkflowRunResponse:
    engine = WorkflowExecutionService(db)
    return await engine.cancel_run(run_id, user_id)


@router.post(
    "/runs/{run_id}/steps/{step_run_id}/cancel",
    response_model=WorkflowRunResponse,
)
async def cancel_step_run(
    run_id: UUID,
    step_run_id: UUID,
    db: AsyncSession = Depends(get_db),
    user_id: UUID = Depends(resolve_db_user_id),
) -> WorkflowRunResponse:
    engine = WorkflowExecutionService(db)
    return await engine.cancel_step_run(run_id, step_run_id, user_id)


# --- Convert from crew ---

@router.post("/from-crew/{crew_id}", response_model=WorkflowResponse, status_code=201)
async def convert_crew_to_workflow(
    crew_id: UUID,
    db: AsyncSession = Depends(get_db),
    owner_id: UUID = Depends(resolve_db_user_id),
) -> WorkflowResponse:
    service = WorkflowService(db)
    return await service.convert_from_crew(crew_id, owner_id)