Spaces:
Running

WorkPilot-AI / core /api /routes /workflows.py
Aynkhn's picture
Deploy WorkPilot demo
fd5dd94 verified
Raw History Blame Contribute Delete
21.3 kB
"""Workflows API (Phase 11): compile, validate, versions, dry run, approve, activate, rollback,
templates, manual runs and self-healing proposals.
Roles: members read; managers compile, draft, dry-run, run, roll back and handle proposals;
only owners approve and activate a version.
"""
from __future__ import annotations
import uuid
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel, Field
from sqlalchemy import cast, func, select
from sqlalchemy.dialects.postgresql import JSONB
from core.agent.runs import Run
from core.api.routes.events import _ingest, dispatcher
from core.api.routes.runs import services
from core.auth.deps import Principal, current_principal, require_role
from core.events.intake import normalize_manual
from core.events.workers import Dispatcher
from core.services import Services
from core.tenancy.models import Role
from core.tools.registry import ToolRegistry
from core.workflows import compiler, versions
from core.workflows.catalog import pack_templates, tenant_registry, tool_catalog
from core.workflows.dryrun import dry_run
from core.workflows.dsl import WorkflowDefinition, describe
from core.workflows.executor import WORKFLOW_INTENT
from core.workflows.healing import apply_patch
from core.workflows.models import Workflow, WorkflowProposal, WorkflowVersion
router = APIRouter(tags=["workflows"])
class CompileIn(BaseModel):
text: str = Field(min_length=3, max_length=2000)
class ValidateIn(BaseModel):
definition: dict[str, Any]
class CreateIn(BaseModel):
text: str | None = Field(default=None, min_length=3, max_length=2000)
definition: dict[str, Any] | None = None
template: str | None = Field(default=None, max_length=200)
class VersionIn(BaseModel):
definition: dict[str, Any] | None = None
text: str | None = Field(default=None, min_length=3, max_length=2000)
note: str | None = Field(default=None, max_length=500)
class DryRunIn(BaseModel):
event: dict[str, Any] | None = Field(
default=None, description="sample triggering event payload for event/manual triggers"
)
class RunIn(BaseModel):
input: dict[str, Any] = Field(default_factory=dict)
# ------------------------------------------------------------------ helpers
def _iso(v: Any) -> Any:
return v.isoformat() if v is not None and hasattr(v, "isoformat") else v
def workflow_out(wf: Workflow, latest: WorkflowVersion | None = None) -> dict[str, Any]:
return {
"id": str(wf.id),
"key": wf.key,
"name": wf.name,
"description": wf.description,
"status": wf.status,
"active_version": wf.active_version,
"source": wf.source,
"template": wf.template,
"created_at": _iso(wf.created_at),
"updated_at": _iso(wf.updated_at),
"latest_version": (
{"version": latest.version, "status": latest.status} if latest is not None else None
),
}
def version_out(v: WorkflowVersion) -> dict[str, Any]:
try:
plan = describe(WorkflowDefinition.model_validate(v.definition))
except Exception:
plan = []
return {
"version": v.version,
"status": v.status,
"definition": v.definition,
"definition_hash": v.definition_hash,
"nl_source": v.nl_source,
"plan": plan,
"checks": v.checks,
"dry_run": v.dry_run,
"dry_run_at": _iso(v.dry_run_at),
"dry_run_current": v.dry_run_hash == v.definition_hash,
"created_by": v.created_by,
"created_at": _iso(v.created_at),
"approved_by": str(v.approved_by) if v.approved_by else None,
"approved_at": _iso(v.approved_at),
"activated_at": _iso(v.activated_at),
"deactivated_at": _iso(v.deactivated_at),
"parent_version": v.parent_version,
"note": v.note,
}
def proposal_out(p: WorkflowProposal) -> dict[str, Any]:
return {
"id": str(p.id),
"workflow_id": str(p.workflow_id),
"version": p.version,
"run_id": str(p.run_id),
"step_id": p.step_id,
"failure_class": p.failure_class,
"error": p.error,
"summary": p.summary,
"patch": p.patch,
"status": p.status,
"applied_version": p.applied_version,
"created_at": _iso(p.created_at),
"decided_at": _iso(p.decided_at),
}
def _lifecycle(exc: versions.LifecycleError) -> HTTPException:
detail: Any = str(exc)
if exc.report is not None:
detail = {"message": str(exc), **exc.report.as_dict()}
return HTTPException(exc.status, detail)
def _planner(svc: Services) -> Any:
if svc.runtime is None:
raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, "agent runtime not configured")
return svc.runtime.models.planner
async def _registry(svc: Services, p: Principal) -> ToolRegistry:
"""Pack tools plus the tenant's runtime tools (Phase 16 imports)."""
return await tenant_registry(svc.gateway, p.tenant_id)
async def _compile(svc: Services, p: Principal, text: str) -> compiler.CompileResult:
reg = await _registry(svc, p)
offered = await compiler.candidate_tools(svc.db, p.tenant_id, reg, text, search=svc.search)
try:
return await compiler.compile_nl(text, _planner(svc), reg, offered)
except LookupError as exc: # e.g. a scripted model without a response
raise HTTPException(status.HTTP_502_BAD_GATEWAY, f"planner model: {exc}") from exc
async def _get_version(
svc: Services, p: Principal, workflow_id: uuid.UUID, version: int
) -> WorkflowVersion:
async with svc.db.session(tenant_id=p.tenant_id) as s:
v = (
await s.execute(
select(WorkflowVersion).where(
WorkflowVersion.workflow_id == workflow_id, WorkflowVersion.version == version
)
)
).scalar_one_or_none()
if v is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "version not found")
return v
def _templates(svc: Services) -> list[dict[str, Any]]:
return pack_templates(svc.packs, svc.gateway.registry)
# ------------------------------------------------------------------ static routes
@router.get("/workflows")
async def list_workflows(
p: Principal = Depends(current_principal), svc: Services = Depends(services)
) -> dict[str, Any]:
async with svc.db.session(tenant_id=p.tenant_id) as s:
wfs = list(
(await s.execute(select(Workflow).order_by(Workflow.created_at.desc()))).scalars()
)
latest_q = (
select(WorkflowVersion)
.distinct(WorkflowVersion.workflow_id)
.order_by(WorkflowVersion.workflow_id, WorkflowVersion.version.desc())
)
latest = {v.workflow_id: v for v in (await s.execute(latest_q)).scalars()}
pending = (
await s.execute(
select(func.count())
.select_from(WorkflowProposal)
.where(WorkflowProposal.status == "pending")
)
).scalar_one()
return {
"items": [workflow_out(w, latest.get(w.id)) for w in wfs],
"pending_proposals": int(pending),
}
@router.get("/workflows/templates")
async def list_templates(
p: Principal = Depends(current_principal), svc: Services = Depends(services)
) -> list[dict[str, Any]]:
return _templates(svc)
@router.get("/workflows/tools")
async def list_tools(
p: Principal = Depends(current_principal), svc: Services = Depends(services)
) -> list[dict[str, Any]]:
return tool_catalog(await _registry(svc, p))
@router.post("/workflows/compile")
async def compile_workflow(
body: CompileIn,
p: Principal = Depends(require_role(Role.MANAGER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
"""Natural language -> DSL draft with static-check results. Nothing is saved."""
res = await _compile(svc, p, body.text)
out = res.as_dict()
out["plan"] = describe(res.definition) if res.definition else []
return out
@router.post("/workflows/validate")
async def validate_workflow(
body: ValidateIn,
p: Principal = Depends(require_role(Role.MANAGER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
defn, report = compiler.check(body.definition, await _registry(svc, p))
return {
**report.as_dict(),
"definition": defn.model_dump(mode="json") if defn else None,
"plan": describe(defn) if defn else [],
}
@router.get("/workflows/proposals")
async def list_proposals(
status_: str | None = Query(default="pending", alias="status"),
p: Principal = Depends(current_principal),
svc: Services = Depends(services),
) -> list[dict[str, Any]]:
q = select(WorkflowProposal).order_by(WorkflowProposal.created_at.desc()).limit(200)
if status_:
q = q.where(WorkflowProposal.status == status_)
async with svc.db.session(tenant_id=p.tenant_id) as s:
return [proposal_out(x) for x in (await s.execute(q)).scalars()]
@router.post("/workflows/proposals/{proposal_id}/apply")
async def apply_proposal(
proposal_id: uuid.UUID,
p: Principal = Depends(require_role(Role.MANAGER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
"""Turn a proposed fix into a new DRAFT version (it still needs dry run + approval)."""
async with svc.db.session(tenant_id=p.tenant_id) as s:
prop = await s.get(WorkflowProposal, proposal_id)
if prop is None or prop.status != "pending":
raise HTTPException(status.HTTP_404_NOT_FOUND, "no pending proposal")
if not prop.patch:
raise HTTPException(status.HTTP_409_CONFLICT, "this proposal has no definition change")
base = await _get_version(svc, p, prop.workflow_id, prop.version)
try:
fixed = apply_patch(base.definition, prop.patch)
v = await versions.add_version(
svc.db,
p.tenant_id,
prop.workflow_id,
fixed,
await _registry(svc, p),
actor=p.actor,
nl_source=base.nl_source,
note=f"fix: {prop.summary}",
)
except versions.LifecycleError as exc:
raise _lifecycle(exc) from exc
async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
prop2 = await s.get(WorkflowProposal, proposal_id)
if prop2 is not None:
prop2.status, prop2.applied_version = "applied", v.version
prop2.decided_by, prop2.decided_at = p.user_id, func.now()
return version_out(v)
@router.post("/workflows/proposals/{proposal_id}/dismiss")
async def dismiss_proposal(
proposal_id: uuid.UUID,
p: Principal = Depends(require_role(Role.MANAGER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
prop = await s.get(WorkflowProposal, proposal_id)
if prop is None or prop.status != "pending":
raise HTTPException(status.HTTP_404_NOT_FOUND, "no pending proposal")
prop.status, prop.decided_by, prop.decided_at = "dismissed", p.user_id, func.now()
return {"id": str(proposal_id), "status": "dismissed"}
@router.post("/workflows", status_code=status.HTTP_201_CREATED)
async def create_workflow(
body: CreateIn,
p: Principal = Depends(require_role(Role.MANAGER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
"""Create from natural language (``text``), a ``definition`` or a pack ``template``.
The first version is a draft; it needs a dry run, an owner's approval and activation."""
given = [x for x in (body.text, body.definition, body.template) if x]
if len(given) != 1:
raise HTTPException(422, "give exactly one of text, definition or template")
source, template, nl = "json", None, None
data: Any = body.definition
if body.text:
res = await _compile(svc, p, body.text)
if res.definition is None or not res.report.ok:
raise HTTPException(422, {"message": "compile failed", **res.as_dict()})
data, source, nl = res.definition, "nl", body.text
elif body.template:
tpl = next((t for t in _templates(svc) if t["id"] == body.template), None)
if tpl is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "unknown template")
data, source, template, nl = tpl["definition"], "template", tpl["id"], tpl["nl"]
try:
wf, v = await versions.create_workflow(
svc.db,
p.tenant_id,
data,
await _registry(svc, p),
actor=p.actor,
user_id=p.user_id,
nl_source=nl,
source=source,
template=template,
)
except versions.LifecycleError as exc:
raise _lifecycle(exc) from exc
return {**workflow_out(wf, v), "versions": [version_out(v)]}
# ------------------------------------------------------------------ per workflow
@router.get("/workflows/{workflow_id}")
async def get_workflow(
workflow_id: uuid.UUID,
p: Principal = Depends(current_principal),
svc: Services = Depends(services),
) -> dict[str, Any]:
async with svc.db.session(tenant_id=p.tenant_id) as s:
wf = await s.get(Workflow, workflow_id)
if wf is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "workflow not found")
vs = list(
(
await s.execute(
select(WorkflowVersion)
.where(WorkflowVersion.workflow_id == workflow_id)
.order_by(WorkflowVersion.version.desc())
)
).scalars()
)
props = list(
(
await s.execute(
select(WorkflowProposal)
.where(WorkflowProposal.workflow_id == workflow_id)
.order_by(WorkflowProposal.created_at.desc())
.limit(50)
)
).scalars()
)
return {
**workflow_out(wf, vs[0] if vs else None),
"versions": [version_out(v) for v in vs],
"proposals": [proposal_out(x) for x in props],
}
@router.get("/workflows/{workflow_id}/versions/{version}")
async def get_version(
workflow_id: uuid.UUID,
version: int,
p: Principal = Depends(current_principal),
svc: Services = Depends(services),
) -> dict[str, Any]:
return version_out(await _get_version(svc, p, workflow_id, version))
@router.post("/workflows/{workflow_id}/versions", status_code=status.HTTP_201_CREATED)
async def create_version(
workflow_id: uuid.UUID,
body: VersionIn,
p: Principal = Depends(require_role(Role.MANAGER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
"""A new immutable draft version (edited JSON/canvas, or re-compiled from text)."""
if (body.definition is None) == (body.text is None):
raise HTTPException(422, "give exactly one of definition or text")
data: Any = body.definition
nl = None
if body.text:
res = await _compile(svc, p, body.text)
if res.definition is None or not res.report.ok:
raise HTTPException(422, {"message": "compile failed", **res.as_dict()})
data, nl = res.definition, body.text
try:
v = await versions.add_version(
svc.db,
p.tenant_id,
workflow_id,
data,
await _registry(svc, p),
actor=p.actor,
nl_source=nl,
note=body.note,
)
except versions.LifecycleError as exc:
raise _lifecycle(exc) from exc
return version_out(v)
@router.post("/workflows/{workflow_id}/versions/{version}/dry-run")
async def dry_run_version(
workflow_id: uuid.UUID,
version: int,
body: DryRunIn | None = None,
p: Principal = Depends(require_role(Role.MANAGER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
v = await _get_version(svc, p, workflow_id, version)
defn = WorkflowDefinition.model_validate(v.definition)
event = None
if body is not None and body.event is not None:
event = {"type": "sample", "payload": body.event}
elif defn.trigger.type in ("event", "manual"):
event = {"type": "sample", "payload": {}}
report = await dry_run(svc.gateway, p.tenant_id, defn, actor=p.actor, event=event)
try:
v = await versions.record_dry_run(svc.db, p.tenant_id, workflow_id, version, report)
except versions.LifecycleError as exc:
raise _lifecycle(exc) from exc
return version_out(v)
@router.post("/workflows/{workflow_id}/versions/{version}/approve")
async def approve_version(
workflow_id: uuid.UUID,
version: int,
p: Principal = Depends(require_role(Role.OWNER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
try:
v = await versions.approve(svc.db, p.tenant_id, workflow_id, version, p.user_id)
except versions.LifecycleError as exc:
raise _lifecycle(exc) from exc
return version_out(v)
@router.post("/workflows/{workflow_id}/versions/{version}/activate")
async def activate_version(
workflow_id: uuid.UUID,
version: int,
p: Principal = Depends(require_role(Role.OWNER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
try:
v = await versions.activate(svc.db, p.tenant_id, workflow_id, version)
except versions.LifecycleError as exc:
raise _lifecycle(exc) from exc
return version_out(v)
@router.post("/workflows/{workflow_id}/rollback")
async def rollback_workflow(
workflow_id: uuid.UUID,
p: Principal = Depends(require_role(Role.MANAGER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
try:
v = await versions.rollback(svc.db, p.tenant_id, workflow_id)
except versions.LifecycleError as exc:
raise _lifecycle(exc) from exc
return {"active_version": v.version if v else None, "status": "active" if v else "paused"}
@router.post("/workflows/{workflow_id}/deactivate")
async def deactivate_workflow(
workflow_id: uuid.UUID,
p: Principal = Depends(require_role(Role.MANAGER)),
svc: Services = Depends(services),
) -> dict[str, Any]:
try:
await versions.deactivate(svc.db, p.tenant_id, workflow_id)
except versions.LifecycleError as exc:
raise _lifecycle(exc) from exc
return {"active_version": None, "status": "paused"}
@router.post("/workflows/{workflow_id}/run", status_code=status.HTTP_202_ACCEPTED)
async def run_workflow(
workflow_id: uuid.UUID,
body: RunIn | None = None,
p: Principal = Depends(require_role(Role.MANAGER)),
svc: Services = Depends(services),
d: Dispatcher = Depends(dispatcher),
) -> dict[str, Any]:
"""Run the ACTIVE version now (a ``workflow.run`` event, dispatched like any other)."""
async with svc.db.session(tenant_id=p.tenant_id) as s:
wf = await s.get(Workflow, workflow_id)
if wf is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "workflow not found")
if wf.status != "active" or wf.active_version is None:
raise HTTPException(status.HTTP_409_CONFLICT, "workflow has no active version")
payload = {
"workflow_id": str(wf.id),
"version": wf.active_version,
"trigger": "manual",
"input": (body.input if body else {}),
"requested_by": p.actor,
}
ne = normalize_manual(WORKFLOW_INTENT, payload=payload)
recorded = await _ingest(svc, d, p.tenant_id, [ne])
return {"event_id": str(recorded[0].event_id), "version": wf.active_version}
@router.get("/workflows/{workflow_id}/runs")
async def workflow_runs(
workflow_id: uuid.UUID,
limit: int = Query(default=50, ge=1, le=200),
p: Principal = Depends(current_principal),
svc: Services = Depends(services),
) -> list[dict[str, Any]]:
match = cast({"payload": {"workflow_id": str(workflow_id)}}, JSONB)
async with svc.db.session(tenant_id=p.tenant_id) as s:
rows = (
await s.execute(
select(Run)
.where(Run.event.op("@>")(match))
.order_by(Run.started_at.desc())
.limit(limit)
)
).scalars()
return [
{
"run_id": str(r.id),
"status": r.status,
"version": (r.event.get("payload") or {}).get("version"),
"trigger": (r.event.get("payload") or {}).get("trigger"),
"output": r.output,
"error": r.error,
"started_at": _iso(r.started_at),
"ended_at": _iso(r.ended_at),
}
for r in rows
]