代码提交

This commit is contained in:
董宏凯 committed 2026-07-24 10:33:28 +08:00
1 parent f49def09ea
commit 45df500a9c
55 files changed
+3390 -461

No files matched your search

@@ -2,8 +2,10 @@
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.
snapshot and indexes one direct-agent node per business-chain seat. LangGraph
remains the live execution source, while SQL also stores recovery copies of
all conversations, drafts and delivered artifact bodies so checkpoint-volume
replacement cannot turn an existing collaboration history into a blank page.
"""
from __future__ import annotations
@@ -25,6 +27,11 @@ NODE_STATUSES = {"locked", "ready", "running", "done", "stale", "rejected", "err
_HANDOFF_TEXT_BUDGET = 12_000
_MAX_INLINE_ARTIFACTS_PER_NODE = 4
_MAX_INLINE_ARTIFACT_CHARS = 1_800
# The handoff prompt remains intentionally small, but the recovery copy stored
# in SQL must retain a complete normal Markdown/JSON deliverable. The ceiling
# protects the database from an accidental multi-gigabyte log while covering
# substantially larger reports than this workspace normally produces.
_MAX_PERSISTED_ARTIFACT_CHARS = 4_000_000
_BUILTIN_MATERIAL_BUDGET = 24_000
SUMMARY_AGENT_ID = "roundtable-summary"
ACTION_PLAN_AGENT_ID = "position-action-planner"
@@ -58,6 +65,7 @@ class NodeResponse(BaseModel):
status: str
latest_answer: str | None = None
artifact_manifest: list[dict[str, Any]] = Field(default_factory=list)
conversation_snapshot: dict[str, Any] | None = None
revision: int = 0
upstream_revision: dict[str, Any] | None = None
rejection_count: int = 0
@@ -75,10 +83,13 @@ class SessionResponse(BaseModel):
chain_snapshot: dict[str, Any] | None = None
intent_thread_id: str | None = None
intent_snapshot: dict[str, Any] | None = None
intent_conversation: dict[str, Any] | None = None
summary_thread_id: str | None = None
summary_snapshot: dict[str, Any] | None = None
summary_conversation: dict[str, Any] | None = None
action_plan_thread_id: str | None = None
action_plan_snapshot: dict[str, Any] | None = None
action_plan_conversation: dict[str, Any] | None = None
status: str
created_at: str | None = None
updated_at: str | None = None
@@ -100,6 +111,14 @@ class TaskSnapshotUpdateRequest(BaseModel):
class IntentUpdateRequest(BaseModel):
intent_thread_id: str | None = Field(default=None, max_length=128)
intent_snapshot: dict[str, Any] | None = None
conversation_snapshot: dict[str, Any] | None = None
class ConversationStateUpdateRequest(BaseModel):
"""Durable UI recovery state written while a normal chat is in progress."""
thread_id: str | None = Field(default=None, max_length=128)
conversation_snapshot: dict[str, Any] = Field(default_factory=dict)
class ActivateRequest(BaseModel):
@@ -146,6 +165,14 @@ class CompleteBuiltinRunRequest(BaseModel):
model: str | None = Field(default=None, max_length=256)
class DemoSeedRequest(BaseModel):
"""Canonical frontend fixture imported into the normal SQL session model."""
demo_key: str = Field(min_length=1, max_length=96)
session: dict[str, Any] = Field(default_factory=dict)
nodes: list[dict[str, Any]] = Field(default_factory=list, max_length=32)
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()
@@ -515,13 +542,20 @@ def _artifact_refs(artifacts: Any) -> 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,
}
)
ref = {
"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,
}
# A database recovery payload is already constrained when it is first
# persisted. Preserve it here so downstream agents can still consume
# an upstream report after the owning sandbox/output disk is gone.
content = artifact.get("content")
if isinstance(content, str):
ref["content"] = content
if artifact.get("content_truncated"):
ref["content_truncated"] = True
refs.append(ref)
return refs
@@ -567,7 +601,7 @@ async def _artifact_refs_with_content(
never be allowed to select another thread's user-data directory.
"""
refs = _artifact_refs(artifacts)
if not thread_id or text_budget <= 0:
if text_budget <= 0:
return refs, 0
consumed = 0
@@ -587,6 +621,18 @@ async def _artifact_refs_with_content(
if available <= 0:
break
excerpt_limit = min(_MAX_INLINE_ARTIFACT_CHARS, available)
persisted_content = ref.get("content")
if isinstance(persisted_content, str):
content = _truncate_text(persisted_content, excerpt_limit)
ref["content"] = content
ref["content_truncated"] = bool(
ref.get("content_truncated") or len(persisted_content) > len(content)
)
consumed += len(content)
inline_count += 1
continue
if not thread_id:
continue
try:
actual_path = await aresolve_thread_virtual_path(thread_id, normalized_path)
if not await asyncio.to_thread(actual_path.is_file):
@@ -718,7 +764,7 @@ def _artifact_signature(artifact: dict[str, Any]) -> tuple[str, str, str]:
def _artifact_manifest_refs(artifacts: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Persist only the display metadata received from the thread artifact API."""
"""Persist display metadata plus any database recovery payload."""
refs: list[dict[str, Any]] = []
for artifact in artifacts:
if not isinstance(artifact, dict):
@@ -726,18 +772,59 @@ def _artifact_manifest_refs(artifacts: list[dict[str, Any]]) -> list[dict[str, A
path = str(artifact.get("path") or artifact.get("artifact_url") or "").strip()
if not path.replace("\\", "/").lstrip("/").startswith("mnt/user-data/outputs/"):
continue
refs.append(
{
"name": str(artifact.get("name") or artifact.get("filename") or path.rsplit("/", 1)[-1]),
"path": path,
"mime_type": artifact.get("mime_type") or artifact.get("mimeType") or None,
"modified_at": artifact.get("modified_at") or artifact.get("modifiedAt") or None,
"size_bytes": artifact.get("size_bytes") or artifact.get("sizeBytes") or None,
}
)
ref = {
"name": str(artifact.get("name") or artifact.get("filename") or path.rsplit("/", 1)[-1]),
"path": path,
"mime_type": artifact.get("mime_type") or artifact.get("mimeType") or None,
"modified_at": artifact.get("modified_at") or artifact.get("modifiedAt") or None,
"size_bytes": artifact.get("size_bytes") or artifact.get("sizeBytes") or None,
}
content = artifact.get("content")
if isinstance(content, str):
ref["content"] = content
if artifact.get("content_truncated"):
ref["content_truncated"] = True
refs.append(ref)
return refs
async def _persist_artifact_contents(
thread_id: str | None,
artifacts: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""Copy text deliverables into SQL so history survives ephemeral disks."""
refs = _artifact_manifest_refs(artifacts)
if not thread_id:
return refs
enriched: list[dict[str, Any]] = []
for artifact in refs:
path = str(artifact.get("path") or "")
suffix = Path(path).suffix.lower()
if suffix not in _TEXT_ARTIFACT_SUFFIXES:
enriched.append(artifact)
continue
try:
resolved = await aresolve_thread_virtual_path(thread_id, path)
content = await asyncio.to_thread(resolved.read_text, encoding="utf-8", errors="replace")
except Exception:
# Artifact enrichment is recovery hardening, not a reason to fail
# an otherwise successful delivery. Keep the manifest metadata if
# the sandbox disappeared or its resolver/provider is unavailable.
enriched.append(artifact)
continue
if len(content) > _MAX_PERSISTED_ARTIFACT_CHARS:
artifact = {
**artifact,
"content": content[:_MAX_PERSISTED_ARTIFACT_CHARS],
"content_truncated": True,
}
else:
artifact = {**artifact, "content": content}
enriched.append(artifact)
return enriched
async def _write_builtin_markdown_fallback(
*, thread_id: str, kind: str, content: str
) -> dict[str, Any]:
@@ -784,7 +871,8 @@ async def _effective_delivery_material(
Stale/rejected rows are deliberately excluded. The persisted node answer
provides a quick synopsis; the Markdown files provide the actual
deliverable body, read through the owning thread's virtual-path resolver.
deliverable body, preferably from its database recovery copy and otherwise
through the owning thread's virtual-path resolver.
"""
remaining = _BUILTIN_MATERIAL_BUDGET
lines: list[str] = ["【岗位有效交付】"]
@@ -920,6 +1008,30 @@ def _build_builtin_snapshot(
}
@router.post("/demo/seed", response_model=SessionDetailResponse)
async def seed_demo_session(
request: Request, body: DemoSeedRequest
) -> SessionDetailResponse:
"""Idempotently materialise the frontend demo JSON for the current user.
The endpoint intentionally accepts a complete recovery snapshot instead of
inventing a second demo-only schema. Imported rows therefore exercise the
same history, position switching, artifact and conversation code paths as
real collaboration sessions.
"""
row, nodes = await _get_store(request).ensure_demo_session(
_current_user_id(request),
demo_key=body.demo_key,
session_payload=body.session,
nodes=body.nodes,
)
return SessionDetailResponse(
**row,
nodes=[_project_node(node) for node in 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(
@@ -964,6 +1076,39 @@ async def update_intent_snapshot(
user_id,
intent_thread_id=body.intent_thread_id,
intent_snapshot=body.intent_snapshot,
intent_conversation=body.conversation_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}/summary/state", response_model=SessionResponse)
async def update_summary_conversation(
request: Request, session_id: str, body: ConversationStateUpdateRequest
) -> SessionResponse:
store, user_id, _ = await _require_writable_session(request, session_id)
row = await store.update_session(
session_id,
user_id,
summary_thread_id=body.thread_id,
summary_conversation=body.conversation_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}/action-plan/state", response_model=SessionResponse)
async def update_action_plan_conversation(
request: Request, session_id: str, body: ConversationStateUpdateRequest
) -> SessionResponse:
store, user_id, _ = await _require_writable_session(request, session_id)
row = await store.update_session(
session_id,
user_id,
action_plan_thread_id=body.thread_id,
action_plan_conversation=body.conversation_snapshot,
)
if row is None:
raise HTTPException(status_code=404, detail="Position roundtable session not found")
@@ -1016,6 +1161,16 @@ async def archive_session(request: Request, session_id: str) -> SessionResponse:
return _project_session(row)
@router.delete("/sessions/{session_id}")
async def delete_session(request: Request, session_id: str) -> dict[str, bool]:
deleted = await _get_store(request).delete_session(
session_id, _current_user_id(request)
)
if not deleted:
raise HTTPException(status_code=404, detail="Position roundtable session not found")
return {"deleted": True}
@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))
@@ -1048,6 +1203,38 @@ async def bind_node_thread(
return _project_node(row)
@router.put(
"/sessions/{session_id}/nodes/{node_key}/state",
response_model=NodeResponse,
)
async def update_node_conversation(
request: Request,
session_id: str,
node_key: str,
body: ConversationStateUpdateRequest,
) -> 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 (
body.thread_id
and current.get("thread_id")
and current["thread_id"] != body.thread_id
):
raise HTTPException(status_code=409, detail="Position node is bound to another thread")
row = await store.update_node(
session_id,
node_key,
user_id,
thread_id=body.thread_id if body.thread_id else current.get("thread_id"),
conversation_snapshot=body.conversation_snapshot,
)
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}/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."""
@@ -1069,6 +1256,11 @@ async def complete_node_turn(
# Artifact listing is best-effort on the client. Never erase a previously
# delivered report merely because one listing request transiently failed.
effective_artifacts = body.artifact_manifest or list(node.get("artifact_manifest") or [])
if body.artifact_manifest:
effective_artifacts = await _persist_artifact_contents(
node.get("thread_id"),
effective_artifacts,
)
has_markdown = any(_is_markdown_artifact(item) for item in effective_artifacts)
markdown_changed = _markdown_delivery_changed(node.get("artifact_manifest"), effective_artifacts)
requires_fresh_delivery = node.get("status") in {"rejected", "stale"}
@@ -1240,7 +1432,7 @@ async def _complete_builtin_run(
if body.source_revisions != current_revisions:
raise HTTPException(status_code=409, detail="岗位产物版本已变化,请基于最新交付重新生成")
artifacts = _artifact_manifest_refs(body.artifact_manifest)
artifacts = await _persist_artifact_contents(body.thread_id, body.artifact_manifest)
markdown = [artifact for artifact in artifacts if _is_markdown_artifact(artifact)]
if not markdown:
# The report text is already visible in the chat stream. Do not lose
@@ -1252,6 +1444,7 @@ async def _complete_builtin_run(
kind=kind,
content=body.content,
)
fallback_markdown["content"] = body.content
artifacts.append(fallback_markdown)
markdown = [fallback_markdown]
if kind == "action_plan" and not any(_is_json_artifact(artifact) for artifact in artifacts):
@@ -536,8 +536,8 @@ async def update_publish_squares(body: PublishSquaresUpdateRequest, request: Req
class AppearanceResponse(BaseModel):
"""Effective system-wide appearance defaults."""
default_theme: Literal["light", "dark", "lightblue", "lightgreen"] = Field(
..., description="System default theme — light, dark, lightblue or lightgreen"
default_theme: Literal["light", "dark", "lightblue", "lightgreen", "iceblue"] = Field(
..., description="System default theme — light, dark, lightblue, lightgreen or iceblue"
)
default_skill_view: Literal["card", "list"] = Field(..., description="System default skill list display mode — card or list")
default_agent_view: Literal["card", "list"] = Field(..., description="System default agent list display mode — card or list")
@@ -546,7 +546,7 @@ class AppearanceResponse(BaseModel):
class AppearanceUpdateRequest(BaseModel):
default_theme: Literal["light", "dark", "lightblue", "lightgreen"] | None = Field(default=None)
default_theme: Literal["light", "dark", "lightblue", "lightgreen", "iceblue"] | None = Field(default=None)
default_skill_view: Literal["card", "list"] | None = Field(default=None)
default_agent_view: Literal["card", "list"] | None = Field(default=None)
default_layout_mode: Literal["full", "compact"] | None = Field(default=None)