feat(maf): conversation-driven MAF roundtable (R1/R2) + server-owned stage-3 dispatch

Backend:
- Conversation API at /api/maf-roundtable/conversations: create/list/detail,
  paginated messages, atomic send+run start, owner-only isolation,
  admin read-only diagnostic access
- SSE real-time event stream (GET /conversations/{id}/stream) backed by
  ConversationEventHub + conversation_events store; multi-worker deployment doc
- Deterministic server-owned stage-3 dispatch contracts (dispatch_contracts.py):
  routing resolved from trusted MAF deployment config instead of manager-chosen
  agent ids; config.yaml keeps stage-3 routing deployment-owned
  (default_manager_agent_id / seat ids / business_routes / max_seats_per_run)
- Conversation persistence (conversations/messages stores) + v2 migration script
- Tests: conversations, conversation stream, migration, phase3 conversation dispatch

Frontend:
- Vitest test infra for MAF (vitest.maf.config.ts + test:maf script) with
  component tests for ApprovalCard/RunHeader/SessionsPage and use-maf-events
- Session form lib, flow-graph dialog / run-detail / sessions page updates,
  routes and nav tweaks
- Docs: R0 legacy interaction baseline mapping, updated implementation plan

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
董宏凯andCursor committed 2026-08-03 12:09:47 +08:00
1 parent df408831e5
commit 99642fca6c
46 files changed
+6358 -1306

No files matched your search

