Spaces:
Running

Aynkhn's picture
Deploy WorkPilot demo
fd5dd94 verified
Raw History Blame Contribute Delete
28.8 kB
"""Read models for the web dashboard (Phase 10): who am I, runs, a live run stream (SSE),
an inbox with decided items, analytics and tenant settings.
Everything here is tenant-scoped through ``db.session(tenant_id=...)`` and Postgres RLS.
Writes are limited to tenant settings (owner only) and switching the active tenant.
"""
from __future__ import annotations
import asyncio
import json
import re
import uuid
from collections.abc import AsyncIterator
from datetime import UTC, datetime, timedelta
from typing import Any, Literal
from fastapi import APIRouter, Depends, FastAPI, HTTPException, Query, Request, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field, field_validator
from sqlalchemy import func, select, update
from core.agent.runs import Run
from core.api.routes.approvals import to_out
from core.api.routes.runs import services
from core.api.schemas import TokenPair
from core.approvals.models import Approval
from core.auth.deps import Principal, current_principal, require_role
from core.auth.jwt import issue_token
from core.config import get_settings
from core.gateway import audit
from core.gateway.models import AuditLog, KillSwitch
from core.services import Services
from core.tenancy.models import Membership, Role, Tenant, User
from core.tenancy.service import memberships_for
from core.tools.registry import ToolNotFound
from core.tools.spec import ToolContext
router = APIRouter(tags=["ui"])
TERMINAL = frozenset({"completed", "rejected", "failed", "unsupported"})
SETTINGS_KEYS = ("policy_attrs", "approval_rules")
# Phase 15 (ADR-0009 G1/G4): core safety profile, enabled packs, channel-event bindings,
# prompt A/B experiments, and per-pack blocks validated by ``Pack.settings_schema()``.
PHASE15_KEYS = ("safety_profile", "packs", "event_bindings", "prompt_experiments")
def install(app: FastAPI) -> None:
"""Register the dashboard routes and CORS for the configured web origins."""
origins = get_settings().cors_origins
if origins:
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["Authorization", "Content-Type", "X-Stepup-Token", "Last-Event-ID"],
)
app.include_router(router)
# ---------------------------------------------------------------------------- me / tenants
class SwitchTenantIn(BaseModel):
tenant_id: uuid.UUID
async def _tenant(svc: Services, tenant_id: uuid.UUID) -> Tenant | None:
async with svc.db.session(tenant_id=tenant_id) as s:
return await s.get(Tenant, tenant_id)
@router.get("/me")
async def me(p: Principal = Depends(current_principal), svc: Services = Depends(services)) -> dict:
async with svc.db.session() as s:
user = await s.get(User, p.user_id)
if user is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "user not found")
tenants = []
for m in await memberships_for(svc.db, p.user_id):
t = await _tenant(svc, m.tenant_id)
tenants.append(
{"id": m.tenant_id, "name": t.name if t else str(m.tenant_id), "role": m.role.value}
)
current = await _tenant(svc, p.tenant_id)
return {
"user": {"id": user.id, "email": user.email, "totp_enrolled": bool(user.totp_secret)},
"tenant": {
"id": p.tenant_id,
"name": current.name if current else "",
"plan": current.plan if current else "free",
"locale": current.locale if current else "en",
"timezone": current.timezone if current else "Asia/Karachi",
},
"role": p.role.value,
"tenants": tenants,
}
@router.post("/me/tenant", response_model=TokenPair)
async def switch_tenant(
body: SwitchTenantIn,
p: Principal = Depends(current_principal),
svc: Services = Depends(services),
) -> TokenPair:
"""Tenant switcher: new tokens bound to another workspace the user belongs to."""
if body.tenant_id not in [m.tenant_id for m in await memberships_for(svc.db, p.user_id)]:
raise HTTPException(status.HTTP_403_FORBIDDEN, "not a member of this tenant")
return TokenPair(
access_token=issue_token(p.user_id, body.tenant_id, "access"),
refresh_token=issue_token(p.user_id, body.tenant_id, "refresh"),
tenant_id=body.tenant_id,
)
# ---------------------------------------------------------------------------- runs
def _run_row(r: Run, pending: int = 0) -> dict[str, Any]:
event = r.event or {}
return {
"run_id": r.id,
"thread_id": r.thread_id,
"status": r.status,
"intent": r.intent,
"event_type": event.get("type"),
"source": event.get("source"),
"text": (event.get("text") or "")[:300] or None,
"output": r.output,
"error": r.error,
"cost_usd": r.cost_usd,
"started_at": r.started_at,
"ended_at": r.ended_at,
"pending_approvals": pending,
}
@router.get("/runs")
async def list_runs(
status_: str | None = Query(default=None, alias="status", max_length=30),
limit: int = Query(default=50, ge=1, le=200),
offset: int = Query(default=0, ge=0),
p: Principal = Depends(current_principal),
svc: Services = Depends(services),
) -> dict:
async with svc.db.session(tenant_id=p.tenant_id) as s:
q = select(Run)
count_q = select(func.count()).select_from(Run)
if status_:
q = q.where(Run.status == status_)
count_q = count_q.where(Run.status == status_)
total = (await s.execute(count_q)).scalar_one()
runs = list(
(
await s.execute(q.order_by(Run.started_at.desc()).limit(limit).offset(offset))
).scalars()
)
pending: dict[uuid.UUID, int] = {}
if runs:
rows = await s.execute(
select(Approval.run_id, func.count())
.where(Approval.run_id.in_([r.id for r in runs]), Approval.status == "pending")
.group_by(Approval.run_id)
)
pending = {rid: n for rid, n in rows.all() if rid is not None}
return {"items": [_run_row(r, pending.get(r.id, 0)) for r in runs], "total": total}
def _audit_row(a: AuditLog) -> dict[str, Any]:
return {
"seq": a.seq,
"at": a.at,
"actor": a.actor,
"tool": a.tool,
"args": a.args_redacted,
"taint": a.taint,
"decision": a.decision,
"reason": a.reason,
"approval_id": a.approval_id,
"result_status": a.result_status,
"latency_ms": a.latency_ms,
"cost_usd": a.cost_usd,
}
def _approval_brief(a: Approval) -> dict[str, Any]:
return {
"id": a.id,
"tool": a.tool,
"status": a.status,
"reason": a.reason,
"created_at": a.created_at,
"decided_at": a.decided_at,
"decision_note": a.decision_note,
"replaced_by": a.replaced_by,
}
async def _graph_state(svc: Services, thread_id: str) -> dict[str, Any]:
"""Plan, cursor and progress log from the LangGraph checkpoint (best effort)."""
if svc.runtime is None:
return {}
try:
snap = await svc.runtime.graph.aget_state({"configurable": {"thread_id": thread_id}})
except Exception: # missing checkpoint tables or thread: the timeline still works
return {}
values = snap.values if isinstance(snap.values, dict) else {}
return {
"plan": values.get("plan") or [],
"cursor": values.get("cursor", 0),
"log": values.get("log") or [],
"actions": values.get("actions") or [],
}
async def _snapshot(
svc: Services, p: Principal, run_id: uuid.UUID, after_seq: int = 0
) -> tuple[Run, list[AuditLog], list[Approval]]:
async with svc.db.session(tenant_id=p.tenant_id) as s:
run = (await s.execute(select(Run).where(Run.id == run_id))).scalar_one_or_none()
if run is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "run not found")
rows = list(
(
await s.execute(
select(AuditLog)
.where(AuditLog.run_id == run_id, AuditLog.seq > after_seq)
.order_by(AuditLog.seq)
)
).scalars()
)
approvals = list(
(
await s.execute(
select(Approval).where(Approval.run_id == run_id).order_by(Approval.created_at)
)
).scalars()
)
return run, rows, approvals
@router.get("/runs/{run_id}/timeline")
async def run_timeline(
run_id: uuid.UUID,
p: Principal = Depends(current_principal),
svc: Services = Depends(services),
) -> dict:
"""Everything the run detail page needs in one read: run, plan/log, tool calls, approvals."""
run, rows, approvals = await _snapshot(svc, p, run_id)
return {
"run": _run_row(run, sum(1 for a in approvals if a.status == "pending")),
"event": run.event,
"state": await _graph_state(svc, run.thread_id),
"actions": [_audit_row(r) for r in rows],
"approvals": [_approval_brief(a) for a in approvals],
"trace_url": _trace_url(run),
}
def _trace_url(run: Run) -> str | None:
host = get_settings().langfuse_host
return f"{host.rstrip('/')}/trace/{run.id}" if host else None
def _sse(event: str, data: Any, event_id: int | None = None) -> str:
head = f"id: {event_id}\n" if event_id is not None else ""
return f"{head}event: {event}\ndata: {json.dumps(data, default=str)}\n\n"
@router.get("/runs/{run_id}/stream")
async def run_stream(
run_id: uuid.UUID,
request: Request,
follow: bool = Query(default=False),
after: int = Query(default=0, ge=0),
poll_ms: int = Query(default=500, ge=100, le=5000),
max_seconds: int = Query(default=600, ge=1, le=3600),
p: Principal = Depends(current_principal),
svc: Services = Depends(services),
) -> StreamingResponse:
"""Server-sent events for one run: ``status`` (run row + approvals + plan/log) whenever it
changes, ``action`` per audit row (one gateway decision each), then ``end``.
The stream ends when the run is terminal, or when it is waiting for approval unless
``follow=true`` (the dashboard follows through the approval and sees it complete).
"""
await _snapshot(svc, p, run_id) # 404 before the stream starts
last_id = request.headers.get("last-event-id")
start_seq = int(last_id) if last_id and last_id.isdigit() else after
async def events() -> AsyncIterator[str]:
seq, last_status, deadline = start_seq, None, asyncio.get_running_loop().time()
deadline += max_seconds
yield "retry: 2000\n\n"
while True:
run, rows, approvals = await _snapshot(svc, p, run_id, after_seq=seq)
for r in rows:
seq = r.seq
yield _sse("action", _audit_row(r), r.seq)
key = (run.status, run.output, tuple((a.id, a.status) for a in approvals))
if key != last_status:
last_status = key
yield _sse(
"status",
{
"run": _run_row(run, sum(1 for a in approvals if a.status == "pending")),
"state": await _graph_state(svc, run.thread_id),
"approvals": [_approval_brief(a) for a in approvals],
},
)
done = run.status in TERMINAL or (run.status == "waiting_approval" and not follow)
loop_time = asyncio.get_running_loop().time()
if done or loop_time > deadline or await request.is_disconnected():
yield _sse("end", {"status": run.status})
return
await asyncio.sleep(poll_ms / 1000)
return StreamingResponse(
events(),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)
# ---------------------------------------------------------------------------- inbox
async def _facts(svc: Services, p: Principal, a: Approval) -> dict[str, Any]:
"""The trusted facts policy saw for this call (e.g. order total), read live."""
try:
tool = svc.registry.get(a.tool)
except ToolNotFound:
return {}
if tool.policy_context is None:
return {}
try:
async with svc.db.session(tenant_id=p.tenant_id) as s:
ctx = ToolContext(
tenant_id=p.tenant_id, actor=a.actor, run_id=a.run_id, session=s, dry_run=True
)
return await tool.policy_context(dict(a.args), ctx)
except Exception: # facts are a display aid; never fail the inbox over them
return {}
def _args_schema(svc: Services, tool: str) -> dict[str, Any]:
try:
return svc.registry.get(tool).spec.json_schema()
except ToolNotFound:
return {}
@router.get("/inbox")
async def inbox(
status_: Literal["pending", "decided", "all"] = Query(default="pending", alias="status"),
limit: int = Query(default=100, ge=1, le=500),
p: Principal = Depends(current_principal),
svc: Services = Depends(services),
) -> list[dict]:
"""Approvals with what the inbox card needs beyond ``/approvals``: the HITL kind, the
args JSON schema (edit form), live policy facts and decision details."""
async with svc.db.session(tenant_id=p.tenant_id) as s:
q = select(Approval)
if status_ == "pending":
q = q.where(Approval.status == "pending").order_by(Approval.created_at)
else:
if status_ == "decided":
q = q.where(Approval.status != "pending")
q = q.order_by(Approval.created_at.desc())
items = list((await s.execute(q.limit(limit))).scalars())
out = []
for a in items:
row = to_out(a).model_dump(mode="json")
tool = svc.registry.get(a.tool).spec if svc.registry.has(a.tool) else None
row.update(
kind=a.kind,
risk_tier=int(tool.risk_tier) if tool else None,
args_schema=_args_schema(svc, a.tool),
facts=await _facts(svc, p, a) if a.status == "pending" else {},
decided_at=a.decided_at.isoformat() if a.decided_at else None,
decision_note=a.decision_note,
replaced_by=str(a.replaced_by) if a.replaced_by else None,
# Phase 7 adds an undo window for queued T2 sends; surface it when present.
send_after=_iso(getattr(a, "send_after", None)),
# Phase 7: the cancel endpoint for that send (gateway tool ecommerce.cancel_message
# via the pack route); without it the UI falls back to POST /approvals/{id}/undo.
undo_url=getattr(a, "undo_url", None) if getattr(a, "send_after", None) else None,
)
out.append(row)
return out
def _iso(v: Any) -> str | None:
return v.isoformat() if isinstance(v, datetime) else None
# ---------------------------------------------------------------------------- analytics
@router.get("/analytics/summary")
async def analytics_summary(
days: int = Query(default=30, ge=1, le=365),
p: Principal = Depends(current_principal),
svc: Services = Depends(services),
) -> dict:
since = datetime.now(UTC) - timedelta(days=days)
async with svc.db.session(tenant_id=p.tenant_id) as s:
runs_by_status = {
st: n
for st, n in (
await s.execute(
select(Run.status, func.count())
.where(Run.started_at >= since)
.group_by(Run.status)
)
).all()
}
approvals_by_status = {
st: n
for st, n in (
await s.execute(
select(Approval.status, func.count())
.where(Approval.created_at >= since)
.group_by(Approval.status)
)
).all()
}
with_approval = select(Approval.run_id).where(Approval.run_id.is_not(None))
completed = runs_by_status.get("completed", 0)
completed_auto = (
await s.execute(
select(func.count())
.select_from(Run)
.where(
Run.status == "completed",
Run.started_at >= since,
Run.id.not_in(with_approval),
)
)
).scalar_one()
latency = (
await s.execute(
select(
func.percentile_cont(0.5).within_group(
func.extract("epoch", Approval.decided_at - Approval.created_at)
)
).where(Approval.decided_at.is_not(None), Approval.created_at >= since)
)
).scalar_one_or_none()
denials = (
await s.execute(
select(AuditLog.reason, func.count().label("n"))
.where(
AuditLog.decision.in_(["denied", "rejected"]),
AuditLog.at >= since,
AuditLog.reason.is_not(None),
)
.group_by(AuditLog.reason)
.order_by(func.count().desc())
.limit(5)
)
).all()
tool_calls = {
d: n
for d, n in (
await s.execute(
select(AuditLog.decision, func.count())
.where(AuditLog.at >= since)
.group_by(AuditLog.decision)
)
).all()
}
cost = (
await s.execute(
select(func.coalesce(func.sum(Run.cost_usd), 0.0)).where(Run.started_at >= since)
)
).scalar_one()
day = func.date_trunc("day", Run.started_at)
per_day = (
await s.execute(
select(day, Run.status, func.count())
.where(Run.started_at >= since)
.group_by(day, Run.status)
.order_by(day)
)
).all()
daily: dict[str, dict[str, int]] = {}
for d, st, n in per_day:
daily.setdefault(d.date().isoformat(), {})[st] = n
approved = approvals_by_status.get("approved", 0) + approvals_by_status.get("edited", 0)
rejected = approvals_by_status.get("rejected", 0)
total_runs = sum(runs_by_status.values())
return {
"days": days,
"runs": {"total": total_runs, "by_status": runs_by_status},
"approvals": {
"approved": approved,
"rejected": rejected,
"pending": approvals_by_status.get("pending", 0),
"by_status": approvals_by_status,
"approval_rate": approved / (approved + rejected) if approved + rejected else None,
},
"auto_resolution_rate": completed_auto / completed if completed else None,
"median_approval_latency_s": float(latency) if latency is not None else None,
"top_denial_reasons": [{"reason": r, "count": n} for r, n in denials],
"tool_calls": {"total": sum(tool_calls.values()), "by_decision": tool_calls},
"cost_usd": float(cost or 0.0),
"cost_per_run_usd": float(cost or 0.0) / total_runs if total_runs else None,
"daily": [{"date": d, **v} for d, v in sorted(daily.items())],
}
# ---------------------------------------------------------------------------- settings
_KEY = re.compile(r"^[a-z][a-z0-9_]{0,63}$")
class ApprovalRuleIn(BaseModel):
tool: str = Field(min_length=1, max_length=200)
arg: str | None = Field(default=None, max_length=64)
min: int | None = Field(default=None, ge=0)
role: Role = Role.MANAGER
stepup: bool = False
class PromptExperimentIn(BaseModel):
labels: list[str] = Field(min_length=2, max_length=2)
split: float = Field(default=0.5, ge=0.0, le=1.0)
class SettingsIn(BaseModel):
# Cedar has no floating point: thresholds are whole numbers (e.g. rupees).
policy_attrs: dict[str, int | bool | str] | None = None
approval_rules: list[ApprovalRuleIn] | None = Field(default=None, max_length=50)
# Phase 15
safety_profile: Literal["standard", "healthcare", "finance", "strict"] | None = None
packs: list[str] | None = Field(default=None, max_length=50)
event_bindings: dict[str, str] | None = None
prompt_experiments: dict[str, PromptExperimentIn] | None = None
pack_settings: dict[str, dict[str, Any]] | None = None
@field_validator("policy_attrs")
@classmethod
def _keys(cls, v: dict[str, Any] | None) -> dict[str, Any] | None:
if v is None:
return v
if len(v) > 50:
raise ValueError("at most 50 policy attributes")
for k, val in v.items():
if not _KEY.match(k):
raise ValueError(f"invalid attribute name {k!r}")
if isinstance(val, str) and len(val) > 200:
raise ValueError(f"value of {k!r} is too long")
return v
async def _settings_view(svc: Services, p: Principal) -> dict[str, Any]:
async with svc.db.session(tenant_id=p.tenant_id) as s:
tenant = await s.get(Tenant, p.tenant_id)
switches = list(
(await s.execute(select(KillSwitch).order_by(KillSwitch.created_at))).scalars()
)
team = (
await s.execute(
select(Membership.user_id, Membership.role, User.email)
.join(User, User.id == Membership.user_id)
.where(Membership.tenant_id == p.tenant_id)
.order_by(User.email)
)
).all()
settings = dict(tenant.settings or {}) if tenant else {}
from core.agent.tenant_config import safety_profile
return {
"policy_attrs": settings.get("policy_attrs", {}),
"approval_rules": settings.get("approval_rules", []),
# Phase 15
"safety_profile": safety_profile(settings),
"packs": settings.get("packs"),
"event_bindings": settings.get("event_bindings", {}),
"prompt_experiments": settings.get("prompt_experiments", {}),
"pack_settings_schemas": {
pk.name: _schema_json(pk) for pk in svc.packs if _schema_json(pk) is not None
},
"kill_switches": [
{
"scope": k.scope,
"target": k.target,
"enabled": k.enabled,
"reason": k.reason,
"global": k.tenant_id is None,
}
for k in switches
],
"team": [{"user_id": u, "role": r.value, "email": e} for u, r, e in team],
"editable": p.role is Role.OWNER,
}
@router.get("/settings")
async def get_tenant_settings(
p: Principal = Depends(current_principal), svc: Services = Depends(services)
) -> dict:
return await _settings_view(svc, p)
@router.put("/settings")
async def put_tenant_settings(
body: SettingsIn,
p: Principal = Depends(require_role(Role.OWNER)),
svc: Services = Depends(services),
) -> dict:
"""Owner-only. Changes ``policy_attrs``, ``approval_rules`` and (Phase 15)
``safety_profile``, ``packs``, ``event_bindings``, ``prompt_experiments`` and per-pack
blocks (``pack_settings``, validated by each pack's ``settings_schema()``); other keys
stay."""
for r in body.approval_rules or []:
if r.tool != "*" and not svc.registry.has(r.tool):
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, f"unknown tool {r.tool}")
if (r.arg is None) != (r.min is None):
raise HTTPException(
status.HTTP_422_UNPROCESSABLE_ENTITY, "a rule needs both arg and min, or neither"
)
_validate_phase15(svc, body)
changes = body.model_dump(mode="json", exclude_none=True)
for name, block in (changes.pop("pack_settings", None) or {}).items():
changes[name] = _pack_settings(svc, name, block)
if body.approval_rules is not None:
changes["approval_rules"] = [
{k: v for k, v in r.model_dump(mode="json").items() if v is not None}
for r in body.approval_rules
]
async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
tenant = await s.get(Tenant, p.tenant_id, with_for_update=True)
if tenant is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "tenant not found")
merged = {**(tenant.settings or {}), **changes}
await s.execute(update(Tenant).where(Tenant.id == p.tenant_id).values(settings=merged))
await audit.append(
s,
audit.AuditEntry(
tenant_id=p.tenant_id,
actor=p.actor,
tool="core.update_settings",
args=dict(changes),
taint={},
decision="executed",
policy_version="settings",
result_status="ok",
),
)
return await _settings_view(svc, p)
# ------------------------------------------------- settings validation (Phase 15, G1/G4)
def _schema_json(pack: Any) -> dict[str, Any] | None:
"""The pack's optional ``settings_schema()``: a pydantic model class or a JSON schema."""
hook = getattr(pack, "settings_schema", None)
if hook is None:
return None
schema = hook()
if schema is None:
return None
if isinstance(schema, type) and issubclass(schema, BaseModel):
return schema.model_json_schema()
return dict(schema)
def _pack_settings(svc: Services, name: str, block: dict[str, Any]) -> dict[str, Any]:
from core.tools.jsonschema_model import SchemaError, model_from_schema
pack = next((pk for pk in svc.packs if pk.name == name), None)
if pack is None:
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, f"unknown pack {name}")
hook = getattr(pack, "settings_schema", None)
schema = hook() if hook is not None else None
if schema is None:
raise HTTPException(
status.HTTP_422_UNPROCESSABLE_ENTITY, f"pack {name} has no editable settings"
)
try:
if isinstance(schema, type) and issubclass(schema, BaseModel):
model: type[BaseModel] = schema
else:
model = model_from_schema(dict(schema), f"{name}_settings")
return model.model_validate(block).model_dump(mode="json", exclude_none=True)
except (ValueError, SchemaError) as exc:
raise HTTPException(
status.HTTP_422_UNPROCESSABLE_ENTITY, f"invalid settings for {name}: {exc}"
) from exc
def _validate_phase15(svc: Services, body: SettingsIn) -> None:
def bad(msg: str) -> HTTPException:
return HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, msg)
installed = {pk.name for pk in svc.packs}
for name in body.packs or []:
if name not in installed:
raise bad(f"unknown pack {name}")
if body.event_bindings:
from core.agent.tenant_config import collect_alias_claims
claims = collect_alias_claims(svc.packs)
if len(body.event_bindings) > 50:
raise bad("at most 50 event bindings")
for event_type, target in body.event_bindings.items():
cs = claims.get(event_type)
if not cs:
raise bad(f"no installed pack handles event {event_type}")
if target not in {c.intent for c in cs} | {c.pack for c in cs}:
raise bad(f"{target} does not handle {event_type}")
for name, exp in (body.prompt_experiments or {}).items():
from core.memory.prompts import LABEL_RE, NAME_RE
if not NAME_RE.match(name) or not all(LABEL_RE.match(x) for x in exp.labels):
raise bad(f"invalid prompt experiment {name}")