Merge origin/master into ji
This commit is contained in:
commit
e96cc97462
54 files changed
+4900
-334
No files matched your search
+48
@@ -0,0 +1,48 @@
|
||||
"""圆桌总控编排引擎(Phase 2)。
|
||||
|
||||
把前端 useStep2Orchestration 的编排循环移植到后端,作为可后台跑、可单测的纯引擎。
|
||||
Phase 3 会提供具体的 ``RoundtableGateway`` 实现(复用 multi_agent.py 内部函数)+
|
||||
执行器 / LangGraph 注册,把引擎接到真实的 LLM / 线程上。
|
||||
|
||||
公开入口:
|
||||
- ``run_orchestration`` —— 跑一次完整编排(循环 → 共识 → 报告绘制)。
|
||||
- ``JobProgressWriter`` —— 进度落库 + 可选 SSE 外发。
|
||||
- 协议 / 数据类(``RoundtableGateway`` / ``LeaderTurn`` / ``SeatTurn`` /
|
||||
``ReportResult`` / ``SeatRef``)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .engine import OrchestrationResult, build_report_prompt, run_orchestration
|
||||
from .progress import JobProgressWriter
|
||||
from .simulated_gateway import SimulatedRoundtableGateway
|
||||
from .types import (
|
||||
CHAIN_CLOSEOUT_PROMPT,
|
||||
CONTINUE_PROMPT,
|
||||
MAX_CYCLES,
|
||||
LeaderTurn,
|
||||
ReportResult,
|
||||
RoundtableGateway,
|
||||
SeatRef,
|
||||
SeatTurn,
|
||||
build_chain_leader_task,
|
||||
pick_chain_task,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"run_orchestration",
|
||||
"OrchestrationResult",
|
||||
"build_report_prompt",
|
||||
"JobProgressWriter",
|
||||
"SimulatedRoundtableGateway",
|
||||
"RoundtableGateway",
|
||||
"LeaderTurn",
|
||||
"SeatTurn",
|
||||
"ReportResult",
|
||||
"SeatRef",
|
||||
"MAX_CYCLES",
|
||||
"CONTINUE_PROMPT",
|
||||
"CHAIN_CLOSEOUT_PROMPT",
|
||||
"build_chain_leader_task",
|
||||
"pick_chain_task",
|
||||
]
|
||||
+299
@@ -0,0 +1,299 @@
|
||||
"""圆桌总控编排引擎 —— 后台跑的编排循环(移植自前端 useStep2Orchestration.ts)。
|
||||
|
||||
纯逻辑:通过 ``RoundtableGateway`` 协议驱动「单轮 leader / seat / report」,通过
|
||||
``JobProgressWriter`` 落库进度。两种模式:
|
||||
|
||||
- recommend(``runOrchestration``):总控自由派活循环,leader → 顺序派 special →
|
||||
leader …,直到 ``dispatched==[]``(共识)或达到 ``MAX_CYCLES``;
|
||||
- chain(``runChainOrchestration``):总控**按席位顺序**逐位派活,走完整链后由
|
||||
leader 收口产出最终结论。
|
||||
|
||||
共识达成(或 max cycles 强制收口)后进入 Step3 报告绘制,写出 ``方案总览.html``,
|
||||
返回 ``DraftStep3Snapshot`` 形状的 step3 快照。命中澄清则返回 ``awaiting_input``
|
||||
(thread 已 checkpoint,resume 时由调用方用用户答案再发起一轮即可续跑)。
|
||||
|
||||
**不并行 special**(与前端同一不变量):顺序 await 每个席位,避免 token 级抖动 +
|
||||
保证派活链路游标严格推进。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from .progress import JobProgressWriter
|
||||
from .types import (
|
||||
CHAIN_CLOSEOUT_PROMPT,
|
||||
CONTINUE_PROMPT,
|
||||
MAX_CYCLES,
|
||||
ReportResult,
|
||||
RoundtableGateway,
|
||||
SeatRef,
|
||||
build_chain_leader_task,
|
||||
pick_chain_task,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class OrchestrationResult:
|
||||
"""引擎一次运行的终态。"""
|
||||
|
||||
status: str # "done" | "awaiting_input" | "error"
|
||||
consensus: bool = False
|
||||
step3: dict | None = None
|
||||
pending_clarification: str | None = None
|
||||
error: str | None = None
|
||||
last_leader_content: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class _LoopOutcome:
|
||||
"""内部:编排循环(未进报告阶段)的结果。"""
|
||||
|
||||
kind: str # "consensus" | "clarification" | "max_cycles"
|
||||
question: str | None = None
|
||||
last_leader_content: str = ""
|
||||
# {agent_id: 最近一次交付正文}
|
||||
deliveries: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
|
||||
async def run_orchestration(
|
||||
*,
|
||||
gateway: RoundtableGateway,
|
||||
progress: JobProgressWriter,
|
||||
agents: list[SeatRef],
|
||||
thread_ids: dict[str, str],
|
||||
coordinator_name: str,
|
||||
model: str | None,
|
||||
seed_message: str,
|
||||
mode: str = "recommend",
|
||||
intent_text: str = "",
|
||||
) -> OrchestrationResult:
|
||||
"""运行一次完整编排(循环 → 共识 → 报告绘制)。
|
||||
|
||||
Args:
|
||||
gateway: 单轮执行抽象出口。
|
||||
progress: 进度写入器(落库 + 可选 SSE 外发)。
|
||||
agents: 有序席位(recommend=选择顺序 / chain=链条顺序)。
|
||||
thread_ids: {agent_id / coordinator_name: thread_id},预先建好。
|
||||
coordinator_name: 总控 agent_id(如 "roundtable-coordinator")。
|
||||
model: 选定模型(None/"" 走后端默认)。
|
||||
seed_message: 第一轮 leader 的 prompt(启动=初始意图;resume=用户答案续轮)。
|
||||
mode: "recommend" | "chain"。
|
||||
intent_text: 任务意图,用于报告 prompt(缺省退回 seed_message)。
|
||||
"""
|
||||
try:
|
||||
await progress.begin()
|
||||
if mode == "chain":
|
||||
outcome = await _run_chain(gateway, progress, agents, thread_ids, coordinator_name, model, seed_message)
|
||||
else:
|
||||
outcome = await _run_recommend(gateway, progress, agents, thread_ids, coordinator_name, model, seed_message)
|
||||
|
||||
if outcome.kind == "clarification":
|
||||
question = outcome.question or "总控需要补充信息,请补充后继续。"
|
||||
await progress.awaiting_input(question)
|
||||
return OrchestrationResult(
|
||||
status="awaiting_input",
|
||||
pending_clarification=question,
|
||||
last_leader_content=outcome.last_leader_content,
|
||||
)
|
||||
|
||||
# consensus 或 max_cycles:均收口 → 报告绘制
|
||||
await progress.consensus(100)
|
||||
step3 = await _run_report(
|
||||
gateway,
|
||||
progress,
|
||||
agents=agents,
|
||||
model=model,
|
||||
intent_text=intent_text or seed_message,
|
||||
consensus_text=outcome.last_leader_content,
|
||||
deliveries=outcome.deliveries,
|
||||
)
|
||||
await progress.done()
|
||||
return OrchestrationResult(
|
||||
status="done",
|
||||
consensus=True,
|
||||
step3=step3,
|
||||
last_leader_content=outcome.last_leader_content,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 — 顶层兜底:标记 error 并返回
|
||||
logger.exception("roundtable orchestration failed")
|
||||
await progress.error(str(exc))
|
||||
return OrchestrationResult(status="error", error=str(exc))
|
||||
|
||||
|
||||
# ── recommend 模式 ───────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
async def _run_recommend(
|
||||
gateway: RoundtableGateway,
|
||||
progress: JobProgressWriter,
|
||||
agents: list[SeatRef],
|
||||
thread_ids: dict[str, str],
|
||||
coordinator_name: str,
|
||||
model: str | None,
|
||||
seed_message: str,
|
||||
) -> _LoopOutcome:
|
||||
deliveries: dict[str, str] = {}
|
||||
last_leader = ""
|
||||
message = seed_message
|
||||
|
||||
for cycle in range(1, MAX_CYCLES + 1):
|
||||
await progress.leader_thinking(cycle)
|
||||
turn = await gateway.run_leader(
|
||||
thread_ids=thread_ids,
|
||||
coordinator_name=coordinator_name,
|
||||
message=message,
|
||||
model=model,
|
||||
)
|
||||
if turn.final_text:
|
||||
last_leader = turn.final_text
|
||||
|
||||
if turn.is_clarification:
|
||||
return _LoopOutcome("clarification", question=turn.clarification, last_leader_content=last_leader, deliveries=deliveries)
|
||||
if turn.is_consensus:
|
||||
return _LoopOutcome("consensus", last_leader_content=last_leader, deliveries=deliveries)
|
||||
|
||||
# **顺序**派活 —— 不要并行
|
||||
await progress.dispatching(cycle)
|
||||
for agent_id, task in turn.dispatched:
|
||||
await progress.seat_active(agent_id)
|
||||
seat = await gateway.run_seat(thread_ids=thread_ids, agent_id=agent_id, task=task, model=model)
|
||||
deliveries[agent_id] = seat.final_text
|
||||
await progress.seat_done(agent_id, cycle)
|
||||
|
||||
await progress.bump_consensus()
|
||||
message = CONTINUE_PROMPT
|
||||
|
||||
# 达到最大轮次:强制收口(对齐前端 toast「已达到最大研讨轮次」)
|
||||
logger.info("roundtable recommend loop hit MAX_CYCLES=%d, forcing consensus", MAX_CYCLES)
|
||||
return _LoopOutcome("max_cycles", last_leader_content=last_leader, deliveries=deliveries)
|
||||
|
||||
|
||||
# ── chain 模式 ───────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
async def _run_chain(
|
||||
gateway: RoundtableGateway,
|
||||
progress: JobProgressWriter,
|
||||
agents: list[SeatRef],
|
||||
thread_ids: dict[str, str],
|
||||
coordinator_name: str,
|
||||
model: str | None,
|
||||
seed_message: str,
|
||||
) -> _LoopOutcome:
|
||||
deliveries: dict[str, str] = {}
|
||||
last_leader = ""
|
||||
total = len(agents)
|
||||
|
||||
for i, seat in enumerate(agents):
|
||||
# (a) 总控按链条顺序只给当前席位派活
|
||||
await progress.leader_thinking(i + 1)
|
||||
leader_task = build_chain_leader_task(
|
||||
seed_message=seed_message,
|
||||
position=i,
|
||||
total=total,
|
||||
seat_agent_id=seat.agent_id,
|
||||
seat_name=seat.name,
|
||||
is_first=(i == 0),
|
||||
)
|
||||
turn = await gateway.run_leader(
|
||||
thread_ids=thread_ids,
|
||||
coordinator_name=coordinator_name,
|
||||
message=leader_task,
|
||||
model=model,
|
||||
)
|
||||
if turn.final_text:
|
||||
last_leader = turn.final_text
|
||||
if turn.is_clarification:
|
||||
return _LoopOutcome("clarification", question=turn.clarification, last_leader_content=last_leader, deliveries=deliveries)
|
||||
|
||||
task = pick_chain_task(turn.dispatched, turn.final_text, seat.agent_id, seat.name)
|
||||
|
||||
# (b) 当前席位交付(顺序,不并行)
|
||||
await progress.seat_active(seat.agent_id)
|
||||
seat_turn = await gateway.run_seat(thread_ids=thread_ids, agent_id=seat.agent_id, task=task, model=model)
|
||||
deliveries[seat.agent_id] = seat_turn.final_text
|
||||
await progress.seat_done(seat.agent_id, i + 1)
|
||||
|
||||
if total > 0:
|
||||
await progress.set_consensus_pct(round((i + 1) / total * 90))
|
||||
|
||||
# (c) 总控收口:综合全链交付,产出最终结论
|
||||
if total > 0:
|
||||
await progress.leader_thinking(total + 1)
|
||||
closeout = await gateway.run_leader(
|
||||
thread_ids=thread_ids,
|
||||
coordinator_name=coordinator_name,
|
||||
message=CHAIN_CLOSEOUT_PROMPT,
|
||||
model=model,
|
||||
)
|
||||
if closeout.final_text:
|
||||
last_leader = closeout.final_text
|
||||
|
||||
return _LoopOutcome("consensus", last_leader_content=last_leader, deliveries=deliveries)
|
||||
|
||||
|
||||
# ── 报告阶段 ─────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
async def _run_report(
|
||||
gateway: RoundtableGateway,
|
||||
progress: JobProgressWriter,
|
||||
*,
|
||||
agents: list[SeatRef],
|
||||
model: str | None,
|
||||
intent_text: str,
|
||||
consensus_text: str,
|
||||
deliveries: dict[str, str],
|
||||
) -> dict:
|
||||
await progress.report_drawing()
|
||||
report_thread_id = await gateway.create_report_thread()
|
||||
prompt = build_report_prompt(intent_text, agents, deliveries, consensus_text)
|
||||
report: ReportResult = await gateway.run_report(report_thread_id=report_thread_id, prompt=prompt, model=model)
|
||||
return {
|
||||
"html": report.html,
|
||||
"generatedAt": report.generated_at or datetime.now(UTC).isoformat(),
|
||||
"model": report.model or (model or ""),
|
||||
"summary": report.summary,
|
||||
}
|
||||
|
||||
|
||||
def build_report_prompt(
|
||||
intent_text: str,
|
||||
agents: list[SeatRef],
|
||||
deliveries: dict[str, str],
|
||||
consensus_text: str,
|
||||
) -> str:
|
||||
"""拼装 Step3 报告绘制 prompt:意图 + 各席位交付 + 总控共识。
|
||||
|
||||
席位交付按 ``agents`` 顺序列出(缺交付的席位跳过)。报告智能体据此用 write_file
|
||||
写出自包含的 ``outputs/方案总览.html``(具体绘制规则在 roundtable-report 的 SOUL)。
|
||||
"""
|
||||
lines: list[str] = [
|
||||
"【圆桌最终成果汇总 —— 请据此绘制方案总览 HTML 看板】",
|
||||
"",
|
||||
"## 任务意图",
|
||||
(intent_text or "").strip() or "(未提供)",
|
||||
"",
|
||||
"## 各席位交付",
|
||||
]
|
||||
name_by_id = {a.agent_id: a.name for a in agents}
|
||||
has_delivery = False
|
||||
for a in agents:
|
||||
text = (deliveries.get(a.agent_id) or "").strip()
|
||||
if not text:
|
||||
continue
|
||||
has_delivery = True
|
||||
lines.append(f"### {name_by_id.get(a.agent_id, a.agent_id)}")
|
||||
lines.append(text)
|
||||
lines.append("")
|
||||
if not has_delivery:
|
||||
lines.append("(各席位暂无可用交付,请基于任务意图与总控结论绘制。)")
|
||||
lines.append("")
|
||||
lines.append("## 总控最终结论")
|
||||
lines.append((consensus_text or "").strip() or "(未提供)")
|
||||
return "\n".join(lines)
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
"""编排进度写入器 —— 把引擎的状态流转持久化进 ``roundtable_jobs`` 表。
|
||||
|
||||
引擎只调本类的语义方法(leader_thinking / seat_active / seat_done / consensus / …),
|
||||
由它维护「派活链路各节点状态」并落库(best-effort,失败不打断编排)。落库的
|
||||
``dispatch_chain`` 即 Phase 7 流程图弹窗 / Phase 6 历史下拉的数据源。
|
||||
|
||||
进度同时可通过可选的 ``event_sink`` 回调外发(Phase 3 的 SSE 流用),引擎逻辑不感知。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, Awaitable, Callable
|
||||
|
||||
from .types import SeatRef
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 节点状态机:pending → active → done。
|
||||
_PENDING = "pending"
|
||||
_ACTIVE = "active"
|
||||
_DONE = "done"
|
||||
|
||||
EventSink = Callable[[dict[str, Any]], Awaitable[None]] | None
|
||||
|
||||
|
||||
class JobProgressWriter:
|
||||
"""跟踪派活链路节点状态并持久化进度。
|
||||
|
||||
Args:
|
||||
store: ``RoundtableJobRepository``(或任何提供 ``update_progress`` 的对象);
|
||||
传 None 时所有持久化变 no-op(引擎仍可纯跑,便于干测)。
|
||||
job_id: 目标作业 id。
|
||||
agents: 有序席位列表(recommend=选择顺序 / chain=链条顺序)→ 决定节点 order。
|
||||
event_sink: 可选异步回调,每次进度变更时透传一份归一化事件(Phase 3 SSE)。
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
store: Any | None,
|
||||
*,
|
||||
job_id: str,
|
||||
agents: list[SeatRef],
|
||||
event_sink: EventSink = None,
|
||||
) -> None:
|
||||
self._store = store
|
||||
self._job_id = job_id
|
||||
self._agents = list(agents)
|
||||
self._event_sink = event_sink
|
||||
self._state: dict[str, str] = {a.agent_id: _PENDING for a in agents}
|
||||
self._spoke_cycle: dict[str, int] = {}
|
||||
self._consensus = 0
|
||||
|
||||
# ── 节点快照 ──────────────────────────────────────────────────────────
|
||||
|
||||
def _nodes(self) -> list[dict[str, Any]]:
|
||||
"""构造 dispatch_chain 节点数组(§2.3)。
|
||||
|
||||
不含 avatarType —— 颜色由前端 ``getAvatarTypeFor(agentId, order)`` 派生,
|
||||
避免把前端的 BUILTIN_AGENT_META 配色表重复移植到后端(易漂移)。
|
||||
"""
|
||||
out: list[dict[str, Any]] = []
|
||||
for i, a in enumerate(self._agents):
|
||||
node: dict[str, Any] = {
|
||||
"agentId": a.agent_id,
|
||||
"name": a.name,
|
||||
"order": i + 1,
|
||||
"state": self._state.get(a.agent_id, _PENDING),
|
||||
}
|
||||
if a.agent_id in self._spoke_cycle:
|
||||
node["lastSpokeCycle"] = self._spoke_cycle[a.agent_id]
|
||||
out.append(node)
|
||||
return out
|
||||
|
||||
async def _persist(self, **fields: Any) -> None:
|
||||
"""落库(始终带最新 dispatch_chain + consensus)+ 外发事件,均 best-effort。"""
|
||||
fields.setdefault("dispatch_chain", self._nodes())
|
||||
fields.setdefault("consensus_percentage", self._consensus)
|
||||
if self._store is not None:
|
||||
try:
|
||||
await self._store.update_progress(self._job_id, **fields)
|
||||
except Exception: # noqa: BLE001 — 进度落库失败不能打断编排
|
||||
logger.warning("roundtable job progress persist failed", exc_info=True)
|
||||
if self._event_sink is not None:
|
||||
try:
|
||||
await self._event_sink({"job_id": self._job_id, **fields})
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("roundtable job progress event sink failed", exc_info=True)
|
||||
|
||||
# ── 语义方法(引擎调用)─────────────────────────────────────────────────
|
||||
|
||||
async def begin(self) -> None:
|
||||
await self._persist(status="running", phase="initializing", cycle=0, active_agent_id=None)
|
||||
|
||||
async def leader_thinking(self, cycle: int) -> None:
|
||||
await self._persist(phase="leader_thinking", cycle=cycle, active_agent_id=None)
|
||||
|
||||
async def dispatching(self, cycle: int) -> None:
|
||||
await self._persist(phase="dispatching", cycle=cycle)
|
||||
|
||||
async def seat_active(self, agent_id: str) -> None:
|
||||
if agent_id in self._state:
|
||||
self._state[agent_id] = _ACTIVE
|
||||
await self._persist(phase="dispatching", active_agent_id=agent_id)
|
||||
|
||||
async def seat_done(self, agent_id: str, cycle: int) -> None:
|
||||
if agent_id in self._state:
|
||||
self._state[agent_id] = _DONE
|
||||
self._spoke_cycle[agent_id] = cycle
|
||||
await self._persist(active_agent_id=None)
|
||||
|
||||
async def bump_consensus(self) -> None:
|
||||
"""recommend 每轮派活后 +8(封顶 95),对齐前端。"""
|
||||
self._consensus = min(95, self._consensus + 8)
|
||||
await self._persist()
|
||||
|
||||
async def set_consensus_pct(self, pct: int) -> None:
|
||||
"""chain 每席位后设进度(封顶 95),对齐前端 round((i+1)/total*90)。"""
|
||||
self._consensus = min(95, int(pct))
|
||||
await self._persist()
|
||||
|
||||
async def consensus(self, pct: int = 100) -> None:
|
||||
self._consensus = int(pct)
|
||||
await self._persist(phase="consensus", active_agent_id=None)
|
||||
|
||||
async def report_drawing(self) -> None:
|
||||
await self._persist(phase="report_drawing", active_agent_id=None)
|
||||
|
||||
async def done(self) -> None:
|
||||
self._consensus = 100
|
||||
await self._persist(status="done", phase="report_done", active_agent_id=None)
|
||||
|
||||
async def awaiting_input(self, question: str) -> None:
|
||||
await self._persist(
|
||||
status="awaiting_input",
|
||||
phase="leader_thinking",
|
||||
active_agent_id=None,
|
||||
pending_clarification=question,
|
||||
)
|
||||
|
||||
async def error(self, message: str) -> None:
|
||||
await self._persist(status="error", error=message)
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
"""模拟网关 —— 产生真实的编排进度但**不调真模型 / 真 LangGraph server**。
|
||||
|
||||
用途:
|
||||
- Phase 3a:让 ``/api/roundtable-jobs`` 控制面(路由 + 执行器 + SSE)端到端跑起来,
|
||||
前端 Phase 4-8 可对着真实 API + 真实 job 表 + 真实 SSE 联调,无需真模型;
|
||||
- 单测:``delay=0`` 时瞬时跑完,验证执行器 / 进度落库 / 路由生命周期。
|
||||
|
||||
真网关 ``InProcessRoundtableGateway``(进程内驱动 leader/seat/report run,复用
|
||||
multi_agent 的纯解析函数 + ``set_current_user`` 进程内调 agent runtime)是 Phase 3b,
|
||||
需在 live stack 上验证。本模拟器与真网关实现同一个 ``RoundtableGateway`` 协议,可直接替换。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
from .types import LeaderTurn, ReportResult, SeatRef, SeatTurn
|
||||
|
||||
|
||||
class SimulatedRoundtableGateway:
|
||||
"""脚本化的假网关。
|
||||
|
||||
recommend:第 1 轮把所有席位派活一遍 → 第 2 轮共识;
|
||||
chain:每个 per-seat leader 调用不显式派活(引擎据链条顺序强制跑席位)→ 收口。
|
||||
"""
|
||||
|
||||
def __init__(self, agents: list[SeatRef], *, delay: float = 0.6, mode: str = "recommend") -> None:
|
||||
self._agents = list(agents)
|
||||
self._delay = delay
|
||||
self._mode = mode
|
||||
self._leader_calls = 0
|
||||
|
||||
async def _tick(self) -> None:
|
||||
if self._delay > 0:
|
||||
await asyncio.sleep(self._delay)
|
||||
|
||||
async def run_leader(self, *, thread_ids, coordinator_name, message, model) -> LeaderTurn:
|
||||
await self._tick()
|
||||
self._leader_calls += 1
|
||||
if self._mode == "chain":
|
||||
# chain 模式由引擎按链条顺序强制跑席位,leader 只给说明、不派活。
|
||||
return LeaderTurn(final_text="(模拟)总控:请当前席位按职责给出分析。", dispatched=[])
|
||||
# recommend:首轮派活全部席位,次轮共识。
|
||||
if self._leader_calls == 1:
|
||||
return LeaderTurn(
|
||||
final_text="(模拟)总控首轮派活:已为各席位分配本轮任务。",
|
||||
dispatched=[(a.agent_id, f"请「{a.name}」就任务从你的专业职责给出分析与建议。") for a in self._agents],
|
||||
)
|
||||
return LeaderTurn(final_text="(模拟)各席位已充分研讨,结论收敛,达成共识。", dispatched=[])
|
||||
|
||||
async def run_seat(self, *, thread_ids, agent_id, task, model) -> SeatTurn:
|
||||
await self._tick()
|
||||
return SeatTurn(final_text=f"(模拟){agent_id} 的交付:已基于任务背景完成本轮分析。")
|
||||
|
||||
async def create_report_thread(self) -> str:
|
||||
return "sim-report-thread"
|
||||
|
||||
async def run_report(self, *, report_thread_id, prompt, model) -> ReportResult:
|
||||
await self._tick()
|
||||
html = (
|
||||
"<!doctype html><html><head><meta charset='utf-8'><title>方案总览(模拟)</title></head>"
|
||||
"<body><h1>方案总览(模拟)</h1><p>这是模拟网关生成的占位报告,用于前端联调。</p></body></html>"
|
||||
)
|
||||
return ReportResult(html=html, summary="(模拟)方案已生成", model=model)
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
"""圆桌总控编排引擎 —— 共享类型、常量与纯函数。
|
||||
|
||||
把前端 ``useStep2Orchestration.ts`` 的编排循环(``runOrchestration`` /
|
||||
``runChainOrchestration``)忠实移植到后端。本文件只放:
|
||||
- ``RoundtableGateway`` 协议:引擎驱动「单轮 leader / seat / report」的抽象出口,
|
||||
把对 FastAPI ``Request`` / ``multi_agent.py`` 内部函数的依赖隔离到 Phase 3 的
|
||||
具体实现里(引擎本身纯逻辑、可用假网关单测);
|
||||
- ``LeaderTurn`` / ``SeatTurn`` / ``ReportResult`` / ``SeatRef`` 数据类;
|
||||
- 常量(MAX_CYCLES、各轮 prompt)与 chain 模式的 prompt 构造纯函数。
|
||||
|
||||
对应 ``frontend-web/docs/multi-agent-background-run-dev.md`` §Phase 2。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Protocol, runtime_checkable
|
||||
|
||||
# 编排循环最大轮次,与前端 roundtable-constants.ts MAX_CYCLES 对齐。
|
||||
MAX_CYCLES = 8
|
||||
|
||||
# recommend 模式每轮派活后、回到 leader 的「续轮」prompt(逐字对齐前端)。
|
||||
CONTINUE_PROMPT = (
|
||||
"各子智能体已就上一轮派活完成交付,请你结合最新结论判断是否仍需继续派活;"
|
||||
"若信息已足够,请直接输出最终方案并停止派活。"
|
||||
)
|
||||
|
||||
# chain 模式全链走完后、总控收口的 prompt(逐字对齐前端)。
|
||||
CHAIN_CLOSEOUT_PROMPT = (
|
||||
"各链条席位已按顺序完成发言,请你综合所有席位的交付,输出最终方案与结论。"
|
||||
"不要再派活、不要再向任何席位分配任务。"
|
||||
)
|
||||
|
||||
|
||||
# ── 数据类 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SeatRef:
|
||||
"""一个研讨席位(智能体)。chain 模式下 ``agents`` 的顺序即链条顺序。"""
|
||||
|
||||
agent_id: str
|
||||
name: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class LeaderTurn:
|
||||
"""总控一轮执行的归一化结果(由 gateway.run_leader 产出)。"""
|
||||
|
||||
final_text: str = ""
|
||||
# [(agent_id, task), ...];空 = 共识(不再派活)。
|
||||
dispatched: list[tuple[str, str]] = field(default_factory=list)
|
||||
# 命中澄清时的问题文本;非 None 即 clarification 分支。
|
||||
clarification: str | None = None
|
||||
|
||||
@property
|
||||
def is_clarification(self) -> bool:
|
||||
return bool(self.clarification)
|
||||
|
||||
@property
|
||||
def is_consensus(self) -> bool:
|
||||
return not self.dispatched and not self.is_clarification
|
||||
|
||||
|
||||
@dataclass
|
||||
class SeatTurn:
|
||||
"""某席位一轮交付的归一化结果(由 gateway.run_seat 产出)。"""
|
||||
|
||||
final_text: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class ReportResult:
|
||||
"""Step3 报告绘制结果(由 gateway.run_report 产出)。"""
|
||||
|
||||
html: str = ""
|
||||
summary: str | None = None
|
||||
model: str | None = None
|
||||
generated_at: str | None = None
|
||||
|
||||
|
||||
# ── 网关协议 ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class RoundtableGateway(Protocol):
|
||||
"""引擎驱动「单轮执行」的抽象出口。
|
||||
|
||||
Phase 3 提供具体实现(``LoopbackRoundtableGateway``):内部复用
|
||||
``multi_agent.py`` 的 ``_leader_run`` / ``_special_run`` / ``_create_thread_direct``
|
||||
等(它们依赖 ``Request``,由 Phase 3 的启动上下文注入)。引擎只面向本协议,
|
||||
因此可用假网关脱离真模型 / 真 LangGraph server 单测。
|
||||
|
||||
线程约定:席位 + 总控 thread 由调用方预先建好并通过 ``thread_ids`` 传入
|
||||
(key = agent_id / coordinator_name,value = thread_id);report thread 由引擎在
|
||||
进入报告阶段时通过 ``create_report_thread`` 现建。
|
||||
"""
|
||||
|
||||
async def run_leader(
|
||||
self,
|
||||
*,
|
||||
thread_ids: dict[str, str],
|
||||
coordinator_name: str,
|
||||
message: str,
|
||||
model: str | None,
|
||||
) -> LeaderTurn: ...
|
||||
|
||||
async def run_seat(
|
||||
self,
|
||||
*,
|
||||
thread_ids: dict[str, str],
|
||||
agent_id: str,
|
||||
task: str,
|
||||
model: str | None,
|
||||
) -> SeatTurn: ...
|
||||
|
||||
async def create_report_thread(self) -> str: ...
|
||||
|
||||
async def run_report(
|
||||
self,
|
||||
*,
|
||||
report_thread_id: str,
|
||||
prompt: str,
|
||||
model: str | None,
|
||||
) -> ReportResult: ...
|
||||
|
||||
|
||||
# ── chain 模式 prompt 构造(移植自前端 buildChainLeaderTask / pickChainTask)────
|
||||
|
||||
|
||||
def build_chain_leader_task(
|
||||
*,
|
||||
seed_message: str,
|
||||
position: int,
|
||||
total: int,
|
||||
seat_agent_id: str,
|
||||
seat_name: str,
|
||||
is_first: bool,
|
||||
) -> str:
|
||||
"""构造 chain 模式下「让总控只给当前席位派活」的 leader prompt。"""
|
||||
ordinal = f"{position + 1}/{total}"
|
||||
if is_first:
|
||||
return "\n".join(
|
||||
[
|
||||
"这是一次【按业务链条顺序】进行的多智能体圆桌研讨。任务背景如下:",
|
||||
seed_message,
|
||||
"",
|
||||
f"本次研讨严格按预设链条顺序进行,共 {total} 个席位,现在是第 {ordinal} 个席位。",
|
||||
f"请你作为总控,通过 agent_orchestration 技能**仅**向智能体「{seat_name}」"
|
||||
f"(agent_name: {seat_agent_id})派活,结合任务背景为它分配聚焦其职责的本轮任务。",
|
||||
"不要派给其他任何智能体,也不要自己直接作答或给出最终结论。",
|
||||
]
|
||||
)
|
||||
return "\n".join(
|
||||
[
|
||||
f"链条研讨继续,现在轮到第 {ordinal} 个席位。",
|
||||
f"请你作为总控,结合此前各席位已完成的交付,通过 agent_orchestration 技能**仅**向智能体"
|
||||
f"「{seat_name}」(agent_name: {seat_agent_id})派活,为它分配承接前序结论、聚焦其职责的本轮任务。",
|
||||
"不要派给其他任何智能体,也不要自己直接作答或给出最终结论。",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def pick_chain_task(
|
||||
dispatched: list[tuple[str, str]],
|
||||
leader_content: str,
|
||||
seat_agent_id: str,
|
||||
seat_name: str,
|
||||
) -> str:
|
||||
"""从 leader 终态里取「派给当前链条席位」的任务文本,带纠偏(移植自前端 pickChainTask)。
|
||||
|
||||
1) 命中 agent_id 完全一致的派活 → 用它的 task;
|
||||
2) 总控派了活但写偏 id → 仍用它给出的 task 文本(强制跑正确席位);
|
||||
3) 总控只写了说明没派活 → 用 leader 正文,再不行回退到模板任务。
|
||||
"""
|
||||
wanted = seat_agent_id.lower()
|
||||
for name, task in dispatched:
|
||||
if name.lower() == wanted and (task or "").strip():
|
||||
return task
|
||||
for _name, task in dispatched:
|
||||
if (task or "").strip():
|
||||
return task
|
||||
if (leader_content or "").strip():
|
||||
return (
|
||||
f"请你作为「{seat_name}」,基于以下总控说明与此前各席位的交付,"
|
||||
f"从你的专业职责出发给出你的分析与交付:\n{leader_content.strip()}"
|
||||
)
|
||||
return (
|
||||
f"请你作为「{seat_name}」,基于任务背景与此前各席位的交付,"
|
||||
"从你的专业职责出发给出你的分析与交付。"
|
||||
)
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
"""Create roundtable_jobs table.
|
||||
|
||||
Backend background-orchestration jobs for the roundtable-planning Step 2「后台挂起」
|
||||
feature: one row per server-side run of the leader→dispatch→consensus→report
|
||||
pipeline. Big JSON columns (dispatch_chain / thread_ids / chain) are LONGTEXT on
|
||||
MySQL (can exceed the 64 KB TEXT cap) and plain TEXT elsewhere — matching
|
||||
``PortableLongText`` on ``RoundtableJobRow``. ``create_all`` adds the table for
|
||||
brand-new DBs; this revision creates it on DBs that predate it.
|
||||
|
||||
Revision ID: 20260604_01
|
||||
Revises: 20260603_01
|
||||
Create Date: 2026-06-04
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy import inspect
|
||||
from sqlalchemy.dialects.mysql import LONGTEXT
|
||||
|
||||
|
||||
revision = "20260604_01"
|
||||
down_revision = "20260603_01"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _has_table(table_name: str) -> bool:
|
||||
inspector = inspect(op.get_bind())
|
||||
return table_name in inspector.get_table_names()
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
if _has_table("roundtable_jobs"):
|
||||
return
|
||||
|
||||
long_text = LONGTEXT() if op.get_bind().dialect.name == "mysql" else sa.Text()
|
||||
|
||||
op.create_table(
|
||||
"roundtable_jobs",
|
||||
sa.Column("id", sa.String(64), primary_key=True),
|
||||
sa.Column("draft_id", sa.String(64), nullable=True),
|
||||
sa.Column("user_id", sa.String(64), nullable=True),
|
||||
sa.Column("status", sa.String(32), nullable=False, server_default="queued"),
|
||||
sa.Column("phase", sa.String(32), nullable=False, server_default="initializing"),
|
||||
sa.Column("cycle", sa.Integer, nullable=False, server_default="0"),
|
||||
sa.Column("dispatch_chain", long_text, nullable=True),
|
||||
sa.Column("active_agent_id", sa.String(128), nullable=True),
|
||||
sa.Column("consensus_percentage", sa.Integer, nullable=False, server_default="0"),
|
||||
sa.Column("pending_clarification", sa.Text, nullable=True),
|
||||
sa.Column("thread_ids", long_text, nullable=True),
|
||||
sa.Column("coordinator_name", sa.String(128), nullable=True),
|
||||
sa.Column("orchestration_mode", sa.String(16), nullable=False, server_default="recommend"),
|
||||
sa.Column("chain", long_text, nullable=True),
|
||||
sa.Column("error", sa.Text, nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||
)
|
||||
op.create_index("ix_roundtable_jobs_draft_id", "roundtable_jobs", ["draft_id"])
|
||||
op.create_index("ix_roundtable_jobs_user_id", "roundtable_jobs", ["user_id"])
|
||||
op.create_index("ix_roundtable_jobs_status", "roundtable_jobs", ["status"])
|
||||
op.create_index("ix_roundtable_jobs_updated_at", "roundtable_jobs", ["updated_at"])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
if _has_table("roundtable_jobs"):
|
||||
op.drop_table("roundtable_jobs")
|
||||
+2
@@ -32,6 +32,7 @@ from deerflow.persistence.roundtable_drafts.model import (
|
||||
RoundtableDraftRow,
|
||||
RoundtableRecommendHistoryRow,
|
||||
)
|
||||
from deerflow.persistence.roundtable_jobs.model import RoundtableJobRow
|
||||
from deerflow.persistence.run.model import RunRow
|
||||
from deerflow.persistence.scheduled_tasks.model import (
|
||||
ScheduledTaskDeliveryProfileRow,
|
||||
@@ -61,6 +62,7 @@ __all__ = [
|
||||
"RecommendedQuestionRow",
|
||||
"RoundtableChainRow",
|
||||
"RoundtableDraftRow",
|
||||
"RoundtableJobRow",
|
||||
"RoundtableRecommendHistoryRow",
|
||||
"RunEventRow",
|
||||
"RunRow",
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
"""Roundtable background-job persistence.
|
||||
|
||||
Mirrors ``ai_writing_sessions``: exposes a store factory plus a process-level
|
||||
default-store singleton so the (harness-side) orchestration graph nodes can write
|
||||
progress without reaching into FastAPI ``request.app.state`` (harness → app imports
|
||||
are forbidden). app/gateway/deps.py registers the default store at startup.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from deerflow.persistence.roundtable_jobs.model import RoundtableJobRow
|
||||
from deerflow.persistence.roundtable_jobs.sql import RoundtableJobRepository
|
||||
|
||||
|
||||
def make_roundtable_job_store(session_factory) -> RoundtableJobRepository | None:
|
||||
if session_factory is None:
|
||||
return None
|
||||
return RoundtableJobRepository(session_factory)
|
||||
|
||||
|
||||
# ── 进程级默认 repo 单例(跨 app/harness 边界)──────────────────────────────────
|
||||
#
|
||||
# Phase 2 的圆桌编排图注册成 LangGraph Server assistant 后,节点跑在 harness 进程里,
|
||||
# 拿不到 FastAPI 的 request.app.state;harness → app 又禁止 import。
|
||||
# 写入:app/gateway/deps.py 创建 session_factory 后 register_default_store(...)。
|
||||
# 读取:图节点里 get_default_store(),None 表示未配置 DB(跳过写入即可)。
|
||||
_default_store: RoundtableJobRepository | None = None
|
||||
|
||||
|
||||
def register_default_store(store: RoundtableJobRepository | None) -> None:
|
||||
"""登记进程级默认圆桌作业 store(幂等,可覆盖;传 None 显式清理,主要给测试)。"""
|
||||
global _default_store
|
||||
_default_store = store
|
||||
|
||||
|
||||
def get_default_store() -> RoundtableJobRepository | None:
|
||||
"""返回进程级默认圆桌作业 store;未配置时为 None。"""
|
||||
return _default_store
|
||||
|
||||
|
||||
__all__ = [
|
||||
"RoundtableJobRow",
|
||||
"RoundtableJobRepository",
|
||||
"make_roundtable_job_store",
|
||||
"register_default_store",
|
||||
"get_default_store",
|
||||
]
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
"""ORM model for roundtable background-orchestration jobs.
|
||||
|
||||
A "job" = one **backend** run of the roundtable orchestration pipeline kicked off
|
||||
from Step 2「后台挂起」: it drives the leader→dispatch→sub-agents loop to consensus
|
||||
and then Step 3 report drawing, entirely server-side, surviving page refresh/close.
|
||||
|
||||
Bound 1:1 to a ``roundtable_drafts`` row (``draft_id``) so the history dropdown can
|
||||
show "this task is running" and the dispatch-chain modal can render live progress.
|
||||
|
||||
Big JSON columns (``dispatch_chain`` / ``thread_ids`` / ``chain``) are stored as
|
||||
serialized strings in ``PortableLongText`` (MySQL ``LONGTEXT``) — same approach as
|
||||
``ai_writing_sessions`` / ``roundtable_drafts`` — to avoid MySQL's 64 KB ``TEXT`` cap.
|
||||
|
||||
See ``frontend-web/docs/multi-agent-background-run-dev.md`` §2.5 for the field
|
||||
contract and §Phase 1 for the build steps.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import Integer, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from deerflow.persistence.base import Base
|
||||
from deerflow.persistence.types import BeijingDateTime, PortableLongText
|
||||
|
||||
|
||||
class RoundtableJobRow(Base):
|
||||
__tablename__ = "roundtable_jobs"
|
||||
|
||||
id: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
# The draft/session this job runs for. Indexed for "active job of draft" lookups.
|
||||
draft_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
|
||||
user_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
|
||||
# Job status machine (§2.1): queued / running / awaiting_input / done / error / cancelled.
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default="queued", index=True)
|
||||
# Fine-grained phase (§2.2): initializing / leader_thinking / dispatching /
|
||||
# consensus / report_drawing / report_done.
|
||||
phase: Mapped[str] = mapped_column(String(32), nullable=False, default="initializing")
|
||||
# Current orchestration cycle (0..MAX_CYCLES).
|
||||
cycle: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
# Dispatch chain nodes (§2.3): JSON array of
|
||||
# { agentId, name, avatarType, order, state, lastSpokeCycle? }.
|
||||
dispatch_chain: Mapped[str | None] = mapped_column(PortableLongText, nullable=True)
|
||||
# Currently-speaking seat agent_id (null = coordinator / none).
|
||||
active_agent_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
consensus_percentage: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
# When status=awaiting_input: the coordinator's clarification question text.
|
||||
pending_clarification: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
# ThreadIdMap: JSON object { "<agent_id>": "<thread_id>", ... }.
|
||||
thread_ids: Mapped[str | None] = mapped_column(PortableLongText, nullable=True)
|
||||
coordinator_name: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
# "recommend"(总控自由派活)| "chain"(按业务链条顺序派活).
|
||||
orchestration_mode: Mapped[str] = mapped_column(String(16), nullable=False, default="recommend")
|
||||
# chain 模式来源链条快照:JSON object { id, title }(recommend 模式为 null).
|
||||
chain: Mapped[str | None] = mapped_column(PortableLongText, nullable=True)
|
||||
# Terminal error detail when status=error.
|
||||
error: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
# 时间列必须用 BeijingDateTime(项目规范,与 ai_writing_sessions / roundtable_drafts 对齐)。
|
||||
created_at: Mapped[datetime] = mapped_column(BeijingDateTime(), nullable=False, default=lambda: datetime.now(UTC))
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
BeijingDateTime(),
|
||||
nullable=False,
|
||||
default=lambda: datetime.now(UTC),
|
||||
onupdate=lambda: datetime.now(UTC),
|
||||
)
|
||||
+276
@@ -0,0 +1,276 @@
|
||||
"""SQLAlchemy-backed roundtable background-job storage.
|
||||
|
||||
JSON columns (``dispatch_chain`` / ``thread_ids`` / ``chain``) are stored as
|
||||
serialized strings in ``PortableLongText`` and round-tripped here with
|
||||
``json.dumps`` / ``json.loads`` — same approach as ``ai_writing_sessions`` /
|
||||
``roundtable_drafts``.
|
||||
|
||||
User isolation mirrors ``ai_writing_sessions``: methods take ``user_id`` defaulting
|
||||
to ``AUTO`` (resolved from the run context) so backend graph nodes can write without
|
||||
threading a user id through, while gateway routes pass it explicitly.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import delete, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from deerflow.persistence.roundtable_jobs.model import RoundtableJobRow
|
||||
from deerflow.runtime.user_context import AUTO, _AutoSentinel, resolve_user_id
|
||||
|
||||
_UNSET = object()
|
||||
|
||||
# 终态:列表/清理判定用。
|
||||
TERMINAL_STATUSES = ("done", "error", "cancelled")
|
||||
|
||||
|
||||
def _loads(value: Any) -> Any:
|
||||
if not isinstance(value, str):
|
||||
return value
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
return json.loads(value)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _dumps(value: Any) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
return json.dumps(value, ensure_ascii=False)
|
||||
|
||||
|
||||
class RoundtableJobRepository:
|
||||
def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
|
||||
self._sf = session_factory
|
||||
|
||||
@staticmethod
|
||||
def _row_to_dict(row: RoundtableJobRow) -> dict[str, Any]:
|
||||
d = row.to_dict()
|
||||
for k in ("created_at", "updated_at"):
|
||||
if isinstance(d.get(k), datetime):
|
||||
d[k] = d[k].isoformat()
|
||||
for k in ("dispatch_chain", "thread_ids", "chain"):
|
||||
d[k] = _loads(d.get(k))
|
||||
return d
|
||||
|
||||
# ── create ────────────────────────────────────────────────────────────
|
||||
|
||||
async def create(
|
||||
self,
|
||||
*,
|
||||
id: str,
|
||||
draft_id: str | None = None,
|
||||
user_id: str | None | _AutoSentinel = AUTO,
|
||||
orchestration_mode: str = "recommend",
|
||||
coordinator_name: str | None = None,
|
||||
thread_ids: dict[str, str] | None = None,
|
||||
chain: dict[str, Any] | None = None,
|
||||
dispatch_chain: list[dict[str, Any]] | None = None,
|
||||
status: str = "queued",
|
||||
phase: str = "initializing",
|
||||
) -> dict[str, Any]:
|
||||
resolved_user_id = resolve_user_id(user_id, method_name="RoundtableJobRepository.create")
|
||||
now = datetime.now(UTC)
|
||||
row = RoundtableJobRow(
|
||||
id=id,
|
||||
draft_id=draft_id,
|
||||
user_id=resolved_user_id,
|
||||
status=status,
|
||||
phase=phase,
|
||||
cycle=0,
|
||||
dispatch_chain=_dumps(dispatch_chain),
|
||||
active_agent_id=None,
|
||||
consensus_percentage=0,
|
||||
pending_clarification=None,
|
||||
thread_ids=_dumps(thread_ids),
|
||||
coordinator_name=coordinator_name,
|
||||
orchestration_mode=orchestration_mode,
|
||||
chain=_dumps(chain),
|
||||
error=None,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
async with self._sf() as session:
|
||||
session.add(row)
|
||||
await session.commit()
|
||||
await session.refresh(row)
|
||||
return self._row_to_dict(row)
|
||||
|
||||
# ── update progress ─────────────────────────────────────────────────────
|
||||
|
||||
async def update_progress(
|
||||
self,
|
||||
job_id: str,
|
||||
*,
|
||||
user_id: str | None | _AutoSentinel = AUTO,
|
||||
status=_UNSET,
|
||||
phase=_UNSET,
|
||||
cycle=_UNSET,
|
||||
dispatch_chain=_UNSET,
|
||||
active_agent_id=_UNSET,
|
||||
consensus_percentage=_UNSET,
|
||||
pending_clarification=_UNSET,
|
||||
thread_ids=_UNSET,
|
||||
coordinator_name=_UNSET,
|
||||
error=_UNSET,
|
||||
) -> dict[str, Any] | None:
|
||||
resolved_user_id = resolve_user_id(user_id, method_name="RoundtableJobRepository.update_progress")
|
||||
async with self._sf() as session:
|
||||
row = await session.get(RoundtableJobRow, job_id)
|
||||
if row is None:
|
||||
return None
|
||||
if resolved_user_id is not None and row.user_id != resolved_user_id:
|
||||
return None
|
||||
if status is not _UNSET:
|
||||
row.status = status
|
||||
if phase is not _UNSET:
|
||||
row.phase = phase
|
||||
if cycle is not _UNSET:
|
||||
row.cycle = int(cycle)
|
||||
if dispatch_chain is not _UNSET:
|
||||
row.dispatch_chain = _dumps(dispatch_chain)
|
||||
if active_agent_id is not _UNSET:
|
||||
row.active_agent_id = active_agent_id
|
||||
if consensus_percentage is not _UNSET:
|
||||
row.consensus_percentage = int(consensus_percentage)
|
||||
if pending_clarification is not _UNSET:
|
||||
row.pending_clarification = pending_clarification
|
||||
if thread_ids is not _UNSET:
|
||||
row.thread_ids = _dumps(thread_ids)
|
||||
if coordinator_name is not _UNSET:
|
||||
row.coordinator_name = coordinator_name
|
||||
if error is not _UNSET:
|
||||
row.error = error
|
||||
row.updated_at = datetime.now(UTC)
|
||||
await session.commit()
|
||||
await session.refresh(row)
|
||||
return self._row_to_dict(row)
|
||||
|
||||
# ── read ────────────────────────────────────────────────────────────────
|
||||
|
||||
async def get(
|
||||
self,
|
||||
job_id: str,
|
||||
*,
|
||||
user_id: str | None | _AutoSentinel = AUTO,
|
||||
) -> dict[str, Any] | None:
|
||||
resolved_user_id = resolve_user_id(user_id, method_name="RoundtableJobRepository.get")
|
||||
async with self._sf() as session:
|
||||
row = await session.get(RoundtableJobRow, job_id)
|
||||
if row is None:
|
||||
return None
|
||||
if resolved_user_id is not None and row.user_id != resolved_user_id:
|
||||
return None
|
||||
return self._row_to_dict(row)
|
||||
|
||||
async def get_by_draft(
|
||||
self,
|
||||
draft_id: str,
|
||||
*,
|
||||
user_id: str | None | _AutoSentinel = AUTO,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Return the most-recently-updated job for a draft (or None)."""
|
||||
resolved_user_id = resolve_user_id(user_id, method_name="RoundtableJobRepository.get_by_draft")
|
||||
stmt = select(RoundtableJobRow).where(RoundtableJobRow.draft_id == draft_id)
|
||||
if resolved_user_id is not None:
|
||||
stmt = stmt.where(RoundtableJobRow.user_id == resolved_user_id)
|
||||
stmt = stmt.order_by(RoundtableJobRow.updated_at.desc()).limit(1)
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
row = result.scalars().first()
|
||||
return self._row_to_dict(row) if row is not None else None
|
||||
|
||||
async def list_by_user(
|
||||
self,
|
||||
*,
|
||||
user_id: str | None | _AutoSentinel = AUTO,
|
||||
limit: int = 50,
|
||||
) -> list[dict[str, Any]]:
|
||||
resolved_user_id = resolve_user_id(user_id, method_name="RoundtableJobRepository.list_by_user")
|
||||
stmt = select(RoundtableJobRow)
|
||||
if resolved_user_id is not None:
|
||||
stmt = stmt.where(RoundtableJobRow.user_id == resolved_user_id)
|
||||
stmt = stmt.order_by(RoundtableJobRow.updated_at.desc()).limit(limit)
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
return [self._row_to_dict(r) for r in result.scalars()]
|
||||
|
||||
async def status_map_by_user(
|
||||
self,
|
||||
user_id: str,
|
||||
*,
|
||||
limit: int = 200,
|
||||
) -> dict[str, dict[str, str]]:
|
||||
"""``{draft_id: {"jobId": ..., "status": ...}}`` for the latest job per draft.
|
||||
|
||||
Drives the history dropdown's per-draft status badge (Phase 6). Walks jobs
|
||||
newest-first and keeps the first (latest) one seen for each draft_id.
|
||||
"""
|
||||
stmt = (
|
||||
select(RoundtableJobRow.id, RoundtableJobRow.draft_id, RoundtableJobRow.status)
|
||||
.where(RoundtableJobRow.user_id == user_id)
|
||||
.where(RoundtableJobRow.draft_id.is_not(None))
|
||||
.order_by(RoundtableJobRow.updated_at.desc())
|
||||
.limit(limit)
|
||||
)
|
||||
out: dict[str, dict[str, str]] = {}
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
for job_id, draft_id, status in result.all():
|
||||
if draft_id is None or draft_id in out:
|
||||
continue
|
||||
out[draft_id] = {"jobId": job_id, "status": status}
|
||||
return out
|
||||
|
||||
# ── delete / cleanup ─────────────────────────────────────────────────────
|
||||
|
||||
async def delete(
|
||||
self,
|
||||
job_id: str,
|
||||
*,
|
||||
user_id: str | None | _AutoSentinel = AUTO,
|
||||
) -> bool:
|
||||
resolved_user_id = resolve_user_id(user_id, method_name="RoundtableJobRepository.delete")
|
||||
async with self._sf() as session:
|
||||
row = await session.get(RoundtableJobRow, job_id)
|
||||
if row is None:
|
||||
return False
|
||||
if resolved_user_id is not None and row.user_id != resolved_user_id:
|
||||
return False
|
||||
await session.delete(row)
|
||||
await session.commit()
|
||||
return True
|
||||
|
||||
async def list_older_than(
|
||||
self,
|
||||
cutoff: datetime,
|
||||
*,
|
||||
only_finished: bool = False,
|
||||
limit: int = 500,
|
||||
) -> list[str]:
|
||||
"""列出 updated_at 早于 cutoff 的作业 id(最多 limit 个),供清理任务用。
|
||||
|
||||
only_finished=True 时只列终态(done/error/cancelled),避免清掉还在跑的作业。
|
||||
"""
|
||||
stmt = select(RoundtableJobRow.id).where(RoundtableJobRow.updated_at < cutoff)
|
||||
if only_finished:
|
||||
stmt = stmt.where(RoundtableJobRow.status.in_(TERMINAL_STATUSES))
|
||||
stmt = stmt.order_by(RoundtableJobRow.updated_at.asc()).limit(limit)
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
return [row[0] for row in result.all()]
|
||||
|
||||
async def delete_by_ids(self, job_ids: list[str]) -> int:
|
||||
if not job_ids:
|
||||
return 0
|
||||
stmt = delete(RoundtableJobRow).where(RoundtableJobRow.id.in_(job_ids))
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
await session.commit()
|
||||
return int(result.rowcount or 0)
|
||||
Reference in new issue
Block a user