@@ -0,0 +1,268 @@
"""Deterministic, server-owned contracts for MAF Stage 3 dispatch.
The manager may describe work, but it does not get to choose arbitrary agent
ids, threads, tools, or capabilities. Routing is resolved from the trusted
MAF deployment configuration and the small, validated task-context allowlist.
This module is intentionally independent of the MAF SDK so the policy can be
tested with a weak/fake model and before any workflow is launched.
"""
from __future__ import annotations
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field, model_validator
from deerflow.config.maf_roundtable_config import MafMode
MafIntentType = Literal[
"direct_answer",
"clarification",
"single_seat",
"parallel_consultation",
"chain_consultation",
"tool_write",
]
class DispatchConfigurationError(RuntimeError):
"""The deployment has not supplied a complete trusted route."""
class InvalidDispatchPlanError(ValueError):
"""A proposed or constructed plan violates the dispatch contract."""
class MafIntentDecision(BaseModel):
model_config = ConfigDict(extra="forbid")
intent_type: MafIntentType
confidence: float = Field(ge=0.0, le=1.0)
reason_code: str = Field(min_length=1, max_length=64)
clarification_prompt: str | None = Field(default=None, max_length=1000)
@model_validator(mode="after")
def _clarification_shape(self) -> MafIntentDecision:
if self.intent_type == "clarification" and not self.clarification_prompt:
raise ValueError("clarification intent requires clarification_prompt")
if self.intent_type != "clarification" and self.clarification_prompt is not None:
raise ValueError("only clarification intent may include clarification_prompt")
return self
class MafDispatchAssignment(BaseModel):
model_config = ConfigDict(extra="forbid")
agent_id: str = Field(min_length=1, max_length=64)
role: Literal["seat"] = "seat"
sort_order: int = Field(ge=1, le=64)
class MafDispatchPlan(BaseModel):
"""Validated plan containing only server-selected participants."""
model_config = ConfigDict(extra="forbid")
manager_agent_id: str = Field(min_length=1, max_length=64)
seat_agent_ids: list[str] = Field(default_factory=list, max_length=64)
assignments: list[MafDispatchAssignment] = Field(default_factory=list, max_length=64)
mode: MafMode = "structured"
intent_type: MafIntentType
business_code: str | None = Field(default=None, max_length=255)
max_rounds: int = Field(ge=1, le=64)
@model_validator(mode="after")
def _validate_shape(self) -> MafDispatchPlan:
if self.manager_agent_id in self.seat_agent_ids:
raise ValueError("manager agent cannot also be a seat")
if len(set(self.seat_agent_ids)) != len(self.seat_agent_ids):
raise ValueError("duplicate seat agent")
assignment_ids = [assignment.agent_id for assignment in self.assignments]
if assignment_ids != self.seat_agent_ids:
raise ValueError("assignments must exactly match seat_agent_ids")
if [a.sort_order for a in self.assignments] != list(range(1, len(self.assignments) + 1)):
raise ValueError("assignments must have contiguous sort_order")
if self.intent_type == "clarification":
raise ValueError("clarification cannot be dispatched")
if self.intent_type != "direct_answer" and not self.seat_agent_ids:
raise ValueError("this intent requires at least one configured seat")
return self
def resolve_intent(content: str, task_context: dict[str, Any] | None = None) -> MafIntentDecision:
"""Resolve the common Stage 3 intents deterministically.
A production model can later supply a *description* for the intent, but
this policy remains the final validator. The fallback deliberately uses
conservative keywords and never extracts agent/tool ids from user text.
"""
text = " ".join(str(content or "").strip().split())
lowered = text.casefold()
if len(text) < 4 or lowered in {"?", "?", "不清楚", "不明确", "再说清楚"}:
return MafIntentDecision(
intent_type="clarification",
confidence=0.99,
reason_code="insufficient_task_detail",
clarification_prompt="请补充希望解决的具体问题、目标和必要的业务背景。",
)
write_markers = (
"写入", "发布", "创建工单", "更新任务", "提交", "删除", "write", "publish", "create ticket",
)
chain_markers = ("业务链", "链式", "逐阶段", "先…再", "先...再", "chain")
parallel_markers = ("多专家", "多角度", "并行", "同时分析", "比较", "parallel", "multi-agent")
single_markers = ("请某个专家", "单个席位", "单专家", "single seat", "指定专家")
if any(marker in lowered for marker in write_markers):
intent_type: MafIntentType = "tool_write"
reason_code = "write_request"
elif any(marker in lowered for marker in chain_markers):
intent_type = "chain_consultation"
reason_code = "chain_request"
elif any(marker in lowered for marker in parallel_markers):
intent_type = "parallel_consultation"
reason_code = "parallel_request"
elif any(marker in lowered for marker in single_markers):
intent_type = "single_seat"
reason_code = "single_seat_request"
else:
intent_type = "direct_answer"
reason_code = "default_direct_answer"
return MafIntentDecision(
intent_type=intent_type,
confidence=0.72 if task_context else 0.68,
reason_code=reason_code,
)
def _read(value: Any, name: str, default: Any = None) -> Any:
if isinstance(value, dict):
return value.get(name, default)
return getattr(value, name, default)
class MafDispatchCatalog:
"""Resolve routes from deployment config, never from a request body."""
def __init__(self, maf_config: Any) -> None:
self._config = maf_config
def _route(self, business_code: str | None) -> tuple[str | None, list[str], MafMode | None]:
routes = _read(self._config, "business_routes", {}) or {}
if business_code:
route = routes.get(business_code)
if route is None:
# A supplied business code must match an explicitly configured
# route. Falling back here would silently cross business
# boundaries.
return None, [], None
return (
_read(route, "manager_agent_id"),
list(_read(route, "seat_agent_ids", []) or []),
_read(route, "mode"),
)
return (
_read(self._config, "default_manager_agent_id"),
list(_read(self._config, "default_seat_agent_ids", []) or []),
None,
)
def build_plan(
self,
*,
intent: MafIntentDecision,
task_context: dict[str, Any] | None,
) -> MafDispatchPlan:
business_code = str((task_context or {}).get("business_code") or "").strip() or None
manager_id, route_seats, route_mode = self._route(business_code)
if not manager_id:
raise DispatchConfigurationError(
"no trusted MAF manager route is configured for this conversation"
)
# The server owns the route. Intent only changes how many configured
# seats participate; it never adds an id.
if intent.intent_type in {"single_seat", "tool_write", "direct_answer"}:
seat_ids = route_seats[:1]
else:
seat_ids = route_seats[:]
max_seats = int(_read(self._config, "max_seats_per_run", 16) or 16)
if len(seat_ids) > max_seats:
raise DispatchConfigurationError("configured MAF route exceeds max_seats_per_run")
try:
plan = MafDispatchPlan(
manager_agent_id=str(manager_id).strip(),
seat_agent_ids=[str(agent_id).strip() for agent_id in seat_ids],
assignments=[
MafDispatchAssignment(agent_id=str(agent_id).strip(), sort_order=index)
for index, agent_id in enumerate(seat_ids, start=1)
],
mode=route_mode or _read(self._config, "default_mode", "structured"),
intent_type=intent.intent_type,
business_code=business_code,
max_rounds=int(_read(self._config, "default_max_rounds", 8) or 8),
)
except (TypeError, ValueError) as exc:
raise DispatchConfigurationError("invalid trusted MAF dispatch route") from exc
trusted_ids = {str(manager_id), *(str(agent_id) for agent_id in route_seats)}
validate_dispatch_plan(plan, trusted_agent_ids=trusted_ids, max_seats=max_seats)
return plan
@staticmethod
def participants(plan: MafDispatchPlan) -> list[dict[str, Any]]:
"""Return persistence records; thread ids are intentionally absent."""
return [
{
"agent_id": plan.manager_agent_id,
"role": "manager",
"sort_order": 0,
"display_name": "",
},
*[
{
"agent_id": assignment.agent_id,
"role": "seat",
"sort_order": assignment.sort_order,
"display_name": "",
}
for assignment in plan.assignments
],
]
def validate_dispatch_plan(
plan: MafDispatchPlan,
*,
trusted_agent_ids: set[str],
max_seats: int,
) -> None:
"""Final allowlist check used before persistence and workflow launch."""
if plan.manager_agent_id not in trusted_agent_ids:
raise InvalidDispatchPlanError("manager agent is outside the trusted route")
if len(plan.seat_agent_ids) > max_seats:
raise InvalidDispatchPlanError("dispatch plan exceeds the seat limit")
if any(agent_id not in trusted_agent_ids for agent_id in plan.seat_agent_ids):
raise InvalidDispatchPlanError("seat agent is outside the trusted route")
if len(set(plan.seat_agent_ids)) != len(plan.seat_agent_ids):
raise InvalidDispatchPlanError("dispatch plan contains duplicate seats")
if plan.manager_agent_id in plan.seat_agent_ids:
raise InvalidDispatchPlanError("manager cannot be dispatched as a seat")
__all__ = [
"DispatchConfigurationError",
"InvalidDispatchPlanError",
"MafDispatchAssignment",
"MafDispatchPlan",
"MafDispatchCatalog",
"MafIntentDecision",
"MafIntentType",
"resolve_intent",
"validate_dispatch_plan",
]