feat(position-roundtable): add standalone position collaboration

This commit is contained in:
fengxiangdebaozi committed 2026-07-21 17:50:24 +08:00
1 parent b93b82fcaf
commit 85e119db08
22 files changed
+3494 -201

No files matched your search

@@ -53,9 +53,10 @@ from app.gateway.routers import (
notifications,
open_3qfx,
open_chat,
parallel_agent_tasks,
parallel_agents,
positions,
parallel_agent_tasks,
parallel_agents,
position_roundtable,
positions,
public_config,
public_embed,
public_leaderboard,
@@ -1443,8 +1444,11 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
# Step3 流程图结构化抽取 + 校验 (SSE) at /api/flow-extract
app.include_router(flow_extract.router)
# Roundtable-planning business chains at /api/roundtable-chains
app.include_router(roundtable_chains.router)
# Roundtable-planning business chains at /api/roundtable-chains
app.include_router(roundtable_chains.router)
# 岗位协同独立会话 / 节点状态(不使用原圆桌总控或后台作业)
app.include_router(position_roundtable.router)
# Global business ? agent / chain mapping at /api/business-mapping
app.include_router(business_mapping.router)
@@ -255,9 +255,15 @@ async def langgraph_runtime(app: FastAPI) -> AsyncGenerator[None, None]:
app.state.roundtable_draft_share_store = make_roundtable_draft_share_store(sf)
from deerflow.persistence.roundtable_chains import make_roundtable_chain_store
app.state.roundtable_chain_store = make_roundtable_chain_store(sf)
from deerflow.persistence.roundtable_chains import make_roundtable_chain_store
app.state.roundtable_chain_store = make_roundtable_chain_store(sf)
# 独立的岗位协同 Session / Node 存储。它只索引业务流程状态,真实消息和
# 文件仍复用 LangGraph thread/checkpoint 与现有 artifact API。
from deerflow.persistence.position_roundtable import make_position_roundtable_store
app.state.position_roundtable_store = make_position_roundtable_store(sf)
from deerflow.persistence.business_mapping import make_business_mapping_store
@@ -0,0 +1,563 @@
"""API for the standalone position-collaboration workspace.
Unlike the existing multi-agent roundtable, this feature has no coordinator and
no background roundtable job. The API only persists the task/intent/chain
snapshot and indexes one direct-agent node per business-chain seat. Actual chat
messages and artifacts stay in the established LangGraph thread stores.
"""
from __future__ import annotations
import asyncio
from pathlib import Path
from typing import Any
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel, Field
from app.gateway.path_utils import aresolve_thread_virtual_path
from deerflow.runtime.user_context import get_effective_user_id
router = APIRouter(prefix="/api/position-roundtable", tags=["position-roundtable"])
NODE_STATUSES = {"locked", "ready", "running", "done", "stale", "error"}
_HANDOFF_TEXT_BUDGET = 12_000
_MAX_INLINE_ARTIFACTS_PER_NODE = 4
_MAX_INLINE_ARTIFACT_CHARS = 1_800
_TEXT_ARTIFACT_SUFFIXES = {
".csv",
".json",
".log",
".md",
".markdown",
".rst",
".txt",
".xml",
".yaml",
".yml",
}
class NodeResponse(BaseModel):
id: str
session_id: str
node_key: str
stage_index: int
seat_index: int
agent_id: str
position_id: str | None = None
thread_id: str | None = None
status: str
latest_answer: str | None = None
artifact_manifest: list[dict[str, Any]] = Field(default_factory=list)
revision: int = 0
upstream_revision: dict[str, Any] | None = None
created_at: str | None = None
updated_at: str | None = None
class SessionResponse(BaseModel):
id: str
external_task_id: str | None = None
task_snapshot: dict[str, Any] = Field(default_factory=dict)
chain_id: str | None = None
chain_snapshot: dict[str, Any] | None = None
intent_thread_id: str | None = None
intent_snapshot: dict[str, Any] | None = None
status: str
created_at: str | None = None
updated_at: str | None = None
class SessionDetailResponse(SessionResponse):
nodes: list[NodeResponse] = Field(default_factory=list)
class SessionCreateRequest(BaseModel):
external_task_id: str | None = Field(default=None, max_length=128)
task_snapshot: dict[str, Any] = Field(default_factory=dict)
class TaskSnapshotUpdateRequest(BaseModel):
task_snapshot: dict[str, Any] = Field(default_factory=dict)
class IntentUpdateRequest(BaseModel):
intent_thread_id: str | None = Field(default=None, max_length=128)
intent_snapshot: dict[str, Any] | None = None
class ActivateRequest(BaseModel):
chain_id: str = Field(min_length=1, max_length=64)
class NodeThreadRequest(BaseModel):
thread_id: str = Field(min_length=1, max_length=128)
class CompleteTurnRequest(BaseModel):
latest_answer: str = Field(default="", max_length=500_000)
artifact_manifest: list[dict[str, Any]] = Field(default_factory=list)
upstream_revision: dict[str, Any] | None = None
def _current_user_id(request: Request) -> str:
user = getattr(request.state, "user", None)
return str(user.id) if user is not None else get_effective_user_id()
def _get_store(request: Request):
store = getattr(request.app.state, "position_roundtable_store", None)
if store is None:
raise HTTPException(status_code=503, detail="Position roundtable store not available")
return store
def _get_chain_store(request: Request):
store = getattr(request.app.state, "roundtable_chain_store", None)
if store is None:
raise HTTPException(status_code=503, detail="Business chain store not available")
return store
async def _require_writable_session(
request: Request, session_id: str
) -> tuple[Any, str, dict[str, Any]]:
"""Load a Session that can still accept task, intent, or node updates."""
store = _get_store(request)
user_id = _current_user_id(request)
session = await store.get_session(session_id, user_id)
if session is None:
raise HTTPException(status_code=404, detail="Position roundtable session not found")
if session.get("status") == "archived":
raise HTTPException(status_code=409, detail="该岗位协同会话已归档,仅可查看历史记录")
return store, user_id, session
def _project_session(row: dict[str, Any]) -> SessionResponse:
return SessionResponse(**row)
def _project_node(row: dict[str, Any]) -> NodeResponse:
return NodeResponse(**row)
async def _load_detail(request: Request, session_id: str) -> SessionDetailResponse:
store = _get_store(request)
user_id = _current_user_id(request)
row = await store.get_session(session_id, user_id)
if row is None:
raise HTTPException(status_code=404, detail="Position roundtable session not found")
nodes = await store.list_nodes(session_id, user_id)
return SessionDetailResponse(**row, nodes=[_project_node(node) for node in nodes or []])
def _chain_nodes(chain: dict[str, Any]) -> list[dict[str, Any]]:
seats = chain.get("seats") if isinstance(chain.get("seats"), list) else []
if not seats:
raise HTTPException(status_code=400, detail="业务链条没有可执行的智能体席位")
seat_by_agent_id = {str(seat.get("agent_id")): seat for seat in seats if seat.get("agent_id")}
if len(seat_by_agent_id) != len(seats):
raise HTTPException(status_code=400, detail="业务链条包含无效或重复的智能体席位")
raw_stages = chain.get("stages")
stages: list[list[str]]
if isinstance(raw_stages, list) and raw_stages:
stages = [[str(agent_id) for agent_id in stage] for stage in raw_stages if isinstance(stage, list)]
else:
stages = [[str(seat["agent_id"])] for seat in seats]
if not stages or any(not stage for stage in stages):
raise HTTPException(status_code=400, detail="业务链条阶段配置无效")
result: list[dict[str, Any]] = []
for stage_index, stage in enumerate(stages):
for seat_index, agent_id in enumerate(stage):
seat = seat_by_agent_id.get(agent_id)
if seat is None:
raise HTTPException(status_code=400, detail=f"业务链条阶段包含不存在的席位: {agent_id}")
position_id = seat.get("position_id")
if not isinstance(position_id, str) or not position_id.strip():
raise HTTPException(
status_code=400,
detail=f"智能体「{seat.get('name') or agent_id}」尚未配置岗位,请先从岗位协同入口配置",
)
result.append(
{
"node_key": f"stage-{stage_index + 1}-seat-{seat_index + 1}-{agent_id}",
"stage_index": stage_index,
"seat_index": seat_index,
"agent_id": agent_id,
"position_id": position_id.strip(),
"status": "ready" if stage_index == 0 else "locked",
}
)
return result
def _truncate_text(value: Any, limit: int) -> str:
if limit <= 0:
return ""
text = value if isinstance(value, str) else str(value or "")
if len(text) <= limit:
return text
return f"{text[:limit]}\n…(已按交接上下文长度截断)"
def _artifact_refs(artifacts: Any) -> list[dict[str, Any]]:
if not isinstance(artifacts, list):
return []
refs: list[dict[str, Any]] = []
for artifact in artifacts[:20]:
if not isinstance(artifact, dict):
continue
refs.append(
{
"name": artifact.get("name") or artifact.get("filename") or "未命名产物",
"path": artifact.get("path") or artifact.get("artifact_url") or "",
"mime_type": artifact.get("mimeType") or artifact.get("mime_type") or None,
}
)
return refs
def _is_inline_text_artifact(artifact: dict[str, Any]) -> bool:
"""Return whether a listed output is safe and useful to pass as text."""
mime_type = artifact.get("mime_type")
if isinstance(mime_type, str) and mime_type.lower().startswith("text/"):
return True
path = artifact.get("path")
return isinstance(path, str) and Path(path).suffix.lower() in _TEXT_ARTIFACT_SUFFIXES
def _read_text_excerpt(path: Path, max_chars: int) -> tuple[str, bool] | None:
"""Read one bounded UTF-8 text artifact without loading the whole file."""
if max_chars <= 0:
return None
# Four bytes per UTF-8 code point is enough to obtain the requested
# character-sized excerpt without a potentially unbounded file read.
with path.open("rb") as file:
raw = file.read(max_chars * 4 + 1)
if b"\x00" in raw:
return None
try:
text = raw.decode("utf-8")
except UnicodeDecodeError as error:
if len(raw) == max_chars * 4 + 1 and error.start >= len(raw) - 4:
text = raw[: error.start].decode("utf-8")
else:
# Generated artifacts are expected to be UTF-8. Keep a non-UTF-8
# output as a reference only instead of corrupting agent context.
return None
truncated = len(raw) > max_chars * 4 or len(text) > max_chars
return _truncate_text(text, max_chars), truncated
async def _artifact_refs_with_content(
thread_id: str | None, artifacts: Any, text_budget: int
) -> tuple[list[dict[str, Any]], int]:
"""Attach bounded excerpts of text outputs, retaining binary files as refs.
Paths are always resolved against the upstream node's own thread. This is
deliberate: an artifact manifest is client-supplied metadata, so it must
never be allowed to select another thread's user-data directory.
"""
refs = _artifact_refs(artifacts)
if not thread_id or text_budget <= 0:
return refs, 0
consumed = 0
inline_count = 0
for ref in refs:
if inline_count >= _MAX_INLINE_ARTIFACTS_PER_NODE:
break
if not _is_inline_text_artifact(ref):
continue
virtual_path = ref.get("path")
if not isinstance(virtual_path, str):
continue
normalized_path = virtual_path.replace("\\", "/").lstrip("/")
if not normalized_path.startswith("mnt/user-data/outputs/"):
continue
available = text_budget - consumed
if available <= 0:
break
excerpt_limit = min(_MAX_INLINE_ARTIFACT_CHARS, available)
try:
actual_path = await aresolve_thread_virtual_path(thread_id, normalized_path)
if not await asyncio.to_thread(actual_path.is_file):
continue
excerpt = await asyncio.to_thread(_read_text_excerpt, actual_path, excerpt_limit)
except (HTTPException, OSError):
# The file may have been removed after the manifest was stored.
# Keep its metadata so the UI still shows the original output.
continue
if excerpt is None:
continue
content, truncated = excerpt
ref["content"] = content
ref["content_truncated"] = truncated
consumed += len(content)
inline_count += 1
return refs, consumed
async def _handoff_context(request: Request, session_id: str, node_key: str) -> dict[str, Any]:
"""Construct bounded, deterministic hidden context for one direct-agent turn."""
store = _get_store(request)
user_id = _current_user_id(request)
session = await store.get_session(session_id, user_id)
nodes = await store.list_nodes(session_id, user_id)
if session is None or nodes is None:
raise HTTPException(status_code=404, detail="Position roundtable session not found")
if session.get("status") == "archived":
raise HTTPException(status_code=409, detail="该岗位协同会话已归档,仅可查看历史记录")
current = next((node for node in nodes if node["node_key"] == node_key), None)
if current is None:
raise HTTPException(status_code=404, detail="Position roundtable node not found")
if current["status"] == "locked":
raise HTTPException(status_code=409, detail="上游节点尚未完成,当前节点未解锁")
# Same-stage nodes are intentionally excluded. The business chain only
# hands off completed previous stages, in stage/seat order.
remaining = _HANDOFF_TEXT_BUDGET
upstream_candidates = [
node
for node in nodes
if node["stage_index"] < current["stage_index"]
and node["status"] in {"done", "stale"}
]
upstream_nodes: list[dict[str, Any]] = []
for index, node in enumerate(upstream_candidates):
candidates_left = len(upstream_candidates) - index
per_node_limit = min(2_800, max(0, (remaining // candidates_left) * 2 // 3))
answer = _truncate_text(node.get("latest_answer"), per_node_limit)
remaining -= len(answer)
artifact_budget = min(
_MAX_INLINE_ARTIFACT_CHARS,
max(0, remaining // candidates_left),
)
artifacts, consumed = await _artifact_refs_with_content(
node.get("thread_id"), node.get("artifact_manifest"), artifact_budget
)
remaining -= consumed
upstream_nodes.append(
{
"node_key": node["node_key"],
"agent_id": node["agent_id"],
"position_id": node.get("position_id"),
"revision": node.get("revision", 0),
"latest_answer": answer,
"artifacts": artifacts,
}
)
if remaining <= 0:
break
return {
"kind": "position_roundtable_handoff",
"task": session.get("task_snapshot") or {},
"intent": session.get("intent_snapshot") or {},
"current_node": {
"node_key": current["node_key"],
"agent_id": current["agent_id"],
"position_id": current.get("position_id"),
"stage_index": current["stage_index"],
"seat_index": current["seat_index"],
},
"upstream_nodes": upstream_nodes,
"upstream_revision": {
node["node_key"]: node.get("revision", 0) for node in upstream_nodes
},
}
@router.get("/sessions", response_model=list[SessionResponse])
async def list_sessions(request: Request, external_task_id: str | None = None) -> list[SessionResponse]:
rows = await _get_store(request).list_sessions(
_current_user_id(request), external_task_id=external_task_id
)
return [_project_session(row) for row in rows]
@router.post("/sessions", response_model=SessionResponse, status_code=201)
async def create_session(request: Request, body: SessionCreateRequest) -> SessionResponse:
row = await _get_store(request).create_session(
_current_user_id(request),
external_task_id=body.external_task_id,
task_snapshot=body.task_snapshot,
)
return _project_session(row)
@router.get("/sessions/{session_id}", response_model=SessionDetailResponse)
async def get_session(request: Request, session_id: str) -> SessionDetailResponse:
return await _load_detail(request, session_id)
@router.put("/sessions/{session_id}/task", response_model=SessionResponse)
async def update_task_snapshot(
request: Request, session_id: str, body: TaskSnapshotUpdateRequest
) -> SessionResponse:
store, user_id, _ = await _require_writable_session(request, session_id)
row = await store.update_session(session_id, user_id, task_snapshot=body.task_snapshot)
if row is None:
raise HTTPException(status_code=404, detail="Position roundtable session not found")
return _project_session(row)
@router.put("/sessions/{session_id}/intent", response_model=SessionResponse)
async def update_intent_snapshot(
request: Request, session_id: str, body: IntentUpdateRequest
) -> SessionResponse:
store, user_id, _ = await _require_writable_session(request, session_id)
row = await store.update_session(
session_id,
user_id,
intent_thread_id=body.intent_thread_id,
intent_snapshot=body.intent_snapshot,
)
if row is None:
raise HTTPException(status_code=404, detail="Position roundtable session not found")
return _project_session(row)
@router.post("/sessions/{session_id}/activate", response_model=SessionDetailResponse)
async def activate_session(
request: Request, session_id: str, body: ActivateRequest
) -> SessionDetailResponse:
store, user_id, current = await _require_writable_session(request, session_id)
if not current.get("intent_snapshot"):
raise HTTPException(status_code=400, detail="请先完成并保存任务意图")
chain = await _get_chain_store(request).get_chain(
body.chain_id,
user_id,
is_admin=getattr(getattr(request.state, "user", None), "system_role", None) == "admin",
)
if chain is None:
raise HTTPException(status_code=404, detail="业务链条不存在或无权访问")
nodes = _chain_nodes(chain)
activated = await store.activate_session(
session_id,
user_id,
chain_id=body.chain_id,
chain_snapshot=chain,
nodes=nodes,
)
if activated is None:
raise HTTPException(status_code=404, detail="Position roundtable session not found")
row, node_rows = activated
return SessionDetailResponse(**row, nodes=[_project_node(node) for node in node_rows])
@router.post("/sessions/{session_id}/archive", response_model=SessionResponse)
async def archive_session(request: Request, session_id: str) -> SessionResponse:
row = await _get_store(request).archive_session(session_id, _current_user_id(request))
if row is None:
raise HTTPException(status_code=404, detail="Position roundtable session not found")
return _project_session(row)
@router.get("/sessions/{session_id}/nodes/{node_key}", response_model=NodeResponse)
async def get_node(request: Request, session_id: str, node_key: str) -> NodeResponse:
row = await _get_store(request).get_node(session_id, node_key, _current_user_id(request))
if row is None:
raise HTTPException(status_code=404, detail="Position roundtable node not found")
return _project_node(row)
@router.post("/sessions/{session_id}/nodes/{node_key}/thread", response_model=NodeResponse)
async def bind_node_thread(
request: Request, session_id: str, node_key: str, body: NodeThreadRequest
) -> NodeResponse:
store, user_id, _ = await _require_writable_session(request, session_id)
current = await store.get_node(session_id, node_key, user_id)
if current is None:
raise HTTPException(status_code=404, detail="Position roundtable node not found")
if current["status"] == "locked":
raise HTTPException(status_code=409, detail="上游节点尚未完成,当前节点未解锁")
if current.get("thread_id") and current["thread_id"] != body.thread_id:
raise HTTPException(status_code=409, detail="该节点已绑定另一条对话线程")
row = await store.update_node(
session_id,
node_key,
user_id,
thread_id=body.thread_id,
status="running" if current.get("status") == "ready" else current.get("status", "locked"),
)
return _project_node(row)
@router.post("/sessions/{session_id}/nodes/{node_key}/context")
async def build_node_context(request: Request, session_id: str, node_key: str) -> dict[str, Any]:
"""Return the bounded hidden task/intent/upstream context for a node turn."""
return await _handoff_context(request, session_id, node_key)
@router.post("/sessions/{session_id}/nodes/{node_key}/complete-turn", response_model=NodeResponse)
async def complete_node_turn(
request: Request, session_id: str, node_key: str, body: CompleteTurnRequest
) -> NodeResponse:
store, user_id, _ = await _require_writable_session(request, session_id)
node = await store.get_node(session_id, node_key, user_id)
if node is None:
raise HTTPException(status_code=404, detail="Position roundtable node not found")
if node["status"] == "locked":
raise HTTPException(status_code=409, detail="上游节点尚未完成,当前节点未解锁")
row = await store.update_node(
session_id,
node_key,
user_id,
status="done",
latest_answer=body.latest_answer,
artifact_manifest=body.artifact_manifest,
upstream_revision=body.upstream_revision,
increment_revision=True,
)
if row is None:
raise HTTPException(status_code=404, detail="Position roundtable node not found")
# A node has no coordinator. Its completion alone drives the frozen chain:
# all parallel seats in the current stage must finish before the next stage
# is made writable. Re-answering an already completed upstream seat keeps
# downstream records for audit but marks them stale so they must be
# refreshed against the new handoff context.
nodes = await store.list_nodes(session_id, user_id)
if nodes is None:
raise HTTPException(status_code=404, detail="Position roundtable session not found")
if node.get("revision", 0) > 0:
for downstream in nodes:
if (
downstream["stage_index"] > row["stage_index"]
and downstream["status"] in {"ready", "running", "done", "stale"}
):
await store.update_node(
session_id,
downstream["node_key"],
user_id,
status="stale",
)
nodes = await store.list_nodes(session_id, user_id) or []
current_stage = [item for item in nodes if item["stage_index"] == row["stage_index"]]
later_stages = sorted(
{item["stage_index"] for item in nodes if item["stage_index"] > row["stage_index"]}
)
if current_stage and all(item["status"] == "done" for item in current_stage) and later_stages:
next_stage = later_stages[0]
for next_node in nodes:
if next_node["stage_index"] == next_stage and next_node["status"] == "locked":
await store.update_node(
session_id,
next_node["node_key"],
user_id,
status="ready",
)
return _project_node(row)
@router.get("/sessions/{session_id}/results", response_model=list[NodeResponse])
async def list_results(request: Request, session_id: str) -> list[NodeResponse]:
rows = await _get_store(request).list_results(session_id, _current_user_id(request))
if rows is None:
raise HTTPException(status_code=404, detail="Position roundtable session not found")
return [_project_node(row) for row in rows]
@@ -62,6 +62,9 @@ class ChainSeatSchema(BaseModel):
# 持久化,故无需迁移;仅需在此 schema 显式声明,否则 model_dump() 会剥掉它。非法值在运行期
# 被 _SEAT_MODE_PARAMS.get() 安全忽略(回退作业级),故此处只约束长度、不强校验取值。
seat_mode: str | None = Field(default=None, max_length=16)
# 岗位协同专用的席位岗位归属。字段保存在既有 seats JSON 中,普通圆桌编排
# 忽略它;显式声明可确保 Pydantic 在 create/update 的 model_dump() 时不剥掉。
position_id: str | None = Field(default=None, max_length=64)
class ChainResponse(BaseModel):