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:
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)
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Microsoft Agent Framework (MAF) multi-agent roundtable experiment.
|
||||
|
||||
An independent, feature-flag-gated sibling of the legacy multi-agent
|
||||
roundtable (``/api/roundtable-*`` / ``/api/multi-agent/*``). It uses MAF's
|
||||
Agent / Workflow / Group Chat orchestration while reusing the existing
|
||||
DeerFlow Agent Runtime for each seat's actual execution (tools / skills /
|
||||
MCP / sandbox / external writes). Phase 1 ships the persistence skeleton +
|
||||
API contracts; the MAF SDK is loaded lazily inside this package only when
|
||||
the feature flag is on and a run is actually started (Phase 2+).
|
||||
|
||||
Boundary: this package is the **only** place the MAF SDK is imported. It may
|
||||
import ``deerflow.*`` (harness) freely but must not be imported by
|
||||
``deerflow.*``. The harness-layer persistence (``deerflow.persistence.maf_roundtable``)
|
||||
holds only pure data models and never imports the MAF SDK.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.maf_roundtable.schemas import ( # noqa: F401 — re-exported for the router
|
||||
ActionListResponse,
|
||||
ActionResponse,
|
||||
ApprovalDecisionRequest,
|
||||
ApprovalListResponse,
|
||||
ApprovalResponse,
|
||||
CreateRunRequest,
|
||||
CreateSessionRequest,
|
||||
EventListResponse,
|
||||
EventResponse,
|
||||
HealthResponse,
|
||||
ParticipantInput,
|
||||
ParticipantResponse,
|
||||
RunListResponse,
|
||||
RunResponse,
|
||||
SessionListResponse,
|
||||
SessionResponse,
|
||||
UpdateSessionRequest,
|
||||
)
|
||||
from app.maf_roundtable.service import ( # noqa: F401
|
||||
MafConflictError,
|
||||
MafDisabledError,
|
||||
MafForbiddenError,
|
||||
MafNotFoundError,
|
||||
MafRoundtableService,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"ActionListResponse",
|
||||
"ActionResponse",
|
||||
"ApprovalDecisionRequest",
|
||||
"ApprovalListResponse",
|
||||
"ApprovalResponse",
|
||||
"CreateRunRequest",
|
||||
"CreateSessionRequest",
|
||||
"EventListResponse",
|
||||
"EventResponse",
|
||||
"HealthResponse",
|
||||
"MafConflictError",
|
||||
"MafDisabledError",
|
||||
"MafForbiddenError",
|
||||
"MafNotFoundError",
|
||||
"MafRoundtableService",
|
||||
"ParticipantInput",
|
||||
"ParticipantResponse",
|
||||
"RunListResponse",
|
||||
"RunResponse",
|
||||
"SessionListResponse",
|
||||
"SessionResponse",
|
||||
"UpdateSessionRequest",
|
||||
]
|
||||
@@ -0,0 +1,257 @@
|
||||
"""Pydantic request/response schemas for the MAF roundtable API.
|
||||
|
||||
These are the wire contracts between the frontend (Phase 6) and the backend.
|
||||
Phase 1 ships the session / participant / run / event contracts; the action /
|
||||
approval contracts are defined too so Phase 5 can wire the Action Coordinator
|
||||
without a schema break. Sensitive fields (credentials / tokens / cookies)
|
||||
must already be redacted by the writer before they reach these schemas — the
|
||||
backend does not re-redact.
|
||||
|
||||
``MafMode`` / ``MafWritePolicy`` / ``MafParticipantRole`` are imported from the
|
||||
harness config module so API validation and deployment-config validation share
|
||||
a single source of truth.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Self
|
||||
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
from deerflow.config.maf_roundtable_config import MafMode, MafParticipantRole, MafWritePolicy
|
||||
|
||||
# ── sessions ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class ParticipantInput(BaseModel):
|
||||
"""One seat / manager agent bound to a session at creation time."""
|
||||
|
||||
agent_id: str = Field(..., min_length=1, max_length=64)
|
||||
display_name: str = Field(default="", max_length=255)
|
||||
role: MafParticipantRole = "seat"
|
||||
sort_order: int = 0
|
||||
# Frozen at creation — the agent's tools / skills snapshot.
|
||||
capability_snapshot: dict[str, Any] | None = None
|
||||
|
||||
|
||||
class CreateSessionRequest(BaseModel):
|
||||
title: str = Field(default="", max_length=255)
|
||||
task_text: str = Field(..., min_length=1)
|
||||
task_payload: dict[str, Any] | None = None
|
||||
# Optional: omitted → service layer fills from MafRoundtableConfig.default_mode.
|
||||
mode: MafMode | None = None
|
||||
model_name: str | None = Field(default=None, max_length=128)
|
||||
reasoning_effort: str | None = Field(default=None, max_length=32)
|
||||
manager_agent_id: str | None = Field(default=None, max_length=64)
|
||||
# Optional: omitted → MafRoundtableConfig.default_max_rounds.
|
||||
max_rounds: int | None = Field(default=None, ge=1, le=64)
|
||||
# Optional: omitted → MafRoundtableConfig.default_write_policy.
|
||||
write_policy: MafWritePolicy | None = None
|
||||
participants: list[ParticipantInput] = Field(default_factory=list)
|
||||
# Frozen at creation — the full session capability snapshot (agents + tools + skills).
|
||||
capability_snapshot: dict[str, Any] | None = None
|
||||
|
||||
|
||||
# Fields that must not be explicitly set to null on PUT (→ 422).
|
||||
# Clearable fields (task_payload / model_name / reasoning_effort /
|
||||
# manager_agent_id / fact_ledger / final_result) keep null = "clear value".
|
||||
_NON_NULLABLE_UPDATE_FIELDS = frozenset(
|
||||
{"title", "task_text", "mode", "max_rounds", "write_policy", "participants"}
|
||||
)
|
||||
|
||||
|
||||
class UpdateSessionRequest(BaseModel):
|
||||
"""Partial update — only allowed when the session is not yet ``running``.
|
||||
|
||||
Distinguishes "field omitted" (no change) from "field set to null":
|
||||
- Non-nullable fields (title / task_text / mode / max_rounds / write_policy /
|
||||
participants): explicit ``null`` → 422.
|
||||
- Clearable fields (task_payload / model_name / reasoning_effort /
|
||||
manager_agent_id / fact_ledger / final_result): explicit ``null`` clears.
|
||||
Do **not** use ``exclude_none=True`` — that would collapse the two cases.
|
||||
"""
|
||||
|
||||
title: str | None = Field(default=None, max_length=255)
|
||||
task_text: str | None = None
|
||||
task_payload: dict[str, Any] | None = None
|
||||
mode: MafMode | None = None
|
||||
model_name: str | None = Field(default=None, max_length=128)
|
||||
reasoning_effort: str | None = Field(default=None, max_length=32)
|
||||
manager_agent_id: str | None = Field(default=None, max_length=64)
|
||||
max_rounds: int | None = Field(default=None, ge=1, le=64)
|
||||
write_policy: MafWritePolicy | None = None
|
||||
participants: list[ParticipantInput] | None = None
|
||||
# fact_ledger / final_result are mutable runtime fields (updated by the run lifecycle).
|
||||
fact_ledger: dict[str, Any] | None = None
|
||||
final_result: dict[str, Any] | None = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _reject_explicit_null_for_non_nullable(self) -> Self:
|
||||
for name in _NON_NULLABLE_UPDATE_FIELDS:
|
||||
if name in self.model_fields_set and getattr(self, name) is None:
|
||||
raise ValueError(f"{name} cannot be null")
|
||||
return self
|
||||
|
||||
|
||||
class ParticipantResponse(BaseModel):
|
||||
id: str
|
||||
session_id: str
|
||||
agent_id: str
|
||||
display_name: str
|
||||
role: str
|
||||
sort_order: int
|
||||
thread_id: str | None = None
|
||||
sandbox_id: str | None = None
|
||||
status: str
|
||||
last_turn_index: int | None = None
|
||||
capability_snapshot: dict[str, Any] | None = None
|
||||
created_at: str | None = None
|
||||
updated_at: str | None = None
|
||||
|
||||
|
||||
class SessionResponse(BaseModel):
|
||||
id: str
|
||||
user_id: str
|
||||
title: str
|
||||
task_text: str
|
||||
task_payload: dict[str, Any] | None = None
|
||||
mode: str
|
||||
status: str
|
||||
model_name: str | None = None
|
||||
reasoning_effort: str | None = None
|
||||
manager_agent_id: str | None = None
|
||||
max_rounds: int
|
||||
write_policy: str
|
||||
capability_snapshot: dict[str, Any] | None = None
|
||||
fact_ledger: dict[str, Any] | None = None
|
||||
final_result: dict[str, Any] | None = None
|
||||
participants: list[ParticipantResponse] = Field(default_factory=list)
|
||||
created_at: str | None = None
|
||||
updated_at: str | None = None
|
||||
|
||||
|
||||
class SessionListResponse(BaseModel):
|
||||
sessions: list[SessionResponse]
|
||||
total: int
|
||||
|
||||
|
||||
# ── runs ──────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class RunResponse(BaseModel):
|
||||
id: str
|
||||
session_id: str
|
||||
status: str
|
||||
workflow_version: str | None = None
|
||||
maf_checkpoint: dict[str, Any] | None = None
|
||||
last_event_seq: int
|
||||
started_at: str | None = None
|
||||
finished_at: str | None = None
|
||||
error_code: str | None = None
|
||||
error_message_safe: str | None = None
|
||||
token_usage: dict[str, Any] | None = None
|
||||
latency_ms: int | None = None
|
||||
created_at: str | None = None
|
||||
updated_at: str | None = None
|
||||
|
||||
|
||||
class RunListResponse(BaseModel):
|
||||
runs: list[RunResponse]
|
||||
|
||||
|
||||
class CreateRunRequest(BaseModel):
|
||||
workflow_version: str | None = Field(default=None, max_length=64)
|
||||
|
||||
|
||||
# ── events ───────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class EventResponse(BaseModel):
|
||||
id: str
|
||||
session_id: str
|
||||
run_id: str
|
||||
seq: int
|
||||
event_type: str
|
||||
agent_id: str | None = None
|
||||
turn_index: int | None = None
|
||||
payload: dict[str, Any] | None = None
|
||||
created_at: str | None = None
|
||||
|
||||
|
||||
class EventListResponse(BaseModel):
|
||||
events: list[EventResponse]
|
||||
latest_seq: int
|
||||
|
||||
|
||||
# ── actions ───────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class ActionResponse(BaseModel):
|
||||
id: str
|
||||
session_id: str
|
||||
run_id: str | None = None
|
||||
agent_id: str | None = None
|
||||
tool_name: str
|
||||
logical_action_id: str | None = None
|
||||
idempotency_key: str
|
||||
target_key: str | None = None
|
||||
risk_level: str
|
||||
status: str
|
||||
arguments: dict[str, Any] | None = None
|
||||
result: dict[str, Any] | None = None
|
||||
external_object_id: str | None = None
|
||||
approval_id: str | None = None
|
||||
attempt_count: int
|
||||
started_at: str | None = None
|
||||
finished_at: str | None = None
|
||||
created_at: str | None = None
|
||||
updated_at: str | None = None
|
||||
|
||||
|
||||
class ActionListResponse(BaseModel):
|
||||
actions: list[ActionResponse]
|
||||
|
||||
|
||||
# ── approvals ─────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class ApprovalResponse(BaseModel):
|
||||
id: str
|
||||
session_id: str
|
||||
run_id: str | None = None
|
||||
action_id: str | None = None
|
||||
requested_by_agent_id: str | None = None
|
||||
status: str
|
||||
summary: str
|
||||
payload: dict[str, Any] | None = None
|
||||
decided_by: str | None = None
|
||||
decided_at: str | None = None
|
||||
expires_at: str | None = None
|
||||
created_at: str | None = None
|
||||
updated_at: str | None = None
|
||||
|
||||
|
||||
class ApprovalListResponse(BaseModel):
|
||||
approvals: list[ApprovalResponse]
|
||||
|
||||
|
||||
class ApprovalDecisionRequest(BaseModel):
|
||||
# approved | rejected
|
||||
decision: str = Field(..., pattern="^(approved|rejected)$")
|
||||
|
||||
|
||||
# ── health ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class HealthResponse(BaseModel):
|
||||
"""Health / feature-flag probe. The frontend reads ``enabled`` to decide
|
||||
whether to show the MAF entry. ``store_available`` is false when no DB is
|
||||
configured (memory mode) — the router then returns 503 on writes.
|
||||
"""
|
||||
|
||||
enabled: bool
|
||||
store_available: bool
|
||||
default_mode: str
|
||||
default_write_policy: str
|
||||
default_max_rounds: int
|
||||
admin_diagnostic_access: bool
|
||||
@@ -0,0 +1,390 @@
|
||||
"""Service layer for the MAF roundtable experiment.
|
||||
|
||||
Enforces the cross-cutting policies the individual repositories don't:
|
||||
|
||||
- **User isolation (MAF-01-07)**: every read / write is scoped to the caller's
|
||||
``user_id``. Read and write scopes are deliberately **separate**:
|
||||
``admin_diagnostic_access`` only widens the *read* scope (cross-user
|
||||
diagnostics) — it never grants cross-user *writes*. Every mutating operation
|
||||
(update / delete session, start / cancel run, append event, decide approval)
|
||||
is owner-checked via ``_write_scope_user`` regardless of the diagnostic flag.
|
||||
- **Run gating + atomic launch**: a session may have at most one active run
|
||||
(``starting`` / ``running`` / ``waiting_*``). The launch is a **single
|
||||
database transaction** (``store.claim_and_create_pending_run``) that
|
||||
conditionally updates the session to ``running`` and inserts a ``pending``
|
||||
run together — not a multi-step claim/create/set_status dance, and not a
|
||||
Python lock. Concurrent callers cannot both win; a mid-transaction failure
|
||||
rolls everything back so the session never sticks in a half-claimed state.
|
||||
- **Feature flag**: when ``maf_roundtable.enabled`` is off, write paths raise
|
||||
``MafDisabledError`` (the router maps it to 503); reads stay open so admins
|
||||
can review history.
|
||||
- **Config-driven defaults**: ``mode`` / ``write_policy`` / ``max_rounds``
|
||||
default to the deployed ``MafRoundtableConfig`` values when the create
|
||||
request omits them; an explicit request value always wins.
|
||||
|
||||
The service does **not** load the MAF SDK — that is Phase 2+ (the
|
||||
``DeerFlowAgentAdapter``). Phase 1 ships the persistence + API skeleton; until
|
||||
a real executor exists, a launched run is parked in ``pending`` (clearly a
|
||||
reserved / not-yet-executing state) rather than pretending to be ``running``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from deerflow.config.maf_roundtable_config import MafRoundtableConfig
|
||||
from deerflow.persistence.maf_roundtable.store import MafRoundtableStore
|
||||
|
||||
|
||||
class MafDisabledError(RuntimeError):
|
||||
"""Raised when a write is attempted while the feature flag is off."""
|
||||
|
||||
|
||||
class MafNotFoundError(KeyError):
|
||||
"""Raised when a session / run / action / approval is missing or out of scope."""
|
||||
|
||||
def __init__(self, what: str, ident: str) -> None:
|
||||
super().__init__(f"{what} not found or out of scope: {ident}")
|
||||
self.what = what
|
||||
self.ident = ident
|
||||
|
||||
|
||||
class MafConflictError(RuntimeError):
|
||||
"""Raised when a session is in a state that rejects the requested edit."""
|
||||
|
||||
|
||||
class MafForbiddenError(PermissionError):
|
||||
"""Raised when a caller is authenticated but not the owner of the target
|
||||
resource (e.g. an admin trying to *write* another user's session while
|
||||
only holding cross-user *read* via the diagnostic flag)."""
|
||||
|
||||
def __init__(self, what: str, ident: str) -> None:
|
||||
super().__init__(f"not the owner of {what}: {ident}")
|
||||
self.what = what
|
||||
self.ident = ident
|
||||
|
||||
|
||||
# Session statuses that may be edited (config changes).
|
||||
_EDITABLE_STATUSES = {"draft", "completed", "failed", "cancelled"}
|
||||
# Session statuses that mean a run is in flight (no config edits). ``starting``
|
||||
# is the transient CAS-claim state between "claimed" and "run row created".
|
||||
_RUNNING_STATUSES = {"starting", "running", "waiting_approval", "waiting_input"}
|
||||
|
||||
|
||||
class MafRoundtableService:
|
||||
def __init__(
|
||||
self,
|
||||
store: MafRoundtableStore,
|
||||
*,
|
||||
enabled: bool,
|
||||
admin_diagnostic_access: bool,
|
||||
config: MafRoundtableConfig | None = None,
|
||||
) -> None:
|
||||
self._store = store
|
||||
self._enabled = enabled
|
||||
self._admin_diagnostic_access = admin_diagnostic_access
|
||||
# Defaults source for create_session; falls back to the pydantic
|
||||
# defaults when no config is injected (keeps unit tests lightweight).
|
||||
self._config = config or MafRoundtableConfig()
|
||||
|
||||
@property
|
||||
def store(self) -> MafRoundtableStore:
|
||||
return self._store
|
||||
|
||||
@property
|
||||
def enabled(self) -> bool:
|
||||
return self._enabled
|
||||
|
||||
@property
|
||||
def config(self) -> MafRoundtableConfig:
|
||||
return self._config
|
||||
|
||||
def _require_enabled(self) -> None:
|
||||
if not self._enabled:
|
||||
raise MafDisabledError("MAF roundtable feature is disabled")
|
||||
|
||||
# ── permission scopes ──────────────────────────────────────────────────
|
||||
|
||||
def _read_scope_user(self, user_id: str | None, is_admin: bool) -> str | None:
|
||||
"""User id to scope **read** queries by.
|
||||
|
||||
- Admin with diagnostic access: ``None`` (cross-user read for diagnostics).
|
||||
- Anyone else: their own ``user_id`` (enforced).
|
||||
"""
|
||||
if is_admin and self._admin_diagnostic_access:
|
||||
return None
|
||||
return user_id
|
||||
|
||||
def _write_scope_user(self, user_id: str | None, is_admin: bool) -> str | None:
|
||||
"""User id to scope **write** operations by.
|
||||
|
||||
The diagnostic flag is read-only — it never widens the write scope.
|
||||
Every mutating operation is owner-checked against the caller's own
|
||||
``user_id`` (admin or not). A future explicit operator/admin force-stop
|
||||
would be a separate, audited code path, not a reuse of this flag.
|
||||
"""
|
||||
return user_id
|
||||
|
||||
# ── sessions ──────────────────────────────────────────────────────────
|
||||
|
||||
async def create_session(
|
||||
self, *, user_id: str, body: dict[str, Any], is_admin: bool = False
|
||||
) -> dict[str, Any]:
|
||||
self._require_enabled()
|
||||
cfg = self._config
|
||||
# Config-driven defaults: an omitted field falls back to the deployed
|
||||
# MafRoundtableConfig value; an explicit request value always wins.
|
||||
session_data: dict[str, Any] = {
|
||||
"user_id": user_id,
|
||||
"title": body.get("title", ""),
|
||||
"task_text": body["task_text"],
|
||||
"task_payload": body.get("task_payload"),
|
||||
"mode": body.get("mode") or cfg.default_mode,
|
||||
"status": "draft",
|
||||
"model_name": body.get("model_name"),
|
||||
"reasoning_effort": body.get("reasoning_effort"),
|
||||
"manager_agent_id": body.get("manager_agent_id"),
|
||||
"max_rounds": body.get("max_rounds") if body.get("max_rounds") is not None else cfg.default_max_rounds,
|
||||
"write_policy": body.get("write_policy") or cfg.default_write_policy,
|
||||
"capability_snapshot": body.get("capability_snapshot"),
|
||||
}
|
||||
session = await self._store.sessions.create_session(session_data)
|
||||
participants = body.get("participants") or []
|
||||
if participants:
|
||||
await self._store.participants.replace_participants(session["id"], participants)
|
||||
return await self.get_session(session_id=session["id"], user_id=user_id, is_admin=is_admin)
|
||||
|
||||
async def get_session(self, *, session_id: str, user_id: str | None, is_admin: bool = False) -> dict[str, Any]:
|
||||
scope = self._read_scope_user(user_id, is_admin)
|
||||
session = await self._store.sessions.get_session(session_id, user_id=scope)
|
||||
if session is None:
|
||||
raise MafNotFoundError("session", session_id)
|
||||
participants = await self._store.participants.list_participants(session_id)
|
||||
session["participants"] = participants
|
||||
return session
|
||||
|
||||
async def list_sessions(
|
||||
self,
|
||||
*,
|
||||
user_id: str | None,
|
||||
is_admin: bool = False,
|
||||
status: str | None = None,
|
||||
mode: str | None = None,
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
) -> tuple[list[dict[str, Any]], int]:
|
||||
scope = self._read_scope_user(user_id, is_admin)
|
||||
rows = await self._store.sessions.list_sessions(
|
||||
user_id=scope, status=status, mode=mode, limit=limit, offset=offset
|
||||
)
|
||||
total = await self._store.sessions.count_sessions(user_id=scope, status=status, mode=mode)
|
||||
# Attach participants to each row (cheap — Phase 1 lists are bounded).
|
||||
for row in rows:
|
||||
row["participants"] = await self._store.participants.list_participants(row["id"])
|
||||
return rows, total
|
||||
|
||||
async def update_session(
|
||||
self, *, session_id: str, user_id: str | None, fields: dict[str, Any], is_admin: bool = False
|
||||
) -> dict[str, Any]:
|
||||
self._require_enabled()
|
||||
# Writes are owner-scoped even for admins (diagnostic access is read-only).
|
||||
scope = self._write_scope_user(user_id, is_admin)
|
||||
existing = await self._store.sessions.get_session(session_id, user_id=scope)
|
||||
if existing is None:
|
||||
# Distinguish "missing" from "owned by someone else" so an admin
|
||||
# (who can read cross-user) gets a clear 403 rather than a 404.
|
||||
if is_admin and await self._store.sessions.get_session(session_id, user_id=None) is not None:
|
||||
raise MafForbiddenError("session", session_id)
|
||||
raise MafNotFoundError("session", session_id)
|
||||
if existing["status"] in _RUNNING_STATUSES:
|
||||
raise MafConflictError(
|
||||
f"session {session_id} is running ({existing['status']}); config edits not allowed"
|
||||
)
|
||||
# capability_snapshot is frozen — never accept it on update.
|
||||
fields.pop("capability_snapshot", None)
|
||||
updated = await self._store.sessions.update_session(session_id, user_id=scope, fields=fields)
|
||||
if updated is None:
|
||||
raise MafNotFoundError("session", session_id)
|
||||
if "participants" in fields and fields["participants"] is not None:
|
||||
await self._store.participants.replace_participants(session_id, fields["participants"])
|
||||
return await self.get_session(session_id=session_id, user_id=user_id, is_admin=is_admin)
|
||||
|
||||
async def delete_session(self, *, session_id: str, user_id: str | None, is_admin: bool = False) -> None:
|
||||
self._require_enabled()
|
||||
scope = self._write_scope_user(user_id, is_admin)
|
||||
# Pre-check existence cross-user so an admin gets 403, not 404.
|
||||
if await self._store.sessions.get_session(session_id, user_id=scope) is None:
|
||||
if is_admin and await self._store.sessions.get_session(session_id, user_id=None) is not None:
|
||||
raise MafForbiddenError("session", session_id)
|
||||
raise MafNotFoundError("session", session_id)
|
||||
ok = await self._store.sessions.delete_session(session_id, user_id=scope)
|
||||
if not ok:
|
||||
raise MafNotFoundError("session", session_id)
|
||||
|
||||
# ── runs ────────────────────────────────────────────────────────────────
|
||||
|
||||
async def create_run(
|
||||
self, *, session_id: str, user_id: str | None, workflow_version: str | None = None, is_admin: bool = False
|
||||
) -> dict[str, Any]:
|
||||
self._require_enabled()
|
||||
# Owner-only write: an admin cannot start another user's run. The
|
||||
# owner_user_id also rides in the atomic SQL (not just this pre-check).
|
||||
if not user_id:
|
||||
raise MafNotFoundError("session", session_id)
|
||||
|
||||
run = await self._store.claim_and_create_pending_run(
|
||||
session_id=session_id,
|
||||
owner_user_id=user_id,
|
||||
workflow_version=workflow_version,
|
||||
)
|
||||
if run is not None:
|
||||
return run
|
||||
|
||||
# Classify the failed claim: missing / wrong-owner / already active.
|
||||
any_session = await self._store.sessions.get_session(session_id, user_id=None)
|
||||
if any_session is None:
|
||||
raise MafNotFoundError("session", session_id)
|
||||
if any_session["user_id"] != user_id:
|
||||
if is_admin:
|
||||
raise MafForbiddenError("session", session_id)
|
||||
raise MafNotFoundError("session", session_id)
|
||||
raise MafConflictError(
|
||||
f"session {session_id} already has an active run; concurrent launch rejected"
|
||||
)
|
||||
|
||||
async def get_run(self, *, run_id: str, user_id: str | None, is_admin: bool = False) -> dict[str, Any]:
|
||||
run = await self._store.runs.get_run(run_id)
|
||||
if run is None:
|
||||
raise MafNotFoundError("run", run_id)
|
||||
# Enforce session owner scope (read scope — admins may diagnose).
|
||||
scope = self._read_scope_user(user_id, is_admin)
|
||||
session = await self._store.sessions.get_session(run["session_id"], user_id=scope)
|
||||
if session is None:
|
||||
raise MafNotFoundError("run", run_id)
|
||||
return run
|
||||
|
||||
async def list_runs(self, *, session_id: str, user_id: str | None, is_admin: bool = False) -> list[dict[str, Any]]:
|
||||
scope = self._read_scope_user(user_id, is_admin)
|
||||
session = await self._store.sessions.get_session(session_id, user_id=scope)
|
||||
if session is None:
|
||||
raise MafNotFoundError("session", session_id)
|
||||
return await self._store.runs.list_runs(session_id)
|
||||
|
||||
async def cancel_run(self, *, run_id: str, user_id: str | None, is_admin: bool = False) -> dict[str, Any]:
|
||||
self._require_enabled()
|
||||
if not user_id:
|
||||
raise MafNotFoundError("run", run_id)
|
||||
|
||||
result = await self._store.cancel_run_atomically(run_id=run_id, owner_user_id=user_id)
|
||||
if result is not None:
|
||||
return result
|
||||
|
||||
# Classify the miss: missing vs wrong-owner.
|
||||
run = await self._store.runs.get_run(run_id)
|
||||
if run is None:
|
||||
raise MafNotFoundError("run", run_id)
|
||||
if is_admin:
|
||||
raise MafForbiddenError("run", run_id)
|
||||
raise MafNotFoundError("run", run_id)
|
||||
|
||||
# ── events ─────────────────────────────────────────────────────────────
|
||||
|
||||
async def append_event(
|
||||
self,
|
||||
*,
|
||||
run_id: str,
|
||||
user_id: str | None,
|
||||
event_type: str,
|
||||
agent_id: str | None = None,
|
||||
turn_index: int | None = None,
|
||||
payload: dict[str, Any] | None = None,
|
||||
is_admin: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Append an event to a run's stream (internal / executor only).
|
||||
|
||||
There is **no** public HTTP write endpoint for events — Phase-1 audit
|
||||
integrity requires that only the backend Workflow executor (Phase 2+)
|
||||
call this method. Frontend联调 mocks belong in tests / scripts, not in
|
||||
a production-reachable route.
|
||||
"""
|
||||
self._require_enabled()
|
||||
# Owner-only write: an admin cannot forge events into another user's run.
|
||||
run = await self._store.runs.get_run(run_id)
|
||||
if run is None:
|
||||
raise MafNotFoundError("run", run_id)
|
||||
scope = self._write_scope_user(user_id, is_admin)
|
||||
session = await self._store.sessions.get_session(run["session_id"], user_id=scope)
|
||||
if session is None:
|
||||
if is_admin and await self._store.sessions.get_session(run["session_id"], user_id=None) is not None:
|
||||
raise MafForbiddenError("run", run_id)
|
||||
raise MafNotFoundError("run", run_id)
|
||||
return await self._store.events.append_event(
|
||||
session_id=run["session_id"],
|
||||
run_id=run_id,
|
||||
event_type=event_type,
|
||||
agent_id=agent_id,
|
||||
turn_index=turn_index,
|
||||
payload=payload,
|
||||
)
|
||||
|
||||
async def list_events(
|
||||
self, *, run_id: str, user_id: str | None, after_seq: int = 0, limit: int = 1000, is_admin: bool = False
|
||||
) -> tuple[list[dict[str, Any]], int]:
|
||||
# get_run enforces owner read-scope (raises MafNotFoundError if out of scope).
|
||||
await self.get_run(run_id=run_id, user_id=user_id, is_admin=is_admin)
|
||||
events = await self._store.events.list_events(run_id, after_seq=after_seq, limit=limit)
|
||||
latest = await self._store.events.latest_seq(run_id)
|
||||
return events, latest
|
||||
|
||||
# ── actions ────────────────────────────────────────────────────────────
|
||||
|
||||
async def list_actions(
|
||||
self, *, run_id: str, user_id: str | None, is_admin: bool = False
|
||||
) -> list[dict[str, Any]]:
|
||||
run = await self.get_run(run_id=run_id, user_id=user_id, is_admin=is_admin)
|
||||
return await self._store.actions.list_actions(run_id=run["id"])
|
||||
|
||||
async def get_action(self, *, action_id: str, user_id: str | None, is_admin: bool = False) -> dict[str, Any]:
|
||||
action = await self._store.actions.get_action(action_id)
|
||||
if action is None:
|
||||
raise MafNotFoundError("action", action_id)
|
||||
scope = self._read_scope_user(user_id, is_admin)
|
||||
session = await self._store.sessions.get_session(action["session_id"], user_id=scope)
|
||||
if session is None:
|
||||
raise MafNotFoundError("action", action_id)
|
||||
return action
|
||||
|
||||
# ── approvals ──────────────────────────────────────────────────────────
|
||||
|
||||
async def list_approvals(
|
||||
self, *, run_id: str, user_id: str | None, is_admin: bool = False
|
||||
) -> list[dict[str, Any]]:
|
||||
run = await self.get_run(run_id=run_id, user_id=user_id, is_admin=is_admin)
|
||||
return await self._store.approvals.list_approvals(run_id=run["id"])
|
||||
|
||||
async def decide_approval(
|
||||
self,
|
||||
*,
|
||||
approval_id: str,
|
||||
decision: str,
|
||||
user_id: str | None,
|
||||
is_admin: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
self._require_enabled()
|
||||
approval = await self._store.approvals.get_approval(approval_id)
|
||||
if approval is None:
|
||||
raise MafNotFoundError("approval", approval_id)
|
||||
# Owner-only write: an admin cannot decide another user's approval.
|
||||
scope = self._write_scope_user(user_id, is_admin)
|
||||
session = await self._store.sessions.get_session(approval["session_id"], user_id=scope)
|
||||
if session is None:
|
||||
if is_admin and await self._store.sessions.get_session(approval["session_id"], user_id=None) is not None:
|
||||
raise MafForbiddenError("approval", approval_id)
|
||||
raise MafNotFoundError("approval", approval_id)
|
||||
try:
|
||||
updated = await self._store.approvals.decide(approval_id, decision=decision, decided_by=user_id)
|
||||
except ValueError as exc:
|
||||
raise MafConflictError(str(exc)) from exc
|
||||
if updated is None:
|
||||
raise MafNotFoundError("approval", approval_id)
|
||||
return updated
|
||||
Reference in new issue
Block a user