代码提交

This commit is contained in:
董宏凯 committed 2026-08-03 19:27:54 +08:00
1 parent d93cc62806
commit ddf83f7728
25 files changed
+4086 -424

No files matched your search

@@ -20,7 +20,7 @@ from __future__ import annotations
import re
from typing import Literal
from pydantic import BaseModel, Field, field_validator
from pydantic import BaseModel, Field, field_validator, model_validator
# ── shared enums (config + API schemas) ───────────────────────────────────
@@ -108,10 +108,25 @@ class MafBusinessRoute(BaseModel):
value = str(agent_id).strip()
if not value or len(value) > 64:
raise ValueError("seat_agent_ids must contain non-empty agent ids")
if value not in normalized:
normalized.append(value)
if value in normalized:
raise ValueError("seat_agent_ids must not contain duplicates")
normalized.append(value)
return normalized
@field_validator("manager_agent_id", mode="before")
@classmethod
def _normalize_manager_agent_id(cls, value: object) -> str:
normalized = str(value or "").strip()
if not normalized:
raise ValueError("manager_agent_id must be non-empty")
return normalized
@model_validator(mode="after")
def _validate_manager_not_seat(self) -> MafBusinessRoute:
if self.manager_agent_id in self.seat_agent_ids:
raise ValueError("manager_agent_id must not appear in seat_agent_ids")
return self
class MafRoundtableConfig(BaseModel):
"""Microsoft Agent Framework 多智能体会商实验功能开关。
@@ -191,6 +206,73 @@ class MafRoundtableConfig(BaseModel):
le=7200,
description="外部业务目标写入租约有效期(秒);过期运行中的动作转 unknown。",
)
conversation_event_backend: Literal["memory"] = Field(
default="memory",
description="会商 SSE 事件广播后端;当前仅支持 memory(单 worker)。",
)
require_single_worker_for_conversation_sse: bool = Field(
default=True,
description="当 backend=memory 且检测到多 worker 时,禁止会商 SSE 写入入口。",
)
background_reconcile_interval_seconds: int = Field(
default=10,
ge=5,
le=60,
description="后台自动 reconcile 扫描间隔(秒);补偿投影失败的审计事件。",
)
@field_validator("default_manager_agent_id", mode="before")
@classmethod
def _normalize_default_manager_agent_id(cls, value: object) -> str | None:
if value is None:
return None
normalized = str(value).strip()
if not normalized:
raise ValueError("default_manager_agent_id must be non-empty when provided")
return normalized
@field_validator("default_seat_agent_ids")
@classmethod
def _validate_default_seat_agent_ids(cls, ids: list[str]) -> list[str]:
normalized: list[str] = []
for agent_id in ids:
value = str(agent_id).strip()
if not value or len(value) > 64:
raise ValueError("default_seat_agent_ids must contain non-empty agent ids")
if value in normalized:
raise ValueError("default_seat_agent_ids must not contain duplicates")
normalized.append(value)
return normalized
@field_validator("business_routes")
@classmethod
def _validate_business_route_codes(
cls, routes: dict[str, MafBusinessRoute]
) -> dict[str, MafBusinessRoute]:
code_pattern = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$")
normalized_routes: dict[str, MafBusinessRoute] = {}
for code, route in routes.items():
normalized_code = str(code).strip()
if not code_pattern.fullmatch(normalized_code):
raise ValueError(
"business route code must match ^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$"
)
if normalized_code in normalized_routes:
raise ValueError("business route codes must be unique after trimming")
normalized_routes[normalized_code] = route
return normalized_routes
@model_validator(mode="after")
def _validate_routes(self) -> MafRoundtableConfig:
if self.default_manager_agent_id and self.default_manager_agent_id in self.default_seat_agent_ids:
raise ValueError("default manager_agent_id must not appear in default_seat_agent_ids")
if len(self.default_seat_agent_ids) > self.max_seats_per_run:
raise ValueError("default_seat_agent_ids exceeds max_seats_per_run")
for code, route in self.business_routes.items():
if len(route.seat_agent_ids) > self.max_seats_per_run:
raise ValueError(f"business route {code!r} exceeds max_seats_per_run")
return self
__all__ = [
@@ -99,6 +99,49 @@ class MafParticipantRepository:
await session.commit()
return [_to_dict(r) for r in new_rows]
async def ensure_participants(
self, session_id: str, participants: list[dict[str, Any]]
) -> list[dict[str, Any]]:
"""Insert missing participants without replacing existing threads.
MAF Stage 3 initially persists only the manager participant. After
the manager validates its dispatch plan, selected seats are added here
so unselected seats never receive a thread or execution slot.
"""
async with self._sf() as session:
existing_rows = (
await session.execute(
select(MafRoundtableParticipantRow).where(
MafRoundtableParticipantRow.session_id == session_id
)
)
).scalars().all()
existing = {row.agent_id: row for row in existing_rows}
now = _now()
for participant in participants:
agent_id = str(participant.get("agent_id") or "").strip()
if not agent_id or agent_id in existing:
continue
row = MafRoundtableParticipantRow(
id=uuid4().hex,
session_id=session_id,
agent_id=agent_id,
display_name=str(participant.get("display_name") or ""),
role=str(participant.get("role") or "seat"),
sort_order=int(participant.get("sort_order", 0)),
thread_id=None,
sandbox_id=None,
status="idle",
last_turn_index=None,
capability_snapshot_json=participant.get("capability_snapshot"),
created_at=now,
updated_at=now,
)
session.add(row)
existing[agent_id] = row
await session.commit()
return [_to_dict(existing[agent_id]) for agent_id in existing]
async def update_participant_status(
self, session_id: str, agent_id: str, *, status: str, last_turn_index: int | None = None
) -> dict[str, Any] | None:
@@ -867,6 +867,77 @@ class MafRoundtableStore:
await db.flush()
return {"seq": next_seq, "message_id": message_id, "event_id": event_id}
async def append_conversation_events_idempotently(
self,
db: AsyncSession,
*,
conversation: MafRoundtableConversationRow,
items: list[dict[str, Any]],
) -> int:
"""Batch-atomic idempotent write of multiple conversation events.
MUST be called inside an existing transaction (``db.begin()``). The
caller is responsible for locking the conversation row.
Each item in ``items`` must have:
- ``event_type``: str
- ``event_data``: dict
- ``source_event_id``: str | None
Items with a ``source_event_id`` that already exists for this
conversation are silently skipped (dedup). Items without a
``source_event_id`` are always written.
All new items share one transaction: if any insert fails, the entire
batch rolls back. Returns the count of **newly inserted** events.
"""
if not items:
return 0
now = _now()
existing_sources: set[str] = set()
source_ids_to_check = [
item["source_event_id"]
for item in items
if item.get("source_event_id") is not None
]
if source_ids_to_check:
rows = (
await db.execute(
select(MafRoundtableConversationEventRow.source_event_id).where(
MafRoundtableConversationEventRow.conversation_id == conversation.id,
MafRoundtableConversationEventRow.source_event_id.in_(source_ids_to_check),
)
)
).scalars().all()
existing_sources = {str(r) for r in rows if r is not None}
written = 0
for item in items:
src_id = item.get("source_event_id")
if src_id is not None and src_id in existing_sources:
continue
next_seq = int(conversation.last_stream_seq or 0) + 1
conversation.last_stream_seq = next_seq
db.add(MafRoundtableConversationEventRow(
id=uuid4().hex,
conversation_id=conversation.id,
seq=next_seq,
run_id=item.get("run_id"),
source_event_id=src_id,
event_type=item["event_type"],
data_json=item.get("event_data"),
created_at=now,
))
existing_sources.add(src_id) if src_id else None
written += 1
if written:
await db.flush()
return written
# ── V2 conversation aggregation: atomic send-message + run launch ───────
async def send_message_and_start_run(