feat(maf-roundtable): add Phase-1 multi-agent roundtable infrastructure

Ship an independent, feature-flag-gated MAF roundtable skeleton with six
isolated tables, atomic single-transaction run launch/cancel, owner-scoped
read/write split, shared config enums, and HTTP/concurrency regression tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
董宏凯andCursor committed 2026-08-01 01:07:05 +08:00
1 parent a0a75a9964
commit e690475e6e
27 files changed
+5369 -101

No files matched your search

@@ -45,6 +45,7 @@ from app.gateway.routers import (
knowledge_ingest,
light_apps,
llm_metrics,
maf_roundtable,
mcp,
memory,
menu_overrides,
@@ -53,11 +54,11 @@ from app.gateway.routers import (
notifications,
open_3qfx,
open_chat,
parallel_agent_tasks,
parallel_agents,
position_roundtable,
positions,
position_roles,
parallel_agent_tasks,
parallel_agents,
position_roundtable,
positions,
position_roles,
public_config,
public_embed,
public_leaderboard,
@@ -858,9 +859,9 @@ async def _concurrency_sampler_loop(app: FastAPI) -> None:
logger.info("Concurrency sampler disabled by CONCURRENCY_SAMPLE_ENABLED")
return
store = getattr(app.state, "concurrency_sample_store", None)
run_mgr = getattr(app.state, "run_manager", None)
concurrency_gate = getattr(app.state, "concurrency_gate", None)
store = getattr(app.state, "concurrency_sample_store", None)
run_mgr = getattr(app.state, "run_manager", None)
concurrency_gate = getattr(app.state, "concurrency_gate", None)
if store is None or run_mgr is None:
logger.info("Concurrency sampler not started (no store / run manager — memory backend?)")
return
@@ -881,16 +882,16 @@ async def _concurrency_sampler_loop(app: FastAPI) -> None:
try:
# Runtime toggle (admin can turn sampling off without a restart).
# mtime-cached read, so this is cheap every tick.
from deerflow.config.system_settings import get_concurrency_monitor_settings
if get_concurrency_monitor_settings().enabled:
active_count = None
if concurrency_gate is not None:
active_count = await concurrency_gate.count_active()
if active_count is None:
active = await run_mgr.list_active()
active_count = len(active)
await store.record(active_count)
from deerflow.config.system_settings import get_concurrency_monitor_settings
if get_concurrency_monitor_settings().enabled:
active_count = None
if concurrency_gate is not None:
active_count = await concurrency_gate.count_active()
if active_count is None:
active = await run_mgr.list_active()
active_count = len(active)
await store.record(active_count)
ticks += 1
if ticks % purge_every_ticks == 0:
from datetime import UTC, datetime, timedelta
@@ -1338,18 +1339,18 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
v = os.environ.get("GATEWAY_CORS_ALLOW_ALL", "").strip().lower()
return v in ("1", "true", "yes", "on") or is_auth_disabled()
# The legacy TaskCOP Vue application uses Vite's default development port.
# Keep these origins available even when deployments configure additional
# origins through GATEWAY_CORS_ORIGINS.
taskcop_vite_origins = [
"http://localhost:8080",
"http://127.0.0.1:8080",
]
cors_origins_env = os.environ.get("GATEWAY_CORS_ORIGINS", "").strip()
cors_origins: list[str] = [o.strip() for o in cors_origins_env.split(",") if o.strip()] if cors_origins_env else []
if cors_origins:
cors_origins = list(dict.fromkeys([*cors_origins, *taskcop_vite_origins]))
# The legacy TaskCOP Vue application uses Vite's default development port.
# Keep these origins available even when deployments configure additional
# origins through GATEWAY_CORS_ORIGINS.
taskcop_vite_origins = [
"http://localhost:8080",
"http://127.0.0.1:8080",
]
cors_origins_env = os.environ.get("GATEWAY_CORS_ORIGINS", "").strip()
cors_origins: list[str] = [o.strip() for o in cors_origins_env.split(",") if o.strip()] if cors_origins_env else []
if cors_origins:
cors_origins = list(dict.fromkeys([*cors_origins, *taskcop_vite_origins]))
# Headers the LangGraph SDK / browser clients need to read from cross-origin
# responses. Without exposing them, the SDK's `response.headers.get(...)` returns
@@ -1408,10 +1409,10 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
"http://127.0.0.1:5173",
"http://localhost:5174",
"http://127.0.0.1:5174",
"http://localhost:3000",
"http://127.0.0.1:3000",
*taskcop_vite_origins,
]
"http://localhost:3000",
"http://127.0.0.1:3000",
*taskcop_vite_origins,
]
logger.warning(
"No CORS configuration found; enabling local dev origins only: %s. "
"Set GATEWAY_CORS_ORIGINS or GATEWAY_CORS_ALLOW_ALL for deployment.",
@@ -1471,25 +1472,25 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
# Step3 流程图结构化抽取 + 校验 (SSE) at /api/flow-extract
app.include_router(flow_extract.router)
# Roundtable-planning business chains at /api/roundtable-chains
app.include_router(roundtable_chains.router)
# 岗位协同独立会话 / 节点状态(不使用原圆桌总控或后台作业)
# Canonical position-workspace persistence API.
app.include_router(position_roundtable.router, prefix="/api")
# Compatibility route for intranet gateways whose allowlist only exposes
# the established `/api/multi-agent/*` namespace.
app.include_router(
position_roundtable.router,
prefix="/api/multi-agent",
include_in_schema=False,
)
# Roundtable-planning business chains at /api/roundtable-chains
app.include_router(roundtable_chains.router)
# 岗位协同独立会话 / 节点状态(不使用原圆桌总控或后台作业)
# Canonical position-workspace persistence API.
app.include_router(position_roundtable.router, prefix="/api")
# Compatibility route for intranet gateways whose allowlist only exposes
# the established `/api/multi-agent/*` namespace.
app.include_router(
position_roundtable.router,
prefix="/api/multi-agent",
include_in_schema=False,
)
# Global business ? agent / chain mapping at /api/business-mapping
app.include_router(business_mapping.router)
# Position-roundtable work-view role configuration at /api/position-roles.
app.include_router(position_roles.router)
app.include_router(business_mapping.router)
# Position-roundtable work-view role configuration at /api/position-roles.
app.include_router(position_roles.router)
# Light-app registry (?????) at /api/light-apps
app.include_router(light_apps.router)
@@ -1509,6 +1510,10 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
# Task-workspace configurable jump buttons (按钮管理) at /api/task-buttons
app.include_router(task_buttons.router)
# Microsoft Agent Framework 多智能体会商实验 (independent of the legacy
# roundtable; feature-flag-gated, six isolated tables) at /api/maf-roundtable
app.include_router(maf_roundtable.router)
# Temporary compatibility bridge for the TaskCOP situation-overview frontend.
app.include_router(taskcop_tasks.router)
@@ -255,23 +255,23 @@ async def langgraph_runtime(app: FastAPI) -> AsyncGenerator[None, None]:
app.state.roundtable_draft_share_store = make_roundtable_draft_share_store(sf)
from deerflow.persistence.roundtable_chains import make_roundtable_chain_store
app.state.roundtable_chain_store = make_roundtable_chain_store(sf)
# 独立的岗位协同 Session / Node 存储。它只索引业务流程状态,真实消息和
# 文件仍复用 LangGraph thread/checkpoint 与现有 artifact API。
from deerflow.persistence.position_roundtable import make_position_roundtable_store
app.state.position_roundtable_store = make_position_roundtable_store(sf)
# 岗位会商工作视角(名称 / 顺序 / 特殊意图岗)是全局配置,和组织/RBAC
# 岗位分开保存。启动只补齐缺失内置项,不覆盖管理员的既有修改。
from app.gateway.position_role_defaults import POSITION_ROLE_SEED
from deerflow.persistence.position_roles import make_position_role_store
app.state.position_role_store = make_position_role_store(sf)
await app.state.position_role_store.ensure_seed(POSITION_ROLE_SEED)
from deerflow.persistence.roundtable_chains import make_roundtable_chain_store
app.state.roundtable_chain_store = make_roundtable_chain_store(sf)
# 独立的岗位协同 Session / Node 存储。它只索引业务流程状态,真实消息和
# 文件仍复用 LangGraph thread/checkpoint 与现有 artifact API。
from deerflow.persistence.position_roundtable import make_position_roundtable_store
app.state.position_roundtable_store = make_position_roundtable_store(sf)
# 岗位会商工作视角(名称 / 顺序 / 特殊意图岗)是全局配置,和组织/RBAC
# 岗位分开保存。启动只补齐缺失内置项,不覆盖管理员的既有修改。
from app.gateway.position_role_defaults import POSITION_ROLE_SEED
from deerflow.persistence.position_roles import make_position_role_store
app.state.position_role_store = make_position_role_store(sf)
await app.state.position_role_store.ensure_seed(POSITION_ROLE_SEED)
from deerflow.persistence.business_mapping import make_business_mapping_store
@@ -295,20 +295,52 @@ async def langgraph_runtime(app: FastAPI) -> AsyncGenerator[None, None]:
from deerflow.persistence.task_buttons import make_task_button_store
app.state.task_button_store = make_task_button_store(sf)
from deerflow.persistence.taskcop_tasks import make_taskcop_task_store
app.state.taskcop_task_store = make_taskcop_task_store(sf)
from deerflow.persistence.task_reports import make_task_report_store
app.state.task_report_store = make_task_report_store(sf)
from deerflow.persistence.parallel_agent_tasks import make_parallel_agent_task_store
app.state.task_button_store = make_task_button_store(sf)
from deerflow.persistence.taskcop_tasks import make_taskcop_task_store
app.state.taskcop_task_store = make_taskcop_task_store(sf)
from deerflow.persistence.task_reports import make_task_report_store
app.state.task_report_store = make_task_report_store(sf)
from deerflow.persistence.parallel_agent_tasks import make_parallel_agent_task_store
app.state.parallel_agent_task_store = make_parallel_agent_task_store(sf)
# ── MAF roundtable experiment (Microsoft Agent Framework 多智能体会商) ──
# Independent, feature-flag-gated sibling of the legacy roundtable. Six
# isolated tables (no FK to roundtable_*). The store is always wired
# (so reads work for admin history review) but the **service** is only
# constructed when ``maf_roundtable.enabled`` is on — that is the gate
# the router checks; when off, write paths return 503 and the MAF SDK
# is never imported. Initialization failures are logged but never
# abort Gateway startup (the feature is experimental / opt-in).
from deerflow.persistence.maf_roundtable import make_maf_roundtable_store
app.state.maf_roundtable_store = make_maf_roundtable_store(sf)
try:
from app.maf_roundtable import MafRoundtableService
maf_cfg = getattr(config, "maf_roundtable", None)
maf_enabled = bool(getattr(maf_cfg, "enabled", False)) if maf_cfg is not None else False
maf_admin_diag = (
bool(getattr(maf_cfg, "admin_diagnostic_access", True)) if maf_cfg is not None else True
)
if app.state.maf_roundtable_store is not None:
app.state.maf_roundtable_service = MafRoundtableService(
app.state.maf_roundtable_store,
enabled=maf_enabled,
admin_diagnostic_access=maf_admin_diag,
config=maf_cfg,
)
else:
app.state.maf_roundtable_service = None
except Exception: # noqa: BLE001 — experimental feature must never abort startup
logger.exception("[maf-roundtable] service initialization failed; feature stays off")
app.state.maf_roundtable_service = None
from deerflow.persistence.roundtable_jobs import (
make_roundtable_job_store,
)
@@ -389,11 +421,11 @@ async def langgraph_runtime(app: FastAPI) -> AsyncGenerator[None, None]:
run_events_config = getattr(config, "run_events", None)
app.state.run_event_store = make_run_event_store(run_events_config)
# RunManager with store backing for persistence
app.state.run_manager = RunManager(store=app.state.run_store)
from deerflow.runtime import make_redis_concurrency_gate
app.state.concurrency_gate = make_redis_concurrency_gate(config)
# RunManager with store backing for persistence
app.state.run_manager = RunManager(store=app.state.run_store)
from deerflow.runtime import make_redis_concurrency_gate
app.state.concurrency_gate = make_redis_concurrency_gate(config)
try:
yield
@@ -407,10 +439,10 @@ async def langgraph_runtime(app: FastAPI) -> AsyncGenerator[None, None]:
await queue.stop()
set_auto_ingest_queue(None)
await close_engine()
gate = getattr(app.state, "concurrency_gate", None)
if gate is not None:
await gate.aclose()
await close_engine()
gate = getattr(app.state, "concurrency_gate", None)
if gate is not None:
await gate.aclose()
# ---------------------------------------------------------------------------
@@ -436,12 +468,12 @@ get_run_manager: Callable[[Request], RunManager] = _require("run_manager", "Run
get_checkpointer: Callable[[Request], Checkpointer] = _require("checkpointer", "Checkpointer")
get_run_event_store: Callable[[Request], RunEventStore] = _require("run_event_store", "Run event store")
get_feedback_repo: Callable[[Request], FeedbackRepository] = _require("feedback_repo", "Feedback")
get_run_store: Callable[[Request], RunStore] = _require("run_store", "Run store")
def get_concurrency_gate(request: Request):
"""Return the optional cross-worker concurrency gate."""
return getattr(request.app.state, "concurrency_gate", None)
get_run_store: Callable[[Request], RunStore] = _require("run_store", "Run store")
def get_concurrency_gate(request: Request):
"""Return the optional cross-worker concurrency gate."""
return getattr(request.app.state, "concurrency_gate", None)
def get_store(request: Request):
@@ -0,0 +1,313 @@
"""HTTP router for the MAF roundtable experiment at ``/api/maf-roundtable``.
Phase 1 ships:
- ``GET /health`` — feature-flag probe (open read; the frontend reads
``enabled`` to decide whether to show the entry).
- Session CRUD: ``POST /sessions``, ``GET /sessions``, ``GET /sessions/{id}``,
``PUT /sessions/{id}``, ``DELETE /sessions/{id}``.
- Run lifecycle: ``POST /sessions/{id}/runs``, ``GET /runs/{id}``,
``GET /sessions/{id}/runs``, ``POST /runs/{id}/cancel``.
- Event stream: ``GET /runs/{id}/events?after_seq=N`` (断线补拉) — **read-only**;
there is no public ``POST /runs/{id}/events``. Real workflow events are
written only by the backend executor via ``service.append_event``.
- Actions: ``GET /runs/{id}/actions``, ``GET /actions/{id}``.
- Approvals: ``GET /runs/{id}/approvals``, ``POST /approvals/{id}/decision``.
User isolation (MAF-01-07): every read / write is scoped to the caller's
``user_id``; admins may *read* cross-user when ``admin_diagnostic_access`` is
on, but **writes** remain owner-only (admin write of another user's resource
→ 403). A non-admin user cannot read or mutate another user's session / run /
action / approval — the store returns ``None`` for out-of-scope rows and the
router surfaces that as ``404`` (not ``403``, so the existence of another
user's session is not leaked).
Feature flag (MAF-01-04): when ``maf_roundtable.enabled`` is off, write paths
return ``503 Service Disabled``; reads stay open so admins can review history.
The MAF SDK is **not** imported by this router — Phase 2+ imports it lazily
inside ``app.maf_roundtable.service`` only when a run is actually started.
"""
from __future__ import annotations
from typing import Any
from fastapi import APIRouter, HTTPException, Query, Request
from app.maf_roundtable import (
ActionListResponse,
ActionResponse,
ApprovalDecisionRequest,
ApprovalListResponse,
ApprovalResponse,
CreateRunRequest,
CreateSessionRequest,
EventListResponse,
EventResponse,
HealthResponse,
MafConflictError,
MafDisabledError,
MafForbiddenError,
MafNotFoundError,
RunListResponse,
RunResponse,
SessionListResponse,
SessionResponse,
UpdateSessionRequest,
)
router = APIRouter(prefix="/api/maf-roundtable", tags=["maf-roundtable"])
# ── helpers ───────────────────────────────────────────────────────────────
def _get_service(request: Request):
"""Resolve the MAF service from app.state. Returns None when the feature
is fully off (no store wired) — the router then 503s on writes.
"""
return getattr(request.app.state, "maf_roundtable_service", None)
def _user_ctx(request: Request) -> tuple[str | None, bool]:
"""Return ``(user_id, is_admin)`` for the current request.
When auth is disabled (no user stamped on request.state), the caller is
treated as the ``"default"`` user (same convention as
``get_effective_user_id``) and non-admin — so a no-auth deployment stays
owner-scoped to ``"default"`` rather than accidentally bypassing the
owner filter.
"""
user = getattr(request.state, "user", None)
if user is None:
return "default", False
return str(user.id), getattr(user, "system_role", None) == "admin"
def _map_service_error(exc: Exception) -> HTTPException:
if isinstance(exc, MafDisabledError):
return HTTPException(status_code=503, detail="MAF roundtable feature is disabled")
if isinstance(exc, MafForbiddenError):
return HTTPException(status_code=403, detail=f"not the owner of {exc.what}")
if isinstance(exc, MafNotFoundError):
return HTTPException(status_code=404, detail=f"{exc.what} not found")
if isinstance(exc, MafConflictError):
return HTTPException(status_code=409, detail=str(exc))
return HTTPException(status_code=500, detail=str(exc))
def _require_service(request: Request):
svc = _get_service(request)
if svc is None:
raise HTTPException(status_code=503, detail="MAF roundtable store not available")
return svc
# ── health ─────────────────────────────────────────────────────────────────
@router.get("/health", response_model=HealthResponse)
async def get_health(request: Request) -> HealthResponse:
"""Feature-flag probe. Open read — the frontend reads ``enabled`` to
decide whether to show the MAF entry. Does not require the store.
"""
from deerflow.config import get_app_config
cfg = get_app_config().maf_roundtable
svc = _get_service(request)
store_available = svc is not None and svc.store is not None
return HealthResponse(
enabled=cfg.enabled,
store_available=store_available,
default_mode=cfg.default_mode,
default_write_policy=cfg.default_write_policy,
default_max_rounds=cfg.default_max_rounds,
admin_diagnostic_access=cfg.admin_diagnostic_access,
)
# ── sessions ───────────────────────────────────────────────────────────────
@router.post("/sessions", response_model=SessionResponse)
async def create_session(request: Request, body: CreateSessionRequest) -> SessionResponse:
svc = _require_service(request)
user_id, is_admin = _user_ctx(request)
try:
session = await svc.create_session(user_id=user_id, body=body.model_dump(), is_admin=is_admin)
except (MafDisabledError, MafForbiddenError, MafNotFoundError, MafConflictError) as exc:
raise _map_service_error(exc) from exc
return SessionResponse(**session)
@router.get("/sessions", response_model=SessionListResponse)
async def list_sessions(
request: Request,
status: str | None = Query(default=None),
mode: str | None = Query(default=None),
limit: int = Query(default=100, ge=1, le=500),
offset: int = Query(default=0, ge=0),
) -> SessionListResponse:
svc = _require_service(request)
user_id, is_admin = _user_ctx(request)
rows, total = await svc.list_sessions(
user_id=user_id, is_admin=is_admin, status=status, mode=mode, limit=limit, offset=offset
)
return SessionListResponse(sessions=[SessionResponse(**r) for r in rows], total=total)
@router.get("/sessions/{session_id}", response_model=SessionResponse)
async def get_session(request: Request, session_id: str) -> SessionResponse:
svc = _require_service(request)
user_id, is_admin = _user_ctx(request)
try:
session = await svc.get_session(session_id=session_id, user_id=user_id, is_admin=is_admin)
except MafNotFoundError as exc:
raise _map_service_error(exc) from exc
return SessionResponse(**session)
@router.put("/sessions/{session_id}", response_model=SessionResponse)
async def update_session(request: Request, session_id: str, body: UpdateSessionRequest) -> SessionResponse:
svc = _require_service(request)
user_id, is_admin = _user_ctx(request)
try:
session = await svc.update_session(
session_id=session_id, user_id=user_id, fields=body.model_dump(exclude_unset=True), is_admin=is_admin
)
except (MafDisabledError, MafForbiddenError, MafNotFoundError, MafConflictError) as exc:
raise _map_service_error(exc) from exc
return SessionResponse(**session)
@router.delete("/sessions/{session_id}")
async def delete_session(request: Request, session_id: str) -> dict[str, Any]:
svc = _require_service(request)
user_id, is_admin = _user_ctx(request)
try:
await svc.delete_session(session_id=session_id, user_id=user_id, is_admin=is_admin)
except (MafDisabledError, MafForbiddenError, MafNotFoundError) as exc:
raise _map_service_error(exc) from exc
return {"deleted": True, "id": session_id}
# ── runs ───────────────────────────────────────────────────────────────────
@router.post("/sessions/{session_id}/runs", response_model=RunResponse)
async def create_run(request: Request, session_id: str, body: CreateRunRequest) -> RunResponse:
svc = _require_service(request)
user_id, is_admin = _user_ctx(request)
try:
run = await svc.create_run(
session_id=session_id, user_id=user_id, workflow_version=body.workflow_version, is_admin=is_admin
)
except (MafDisabledError, MafForbiddenError, MafNotFoundError, MafConflictError) as exc:
raise _map_service_error(exc) from exc
return RunResponse(**run)
@router.get("/sessions/{session_id}/runs", response_model=RunListResponse)
async def list_runs(request: Request, session_id: str) -> RunListResponse:
svc = _require_service(request)
user_id, is_admin = _user_ctx(request)
try:
runs = await svc.list_runs(session_id=session_id, user_id=user_id, is_admin=is_admin)
except MafNotFoundError as exc:
raise _map_service_error(exc) from exc
return RunListResponse(runs=[RunResponse(**r) for r in runs])
@router.get("/runs/{run_id}", response_model=RunResponse)
async def get_run(request: Request, run_id: str) -> RunResponse:
svc = _require_service(request)
user_id, is_admin = _user_ctx(request)
try:
run = await svc.get_run(run_id=run_id, user_id=user_id, is_admin=is_admin)
except MafNotFoundError as exc:
raise _map_service_error(exc) from exc
return RunResponse(**run)
@router.post("/runs/{run_id}/cancel", response_model=RunResponse)
async def cancel_run(request: Request, run_id: str) -> RunResponse:
svc = _require_service(request)
user_id, is_admin = _user_ctx(request)
try:
run = await svc.cancel_run(run_id=run_id, user_id=user_id, is_admin=is_admin)
except (MafDisabledError, MafForbiddenError, MafNotFoundError) as exc:
raise _map_service_error(exc) from exc
return RunResponse(**run)
# ── events ─────────────────────────────────────────────────────────────────
@router.get("/runs/{run_id}/events", response_model=EventListResponse)
async def list_events(
request: Request,
run_id: str,
after_seq: int = Query(default=0, ge=0),
limit: int = Query(default=1000, ge=1, le=10000),
) -> EventListResponse:
svc = _require_service(request)
user_id, is_admin = _user_ctx(request)
try:
events, latest = await svc.list_events(
run_id=run_id, user_id=user_id, after_seq=after_seq, limit=limit, is_admin=is_admin
)
except MafNotFoundError as exc:
raise _map_service_error(exc) from exc
return EventListResponse(events=[EventResponse(**e) for e in events], latest_seq=latest)
# ── actions ────────────────────────────────────────────────────────────────
@router.get("/runs/{run_id}/actions", response_model=ActionListResponse)
async def list_actions(request: Request, run_id: str) -> ActionListResponse:
svc = _require_service(request)
user_id, is_admin = _user_ctx(request)
try:
actions = await svc.list_actions(run_id=run_id, user_id=user_id, is_admin=is_admin)
except MafNotFoundError as exc:
raise _map_service_error(exc) from exc
return ActionListResponse(actions=[ActionResponse(**a) for a in actions])
@router.get("/actions/{action_id}", response_model=ActionResponse)
async def get_action(request: Request, action_id: str) -> ActionResponse:
svc = _require_service(request)
user_id, is_admin = _user_ctx(request)
try:
action = await svc.get_action(action_id=action_id, user_id=user_id, is_admin=is_admin)
except MafNotFoundError as exc:
raise _map_service_error(exc) from exc
return ActionResponse(**action)
# ── approvals ──────────────────────────────────────────────────────────────
@router.get("/runs/{run_id}/approvals", response_model=ApprovalListResponse)
async def list_approvals(request: Request, run_id: str) -> ApprovalListResponse:
svc = _require_service(request)
user_id, is_admin = _user_ctx(request)
try:
approvals = await svc.list_approvals(run_id=run_id, user_id=user_id, is_admin=is_admin)
except MafNotFoundError as exc:
raise _map_service_error(exc) from exc
return ApprovalListResponse(approvals=[ApprovalResponse(**a) for a in approvals])
@router.post("/approvals/{approval_id}/decision", response_model=ApprovalResponse)
async def decide_approval(request: Request, approval_id: str, body: ApprovalDecisionRequest) -> ApprovalResponse:
svc = _require_service(request)
user_id, is_admin = _user_ctx(request)
try:
approval = await svc.decide_approval(
approval_id=approval_id, decision=body.decision, user_id=user_id, is_admin=is_admin
)
except (MafDisabledError, MafForbiddenError, MafNotFoundError, MafConflictError) as exc:
raise _map_service_error(exc) from exc
return ApprovalResponse(**approval)