代码提交
This commit is contained in:
1 parent
d93cc62806
commit
ddf83f7728
25 files changed
+4086
-424
No files matched your search
@@ -14,6 +14,7 @@ Group-chat still uses CoordinatorExecutor for speaker selection.
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
@@ -25,6 +26,12 @@ from app.maf_roundtable.action_coordinator import (
|
||||
tool_needs_approval,
|
||||
)
|
||||
from app.maf_roundtable.context_builder import build_manager_synthesis_input
|
||||
from app.maf_roundtable.dispatch_contracts import (
|
||||
InvalidDispatchPlanError,
|
||||
MafDispatchCandidateSet,
|
||||
MafDispatchCatalog,
|
||||
MafDispatchPlan,
|
||||
)
|
||||
from app.maf_roundtable.fact_ledger import (
|
||||
confirm_candidates,
|
||||
empty_ledger,
|
||||
@@ -76,6 +83,8 @@ class RoundtableState:
|
||||
schema_repair_enabled: bool = True,
|
||||
intent_type: str | None = None,
|
||||
dispatch_plan: dict[str, Any] | None = None,
|
||||
candidate_seat_agent_ids: list[str] | None = None,
|
||||
dispatch_contract_enabled: bool | None = None,
|
||||
) -> None:
|
||||
self.session_id = session_id
|
||||
self.run_id = run_id
|
||||
@@ -96,6 +105,18 @@ class RoundtableState:
|
||||
# id from manager model output.
|
||||
self.intent_type = intent_type
|
||||
self.dispatch_plan = dispatch_plan
|
||||
self.dispatch_contract_enabled = (
|
||||
bool(dispatch_plan is not None or intent_type is not None)
|
||||
if dispatch_contract_enabled is None
|
||||
else bool(dispatch_contract_enabled)
|
||||
)
|
||||
plan_seats = list((dispatch_plan or {}).get("seat_agent_ids") or [])
|
||||
self.candidate_seat_agent_ids = list(
|
||||
(dispatch_plan or {}).get("candidate_seat_agent_ids")
|
||||
or candidate_seat_agent_ids
|
||||
or seat_agent_ids
|
||||
)
|
||||
self.selected_seat_agent_ids: list[str] | None = plan_seats or None
|
||||
|
||||
self.current_round = 0
|
||||
self.turn_results: list[dict[str, Any]] = []
|
||||
@@ -137,6 +158,9 @@ class RoundtableState:
|
||||
"schema_repair_enabled": self.schema_repair_enabled,
|
||||
"intent_type": self.intent_type,
|
||||
"dispatch_plan": self.dispatch_plan,
|
||||
"dispatch_contract_enabled": self.dispatch_contract_enabled,
|
||||
"candidate_seat_agent_ids": list(self.candidate_seat_agent_ids),
|
||||
"selected_seat_agent_ids": self.selected_seat_agent_ids,
|
||||
"current_round": self.current_round,
|
||||
"turn_results": self.turn_results,
|
||||
"fact_ledger": self.fact_ledger,
|
||||
@@ -170,6 +194,8 @@ class RoundtableState:
|
||||
schema_repair_enabled=bool(d.get("schema_repair_enabled", True)),
|
||||
intent_type=d.get("intent_type"),
|
||||
dispatch_plan=d.get("dispatch_plan"),
|
||||
candidate_seat_agent_ids=d.get("candidate_seat_agent_ids"),
|
||||
dispatch_contract_enabled=d.get("dispatch_contract_enabled"),
|
||||
)
|
||||
state.current_round = d.get("current_round", 0)
|
||||
state.turn_results = d.get("turn_results", [])
|
||||
@@ -186,62 +212,59 @@ class RoundtableState:
|
||||
state.stage = d.get("stage") or "planning"
|
||||
state.partial_failure = bool(d.get("partial_failure", False))
|
||||
state.cross_review_result = d.get("cross_review_result")
|
||||
state.candidate_seat_agent_ids = list(
|
||||
d.get("candidate_seat_agent_ids") or state.candidate_seat_agent_ids
|
||||
)
|
||||
selected = d.get("selected_seat_agent_ids")
|
||||
state.selected_seat_agent_ids = list(selected) if selected is not None else None
|
||||
state.dispatch_contract_enabled = bool(
|
||||
d.get("dispatch_contract_enabled", state.dispatch_contract_enabled)
|
||||
)
|
||||
return state
|
||||
|
||||
|
||||
# ── Planner (structured) ────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class PlannerExecutor(Executor):
|
||||
"""Produce per-seat assignments for the structured expert stage."""
|
||||
class ManagerAnswerExecutor(Executor):
|
||||
"""Manager-only topology for ordinary direct answers."""
|
||||
|
||||
def __init__(self, adapter: Any, state: RoundtableState) -> None:
|
||||
super().__init__(id="planner")
|
||||
super().__init__(id="manager_answer")
|
||||
self._adapter = adapter
|
||||
self._state = state
|
||||
|
||||
@handler(input=Any, output=dict)
|
||||
@handler(input=Any, workflow_output=dict)
|
||||
async def handle(self, message: Any, ctx: WorkflowContext) -> None:
|
||||
if self._state.is_completed("planner"):
|
||||
await ctx.send_message({"decision": "parallel_seats", "agents": self._state.seat_agent_ids, "replayed": True})
|
||||
if self._state.is_completed("manager_answer") and self._state.final_result is not None:
|
||||
self._state.status = "completed"
|
||||
await ctx.yield_output({"final_result": self._state.final_result, "replayed": True})
|
||||
return
|
||||
|
||||
self._state.stage = "planning"
|
||||
self._state.current_round = max(self._state.current_round, 1)
|
||||
|
||||
assignments = {
|
||||
aid: {
|
||||
"role": f"专家席位 {aid}",
|
||||
"instruction": (
|
||||
f"请作为席位 {aid} 独立分析任务,可使用你的工具与技能。"
|
||||
f"{seat_output_instruction()}"
|
||||
),
|
||||
manager_id = self._state.manager_agent_id or ""
|
||||
thread_id = self._state.thread_map.get(manager_id, "")
|
||||
if not thread_id:
|
||||
self._state.status = "failed"
|
||||
self._state.final_result = {
|
||||
"content": "MAF manager thread is unavailable",
|
||||
"agent_id": manager_id,
|
||||
"error_code": "manager_thread_unavailable",
|
||||
}
|
||||
for aid in self._state.seat_agent_ids
|
||||
}
|
||||
|
||||
manager_id = self._state.manager_agent_id
|
||||
thread_id = self._state.thread_map.get(manager_id or "", "")
|
||||
if manager_id and thread_id:
|
||||
else:
|
||||
try:
|
||||
plan_prompt = (
|
||||
f"任务:{self._state.task_text}\n"
|
||||
f"参与席位:{', '.join(self._state.seat_agent_ids)}\n"
|
||||
"请为每个席位给出简短分工说明。可用纯文本;系统会据此填充各席位指令。"
|
||||
)
|
||||
response = await asyncio.wait_for(
|
||||
self._adapter.run_seat_turn(
|
||||
session_id=self._state.session_id,
|
||||
run_id=self._state.run_id,
|
||||
agent_id=manager_id,
|
||||
turn_index=0,
|
||||
execution_stage="planner",
|
||||
message=plan_prompt,
|
||||
execution_stage="direct_answer",
|
||||
message=self._state.task_text,
|
||||
thread_id=thread_id,
|
||||
model_name=self._state.model_name,
|
||||
reasoning_effort=self._state.reasoning_effort,
|
||||
task_text=plan_prompt,
|
||||
stage_instruction="任务规划与分工",
|
||||
task_text=self._state.task_text,
|
||||
stage_instruction="Answer the user directly; do not delegate to expert seats",
|
||||
fact_ledger=self._state.fact_ledger,
|
||||
capability_snapshot=self._state.capability_snapshot,
|
||||
write_policy=self._state.write_policy,
|
||||
@@ -249,31 +272,247 @@ class PlannerExecutor(Executor):
|
||||
),
|
||||
timeout=self._state.seat_timeout_seconds,
|
||||
)
|
||||
plan_text = (response.content or "").strip()
|
||||
if plan_text:
|
||||
for aid in self._state.seat_agent_ids:
|
||||
assignments[aid]["instruction"] = (
|
||||
f"{plan_text[:1500]}\n\n你的席位 id={aid}。\n{seat_output_instruction()}"
|
||||
)
|
||||
self._state.plan = {"source": "manager", "text": plan_text, "assignments": assignments}
|
||||
if response.error:
|
||||
self._state.status = "failed"
|
||||
else:
|
||||
self._state.plan = {"source": "deterministic", "assignments": assignments}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("planner manager turn failed (%s); using deterministic plan", type(exc).__name__)
|
||||
self._state.plan = {"source": "deterministic", "assignments": assignments}
|
||||
self._state.status = "completed"
|
||||
self._state.final_result = {
|
||||
"content": response.content,
|
||||
"agent_id": manager_id,
|
||||
"error": response.error,
|
||||
"quality_decision": "accept" if not response.error else "controlled_gap",
|
||||
}
|
||||
except Exception as exc: # noqa: BLE001 - runner persists a safe failure
|
||||
self._state.status = "failed"
|
||||
self._state.final_result = {
|
||||
"content": "MAF manager answer failed",
|
||||
"agent_id": manager_id,
|
||||
"error_code": type(exc).__name__,
|
||||
}
|
||||
|
||||
self._state.stage = "done"
|
||||
self._state.mark_completed("manager_answer")
|
||||
dispatch_plan = MafDispatchPlan.model_validate(self._state.dispatch_plan or {
|
||||
"manager_agent_id": manager_id,
|
||||
"seat_agent_ids": [],
|
||||
"assignments": [],
|
||||
"intent_type": "direct_answer",
|
||||
"max_rounds": self._state.max_rounds,
|
||||
"candidate_seat_agent_ids": list(self._state.candidate_seat_agent_ids),
|
||||
"execution_mode": "manager_only",
|
||||
"convergence_path": ["manager answer"],
|
||||
"reason": "direct answer uses manager only",
|
||||
"source": "server",
|
||||
})
|
||||
self._state.dispatch_plan = dispatch_plan.model_dump(mode="json")
|
||||
store = getattr(getattr(self._adapter, "_service", None), "store", None)
|
||||
if store is not None:
|
||||
await store.runs.update_run(
|
||||
self._state.run_id,
|
||||
{"maf_checkpoint": self._state.to_dict()},
|
||||
)
|
||||
if not self._state.dispatch_contract_enabled:
|
||||
await self._adapter._emit_critical(self._state.run_id, {
|
||||
"event_type": "manager.dispatch",
|
||||
"agent_id": manager_id,
|
||||
"turn_index": 0,
|
||||
"payload": {
|
||||
"intent_type": dispatch_plan.intent_type,
|
||||
"execution_mode": dispatch_plan.execution_mode,
|
||||
"convergence_path": list(dispatch_plan.convergence_path),
|
||||
"selected_seat_agent_ids": [],
|
||||
"assignments": [],
|
||||
"reason": dispatch_plan.reason,
|
||||
"source": dispatch_plan.source,
|
||||
},
|
||||
})
|
||||
from app.maf_roundtable.event_normalizer import make_run_completed
|
||||
|
||||
await self._adapter._emit_critical(
|
||||
self._state.run_id,
|
||||
make_run_completed(manager_id, 1, {"manager_only": True}),
|
||||
)
|
||||
await ctx.yield_output({"final_result": self._state.final_result})
|
||||
|
||||
|
||||
class ManagerDispatchExecutor(Executor):
|
||||
"""Understand intent and emit one server-validated dispatch decision."""
|
||||
|
||||
def __init__(
|
||||
self, adapter: Any, state: RoundtableState, *, executor_id: str = "manager_dispatch"
|
||||
) -> None:
|
||||
super().__init__(id=executor_id)
|
||||
self._adapter = adapter
|
||||
self._state = state
|
||||
self._node_id = executor_id
|
||||
|
||||
def _dispatch_decision(self) -> str:
|
||||
plan = self._state.dispatch_plan or {}
|
||||
if self._state.intent_type == "clarification" or not plan:
|
||||
return "clarification"
|
||||
if plan.get("execution_mode") == "manager_only":
|
||||
return "manager_only"
|
||||
if plan.get("mode") == "group_chat" or plan.get("execution_mode") == "group_chat":
|
||||
return "group_chat"
|
||||
return "selected_seats"
|
||||
|
||||
@handler(input=Any, output=dict)
|
||||
async def handle(self, message: Any, ctx: WorkflowContext) -> None:
|
||||
if self._state.is_completed(self._node_id):
|
||||
await ctx.send_message({
|
||||
"decision": self._dispatch_decision(),
|
||||
"agents": list(self._state.selected_seat_agent_ids or []),
|
||||
"execution_mode": (self._state.dispatch_plan or {}).get("execution_mode"),
|
||||
"replayed": True,
|
||||
})
|
||||
return
|
||||
|
||||
self._state.stage = "planning"
|
||||
|
||||
# Legacy MAF roundtable runs do not carry the V2 conversation dispatch
|
||||
# contract. Keep their planner semantics isolated from the new MAF
|
||||
# conversation workflow; in particular, old seat-only runs may have no
|
||||
# manager at all.
|
||||
if not self._state.dispatch_contract_enabled:
|
||||
self._state.current_round = max(self._state.current_round, 1)
|
||||
await _run_legacy_planner(self, ctx)
|
||||
return
|
||||
|
||||
# The manager plan is a strict JSON contract. Legacy free-text
|
||||
# planning is isolated in _run_legacy_planner; new Stage 3 runs
|
||||
# always return through this verifier.
|
||||
await _resolve_manager_dispatch(self, ctx)
|
||||
return
|
||||
|
||||
|
||||
async def _run_legacy_planner(executor: ManagerDispatchExecutor, ctx: WorkflowContext) -> None:
|
||||
"""Keep the pre-V2 free-text planner isolated from new conversations."""
|
||||
state = executor._state
|
||||
if state.is_completed(executor._node_id):
|
||||
await ctx.send_message({"decision": "parallel_seats", "agents": list(state.seat_agent_ids), "replayed": True})
|
||||
return
|
||||
assignments = {
|
||||
agent_id: {
|
||||
"role": f"Expert seat {agent_id}",
|
||||
"instruction": f"Independently analyze the task. {seat_output_instruction()}",
|
||||
}
|
||||
for agent_id in state.seat_agent_ids
|
||||
}
|
||||
manager_id = state.manager_agent_id
|
||||
thread_id = state.thread_map.get(manager_id or "", "")
|
||||
if manager_id and thread_id:
|
||||
try:
|
||||
response = await asyncio.wait_for(
|
||||
executor._adapter.run_seat_turn(
|
||||
session_id=state.session_id,
|
||||
run_id=state.run_id,
|
||||
agent_id=manager_id,
|
||||
turn_index=0,
|
||||
execution_stage="planner",
|
||||
message=state.task_text,
|
||||
thread_id=thread_id,
|
||||
model_name=state.model_name,
|
||||
reasoning_effort=state.reasoning_effort,
|
||||
task_text=state.task_text,
|
||||
stage_instruction="Produce a concise assignment for each configured expert seat.",
|
||||
fact_ledger=state.fact_ledger,
|
||||
capability_snapshot=state.capability_snapshot,
|
||||
write_policy=state.write_policy,
|
||||
wait_timeout_seconds=state.seat_timeout_seconds,
|
||||
),
|
||||
timeout=state.seat_timeout_seconds,
|
||||
)
|
||||
plan_text = (response.content or "").strip()
|
||||
if plan_text:
|
||||
for agent_id in state.seat_agent_ids:
|
||||
assignments[agent_id]["instruction"] = f"{plan_text[:1500]}\n\nSeat id: {agent_id}.\n{seat_output_instruction()}"
|
||||
state.plan = {"source": "manager", "text": plan_text, "assignments": assignments}
|
||||
else:
|
||||
state.plan = {"source": "deterministic", "assignments": assignments}
|
||||
except Exception as exc: # noqa: BLE001 - legacy path deliberately degrades
|
||||
logger.warning("legacy planner failed (%s); using deterministic plan", type(exc).__name__)
|
||||
state.plan = {"source": "deterministic", "assignments": assignments}
|
||||
else:
|
||||
state.plan = {"source": "deterministic", "assignments": assignments}
|
||||
state.mark_completed(executor._node_id)
|
||||
state.stage = "experts"
|
||||
await ctx.send_message({"decision": "parallel_seats", "agents": list(state.seat_agent_ids)})
|
||||
|
||||
|
||||
class PlannerExecutor(ManagerDispatchExecutor):
|
||||
"""Compatibility node retained solely for pre-V2 MAF roundtable runs."""
|
||||
|
||||
def __init__(self, adapter: Any, state: RoundtableState) -> None:
|
||||
super().__init__(adapter, state, executor_id="planner")
|
||||
|
||||
|
||||
class DispatchRouteExecutor(Executor):
|
||||
"""Route only from the verified, persisted manager dispatch decision."""
|
||||
|
||||
def __init__(self, state: RoundtableState) -> None:
|
||||
super().__init__(id="dispatch_route")
|
||||
self._state = state
|
||||
|
||||
@handler(input=Any, output=dict)
|
||||
async def handle(self, message: Any, ctx: WorkflowContext) -> None:
|
||||
plan = self._state.dispatch_plan or {}
|
||||
if self._state.intent_type == "clarification" or not plan:
|
||||
decision = "clarification"
|
||||
elif plan.get("execution_mode") == "manager_only":
|
||||
decision = "manager_only"
|
||||
elif plan.get("mode") == "group_chat" or plan.get("execution_mode") == "group_chat":
|
||||
decision = "group_chat"
|
||||
else:
|
||||
self._state.plan = {"source": "deterministic", "assignments": assignments}
|
||||
decision = "selected_seats"
|
||||
await ctx.send_message({"decision": decision, "agents": list(self._state.selected_seat_agent_ids or [])})
|
||||
|
||||
self._state.mark_completed("planner")
|
||||
|
||||
class DispatchSeatEntryExecutor(Executor):
|
||||
"""Start seat work only after the manager's plan and threads are durable."""
|
||||
|
||||
def __init__(self, state: RoundtableState) -> None:
|
||||
super().__init__(id="dispatch_seat_entry")
|
||||
self._state = state
|
||||
|
||||
@handler(input=Any, output=dict)
|
||||
async def handle(self, message: Any, ctx: WorkflowContext) -> None:
|
||||
self._state.stage = "experts"
|
||||
await ctx.send_message({"decision": "parallel_seats", "agents": self._state.seat_agent_ids})
|
||||
await ctx.send_message({"agents": list(self._state.selected_seat_agent_ids or [])})
|
||||
|
||||
|
||||
# ── Coordinator (group_chat) ────────────────────────────────────────────────
|
||||
class ClarificationTerminalExecutor(Executor):
|
||||
"""Safe terminal branch for invalid, unauthorized, or timed-out planning."""
|
||||
|
||||
def __init__(self, state: RoundtableState) -> None:
|
||||
super().__init__(id="clarification_terminal")
|
||||
self._state = state
|
||||
|
||||
@handler(input=Any, workflow_output=dict)
|
||||
async def handle(self, message: Any, ctx: WorkflowContext) -> None:
|
||||
self._state.status = "waiting_input"
|
||||
self._state.stage = "waiting_input"
|
||||
self._state.mark_completed("clarification_terminal")
|
||||
await ctx.yield_output({"status": "waiting_input", "clarification_prompt": (self._state.dispatch_plan or {}).get("clarification_prompt")})
|
||||
|
||||
|
||||
class DispatchPreparationTerminalExecutor(Executor):
|
||||
"""End the manager-only preparation graph before topology is selected."""
|
||||
|
||||
def __init__(self, state: RoundtableState) -> None:
|
||||
super().__init__(id="dispatch_preparation_terminal")
|
||||
self._state = state
|
||||
|
||||
@handler(input=Any, workflow_output=dict)
|
||||
async def handle(self, message: Any, ctx: WorkflowContext) -> None:
|
||||
self._state.mark_completed("dispatch_preparation_terminal")
|
||||
await ctx.yield_output({
|
||||
"decision": "clarification" if self._state.intent_type == "clarification" else "dispatched",
|
||||
"status": self._state.status,
|
||||
})
|
||||
|
||||
|
||||
class CoordinatorExecutor(Executor):
|
||||
"""Decides which seat speaks next, whether to continue or finish (group_chat)."""
|
||||
"""Choose the next selected group-chat speaker without widening the plan."""
|
||||
|
||||
def __init__(self, adapter: Any, state: RoundtableState) -> None:
|
||||
super().__init__(id="coordinator")
|
||||
@@ -282,41 +521,302 @@ class CoordinatorExecutor(Executor):
|
||||
|
||||
@handler(input=Any, output=dict)
|
||||
async def handle(self, message: Any, ctx: WorkflowContext) -> None:
|
||||
self._state.current_round += 1
|
||||
|
||||
if self._state.stage == "dispatch_validated" and self._state.current_round == 0:
|
||||
self._state.current_round = 1
|
||||
else:
|
||||
self._state.current_round += 1
|
||||
if self._state.current_round > self._state.max_rounds:
|
||||
await ctx.send_message({"decision": "done", "reason": "max_rounds_reached"})
|
||||
return
|
||||
|
||||
if self._state.mode == "structured":
|
||||
# Structured mode no longer uses the coordinator; keep a safe fallback.
|
||||
if self._state.current_round == 1:
|
||||
await ctx.send_message({"decision": "parallel_seats", "agents": self._state.seat_agent_ids})
|
||||
return
|
||||
await ctx.send_message({"decision": "done", "reason": "structured_complete"})
|
||||
return
|
||||
|
||||
eligible = list(self._state.selected_seat_agent_ids) if self._state.selected_seat_agent_ids is not None else list(self._state.seat_agent_ids)
|
||||
remaining = [
|
||||
a for a in self._state.seat_agent_ids
|
||||
if not any(
|
||||
r.get("agent_id") == a and r.get("turn_index", 0) >= self._state.current_round - 1
|
||||
for r in self._state.turn_results
|
||||
)
|
||||
agent_id for agent_id in eligible
|
||||
if not any(row.get("agent_id") == agent_id and row.get("turn_index", 0) >= self._state.current_round - 1 for row in self._state.turn_results)
|
||||
]
|
||||
if not remaining:
|
||||
await ctx.send_message({"decision": "done", "reason": "all_seats_spoke"})
|
||||
await ctx.send_message({"decision": "done", "reason": "all_selected_seats_spoke"})
|
||||
return
|
||||
|
||||
next_agent = remaining[(self._state.current_round - 1) % len(remaining)]
|
||||
await self._adapter._emit_critical(self._state.run_id, {
|
||||
"event_type": "manager.decision",
|
||||
"agent_id": self._state.manager_agent_id or "coordinator",
|
||||
"turn_index": self._state.current_round,
|
||||
"payload": {"next_speaker": next_agent, "reason": "round_robin", "round": self._state.current_round},
|
||||
"payload": {"next_speaker": next_agent, "reason": "selected_plan_round_robin", "round": self._state.current_round},
|
||||
})
|
||||
await ctx.send_message({"decision": "next_speaker", "agent_id": next_agent})
|
||||
|
||||
|
||||
async def _persist_dispatch_checkpoint(adapter: Any, state: RoundtableState) -> None:
|
||||
store = getattr(getattr(adapter, "_service", None), "store", None)
|
||||
if store is not None:
|
||||
await store.runs.update_run(state.run_id, {"maf_checkpoint": state.to_dict()})
|
||||
|
||||
|
||||
async def _emit_dispatch_event(
|
||||
adapter: Any,
|
||||
state: RoundtableState,
|
||||
*,
|
||||
clarification_prompt: str | None = None,
|
||||
) -> None:
|
||||
plan = state.dispatch_plan or {}
|
||||
payload: dict[str, Any] = {
|
||||
"intent_type": state.intent_type,
|
||||
"execution_mode": plan.get("execution_mode", "manager_only"),
|
||||
"selected_seat_agent_ids": list(state.selected_seat_agent_ids or []),
|
||||
"assignments": plan.get("assignments", []),
|
||||
"convergence_path": plan.get("convergence_path", []),
|
||||
"reason": plan.get("reason", "manager_plan_invalid_safe_clarification"),
|
||||
"source": plan.get("source", "deterministic_fallback"),
|
||||
}
|
||||
if clarification_prompt:
|
||||
payload["clarification_prompt"] = clarification_prompt
|
||||
await adapter._emit_critical(state.run_id, {
|
||||
"event_type": "manager.dispatch",
|
||||
"agent_id": state.manager_agent_id or "",
|
||||
"turn_index": 0,
|
||||
"payload": payload,
|
||||
})
|
||||
|
||||
|
||||
async def _ensure_selected_seat_threads(adapter: Any, state: RoundtableState) -> None:
|
||||
"""Persist and bind threads only for server-validated selected seats."""
|
||||
selected = list(state.selected_seat_agent_ids or [])
|
||||
if not selected:
|
||||
return
|
||||
store = getattr(getattr(adapter, "_service", None), "store", None)
|
||||
participants_repo = getattr(store, "participants", None)
|
||||
if participants_repo is None:
|
||||
return
|
||||
route_mode = state.mode if state.mode in {"structured", "group_chat"} else "structured"
|
||||
candidate_set = MafDispatchCandidateSet(
|
||||
manager_agent_id=str(state.manager_agent_id or ""),
|
||||
candidate_seat_agent_ids=list(state.candidate_seat_agent_ids),
|
||||
mode=route_mode,
|
||||
max_rounds=state.max_rounds,
|
||||
)
|
||||
candidate_rows = MafDispatchCatalog.candidate_participants(
|
||||
candidate_set,
|
||||
capability_snapshot=state.capability_snapshot,
|
||||
)
|
||||
selected_rows = [row for row in candidate_rows if row.get("agent_id") in selected]
|
||||
await participants_repo.ensure_participants(state.session_id, selected_rows)
|
||||
persisted = await participants_repo.list_participants(state.session_id)
|
||||
selected_persisted = [row for row in persisted if row.get("agent_id") in selected]
|
||||
if selected_persisted:
|
||||
state.thread_map.update(
|
||||
await adapter.ensure_threads(state.session_id, state.run_id, selected_persisted)
|
||||
)
|
||||
|
||||
|
||||
async def _resolve_manager_dispatch(
|
||||
executor: ManagerDispatchExecutor, ctx: WorkflowContext
|
||||
) -> None:
|
||||
"""Run, validate, persist, and route the sole V2 manager dispatch turn."""
|
||||
adapter = executor._adapter
|
||||
state = executor._state
|
||||
manager_id = str(state.manager_agent_id or "").strip()
|
||||
route_mode = state.mode if state.mode in {"structured", "group_chat"} else "structured"
|
||||
candidate_set = MafDispatchCandidateSet(
|
||||
manager_agent_id=manager_id,
|
||||
candidate_seat_agent_ids=list(state.candidate_seat_agent_ids),
|
||||
mode=route_mode,
|
||||
max_rounds=state.max_rounds,
|
||||
)
|
||||
|
||||
async def clarification(reason: str) -> None:
|
||||
prompt = "Please clarify the goal, expected outcome, and relevant business context."
|
||||
state.intent_type = "clarification"
|
||||
state.dispatch_plan = {
|
||||
"execution_mode": "manager_only",
|
||||
"convergence_path": ["clarification"],
|
||||
"reason": reason,
|
||||
"source": "deterministic_fallback",
|
||||
"clarification_prompt": prompt,
|
||||
}
|
||||
state.selected_seat_agent_ids = []
|
||||
state.plan = None
|
||||
state.status = "waiting_input"
|
||||
state.stage = "waiting_input"
|
||||
state.mark_completed(executor._node_id)
|
||||
await _persist_dispatch_checkpoint(adapter, state)
|
||||
await _emit_dispatch_event(adapter, state, clarification_prompt=prompt)
|
||||
await adapter._emit_critical(state.run_id, {
|
||||
"event_type": "clarification.required",
|
||||
"agent_id": manager_id,
|
||||
"turn_index": 0,
|
||||
"payload": {"prompt": prompt, "reason": reason},
|
||||
})
|
||||
await ctx.send_message({"decision": "clarification", "agents": []})
|
||||
|
||||
# A checkpoint written after validation survives process recovery and is
|
||||
# never re-planned. It still creates any selected threads that were not
|
||||
# bound before interruption.
|
||||
if state.dispatch_plan and state.intent_type:
|
||||
try:
|
||||
existing = MafDispatchPlan.model_validate(state.dispatch_plan)
|
||||
except (TypeError, ValueError):
|
||||
await clarification("checkpoint_dispatch_plan_invalid")
|
||||
return
|
||||
state.selected_seat_agent_ids = list(existing.seat_agent_ids)
|
||||
state.plan = {
|
||||
"source": existing.source,
|
||||
"assignments": {
|
||||
assignment.agent_id: {
|
||||
"role": assignment.role,
|
||||
"instruction": "\n".join(
|
||||
[assignment.task_goal, *assignment.delivery_requirements]
|
||||
),
|
||||
}
|
||||
for assignment in existing.assignments
|
||||
},
|
||||
}
|
||||
await _ensure_selected_seat_threads(adapter, state)
|
||||
state.mark_completed(executor._node_id)
|
||||
await _persist_dispatch_checkpoint(adapter, state)
|
||||
await ctx.send_message({
|
||||
"decision": executor._dispatch_decision(),
|
||||
"agents": list(state.selected_seat_agent_ids or []),
|
||||
"replayed": True,
|
||||
})
|
||||
return
|
||||
|
||||
thread_id = state.thread_map.get(manager_id, "")
|
||||
if not manager_id or not thread_id:
|
||||
await clarification("manager_thread_unavailable")
|
||||
return
|
||||
|
||||
capability_summary = MafDispatchCatalog.manager_capability_summary(
|
||||
state.capability_snapshot,
|
||||
candidate_set,
|
||||
)
|
||||
manager_tool_names = [
|
||||
str(tool.get("tool_name"))
|
||||
for agent in (state.capability_snapshot or {}).get("agents", [])
|
||||
if isinstance(agent, dict) and agent.get("agent_id") == manager_id
|
||||
for tool in (agent.get("tools") or [])
|
||||
if isinstance(tool, dict) and tool.get("tool_name")
|
||||
]
|
||||
contract = {
|
||||
"intent_type": "direct_answer|clarification|single_seat|parallel_consultation|chain_consultation|tool_write",
|
||||
"selected_seat_agent_ids": "candidate IDs only",
|
||||
"assignments": "one ordered task_goal and delivery_requirements entry per selected seat",
|
||||
"execution_mode": "manager_only|single|parallel|chain|group_chat",
|
||||
"convergence_path": ["how work converges"],
|
||||
"reason": "brief explanation",
|
||||
"clarification_prompt": "required only for clarification",
|
||||
}
|
||||
prompt = (
|
||||
"You are the MAF manager. Determine the user intent and return exactly one JSON object, "
|
||||
"without Markdown. You may select only from the trusted candidate seats and their redacted "
|
||||
"capabilities. Invalid or uncertain requests must use clarification; never invent a seat, "
|
||||
"tool, capability, or route.\n\n"
|
||||
f"User task:\n{state.task_text}\n\n"
|
||||
f"Trusted route mode: {candidate_set.mode}\n"
|
||||
f"Trusted candidate seats: {json.dumps(candidate_set.candidate_seat_agent_ids)}\n"
|
||||
f"Trusted capability summary: {json.dumps(capability_summary, ensure_ascii=False)}\n"
|
||||
f"Required JSON shape: {json.dumps(contract)}"
|
||||
)
|
||||
try:
|
||||
response = await asyncio.wait_for(
|
||||
adapter.run_seat_turn(
|
||||
session_id=state.session_id,
|
||||
run_id=state.run_id,
|
||||
agent_id=manager_id,
|
||||
turn_index=0,
|
||||
execution_stage="manager_dispatch",
|
||||
message=prompt,
|
||||
thread_id=thread_id,
|
||||
model_name=state.model_name,
|
||||
reasoning_effort=state.reasoning_effort,
|
||||
task_text=state.task_text,
|
||||
stage_instruction="Return only the strict MAF dispatch JSON object.",
|
||||
excluded_tools=manager_tool_names,
|
||||
fact_ledger=state.fact_ledger,
|
||||
capability_snapshot=state.capability_snapshot,
|
||||
write_policy=state.write_policy,
|
||||
wait_timeout_seconds=state.seat_timeout_seconds,
|
||||
),
|
||||
timeout=state.seat_timeout_seconds,
|
||||
)
|
||||
except TimeoutError:
|
||||
await clarification("manager_dispatch_timeout")
|
||||
return
|
||||
except Exception: # noqa: BLE001 - model/runtime details must not reach the user
|
||||
await clarification("manager_dispatch_failed")
|
||||
return
|
||||
if response.error:
|
||||
await clarification("manager_dispatch_failed")
|
||||
return
|
||||
|
||||
try:
|
||||
proposed, plan = MafDispatchCatalog.parse_manager_decision(
|
||||
response.content or "",
|
||||
candidate_set=candidate_set,
|
||||
max_seats=len(candidate_set.candidate_seat_agent_ids),
|
||||
capability_snapshot=state.capability_snapshot,
|
||||
)
|
||||
except InvalidDispatchPlanError:
|
||||
await clarification("manager_dispatch_invalid")
|
||||
return
|
||||
|
||||
state.intent_type = proposed.intent_type
|
||||
if plan is None:
|
||||
state.dispatch_plan = {
|
||||
"execution_mode": "manager_only",
|
||||
"convergence_path": list(proposed.convergence_path),
|
||||
"reason": proposed.reason,
|
||||
"source": "manager",
|
||||
"clarification_prompt": proposed.clarification_prompt,
|
||||
}
|
||||
state.selected_seat_agent_ids = []
|
||||
state.plan = None
|
||||
state.status = "waiting_input"
|
||||
state.stage = "waiting_input"
|
||||
state.mark_completed(executor._node_id)
|
||||
await _persist_dispatch_checkpoint(adapter, state)
|
||||
await _emit_dispatch_event(
|
||||
adapter,
|
||||
state,
|
||||
clarification_prompt=proposed.clarification_prompt,
|
||||
)
|
||||
await adapter._emit_critical(state.run_id, {
|
||||
"event_type": "clarification.required",
|
||||
"agent_id": manager_id,
|
||||
"turn_index": 0,
|
||||
"payload": {"prompt": proposed.clarification_prompt, "reason": proposed.reason},
|
||||
})
|
||||
await ctx.send_message({"decision": "clarification", "agents": []})
|
||||
return
|
||||
|
||||
state.dispatch_plan = plan.model_dump(mode="json")
|
||||
state.selected_seat_agent_ids = list(plan.seat_agent_ids)
|
||||
state.plan = {
|
||||
"source": plan.source,
|
||||
"assignments": {
|
||||
assignment.agent_id: {
|
||||
"role": assignment.role,
|
||||
"instruction": "\n".join(
|
||||
[assignment.task_goal, *assignment.delivery_requirements]
|
||||
),
|
||||
}
|
||||
for assignment in plan.assignments
|
||||
},
|
||||
}
|
||||
state.stage = "dispatch_validated"
|
||||
# Persist before adding a participant or thread: recovery cannot obtain a
|
||||
# different model decision after a process interruption.
|
||||
await _persist_dispatch_checkpoint(adapter, state)
|
||||
await _ensure_selected_seat_threads(adapter, state)
|
||||
state.mark_completed(executor._node_id)
|
||||
await _persist_dispatch_checkpoint(adapter, state)
|
||||
await _emit_dispatch_event(adapter, state)
|
||||
await ctx.send_message({
|
||||
"decision": executor._dispatch_decision(),
|
||||
"agents": list(state.selected_seat_agent_ids),
|
||||
"execution_mode": plan.execution_mode,
|
||||
})
|
||||
|
||||
|
||||
# ── Seat executor ───────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -349,6 +849,17 @@ class SeatExecutor(Executor):
|
||||
await ctx.send_message({"agent_id": self._agent_id, **prior, "replayed": True})
|
||||
return
|
||||
|
||||
selected = self._state.selected_seat_agent_ids
|
||||
if selected is not None and self._agent_id not in selected:
|
||||
self._state.seat_outcomes[self._agent_id] = {"status": "skipped", "reason": "not_selected"}
|
||||
self._state.mark_completed(node_id)
|
||||
await ctx.send_message({
|
||||
"agent_id": self._agent_id,
|
||||
"status": "skipped",
|
||||
"reason": "not_selected",
|
||||
})
|
||||
return
|
||||
|
||||
thread_id = self._state.thread_map.get(self._agent_id, "")
|
||||
if not thread_id:
|
||||
self._record_failure("no_thread", f"no thread for agent {self._agent_id}")
|
||||
@@ -621,7 +1132,8 @@ class CrossReviewExecutor(Executor):
|
||||
self._state.stage = "review"
|
||||
|
||||
# Barrier: ensure every seat has an outcome (fan-in should guarantee this).
|
||||
missing = [a for a in self._state.seat_agent_ids if a not in self._state.seat_outcomes]
|
||||
review_seats = self._state.selected_seat_agent_ids or self._state.seat_agent_ids
|
||||
missing = [a for a in review_seats if a not in self._state.seat_outcomes]
|
||||
for aid in missing:
|
||||
self._state.seat_outcomes[aid] = {"status": "missing", "error": "no_outcome"}
|
||||
self._state.partial_failure = True
|
||||
@@ -654,7 +1166,7 @@ class CrossReviewExecutor(Executor):
|
||||
try:
|
||||
prompt = build_manager_synthesis_input(
|
||||
task_text=self._state.task_text,
|
||||
seat_results=[r for r in self._state.turn_results if r.get("agent_id") in self._state.seat_agent_ids],
|
||||
seat_results=[r for r in self._state.turn_results if r.get("agent_id") in review_seats],
|
||||
fact_ledger=self._state.fact_ledger,
|
||||
)
|
||||
# Surface the candidate ids + the evidence refs the ledger has
|
||||
|
||||
Reference in new issue
Block a user