feat: add unified strategy project workflow

This commit is contained in:
Administrator committed 2026-09-09 15:40:29 +08:00
1 parent 67d12929fc
commit a26fd32eba
28 files changed
+3382 -191

No files matched your search

@@ -15,7 +15,8 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Request
from pydantic import BaseModel, Field
from app.gateway.auth.password import verify_password_async
from app.gateway.deps import get_agent_store, get_config, get_tag_store
from app.gateway.deps import get_agent_store, get_config, get_skill_store, get_tag_store
from app.gateway.routers._strategy_selection_seed import required_agent_ids as required_strategy_agent_ids
from deerflow.agents.lead_agent.prompt import refresh_skills_system_prompt_cache_async
from deerflow.config.agents_api_config import get_agents_api_config
from deerflow.config.agents_config import CommonQuestion, list_custom_agents, load_agent_config, load_agent_soul, validate_agent_id
@@ -23,13 +24,17 @@ from deerflow.config.app_config import AppConfig
from deerflow.config.paths import get_paths
from deerflow.config.system_settings import load_system_settings, normalize_square_id, resolve_default_square_id
from deerflow.persistence.agents import AgentStore
from deerflow.persistence.skills import SkillStore
from deerflow.persistence.tags import TagStore
from deerflow.runtime.user_context import get_effective_user_id
from deerflow.skills.cascade import sync_agent_skills_to_available
from deerflow.skills.storage import get_or_new_skill_storage
from deerflow.skills.types import SkillCategory
from deerflow.skills.usage import all_entries as get_skill_usage_entries
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api", tags=["agents"])
_STRATEGY_SELECTION_AGENT_IDS = frozenset(required_strategy_agent_ids())
class AgentResponse(BaseModel):
@@ -276,6 +281,109 @@ def _validate_storage_id(agent_id: str) -> str:
raise HTTPException(status_code=422, detail=str(exc)) from exc
async def _validate_strategy_agent_skills(
requested_skills: list[str] | None,
*,
app_config: AppConfig,
skill_store: SkillStore,
) -> list[str] | None:
"""Validate a global strategy role's skill allowlist.
Strategy-selection agents are built-in roles shared by every project and
every user. Their allowlists may therefore reference only canonical skill
names that exist on disk, are enabled/active, and are globally visible:
deployment-owned public skills, explicit built-in rows, or custom skills
currently published by their owner. In particular, an administrator must
not be able to attach a different user's unpublished skill merely because
``?admin=true`` exposes it in the management catalog.
"""
if requested_skills is None:
return None
normalized: list[str] = []
for raw_name in requested_skills:
name = raw_name.strip()
if not name:
raise HTTPException(
status_code=422,
detail="Strategy agent skill names cannot be blank",
)
if name not in normalized:
normalized.append(name)
try:
skills = get_or_new_skill_storage(app_config=app_config).load_skills(
enabled_only=False
)
ownership = {
str(record.get("name") or ""): record
for record in await skill_store.list_all()
if record.get("name")
}
usage_entries = get_skill_usage_entries()
except HTTPException:
raise
except Exception as exc: # noqa: BLE001 - stable API response
logger.exception("Failed to validate strategy-agent skill allowlist")
raise HTTPException(status_code=503, detail="Skill catalog is unavailable") from exc
by_name = {skill.name: skill for skill in skills}
unknown = [name for name in normalized if name not in by_name]
if unknown:
raise HTTPException(
status_code=422,
detail=f"Unknown strategy agent skills: {', '.join(unknown)}",
)
unavailable = [
name
for name in normalized
if not by_name[name].enabled
or str((usage_entries.get(name) or {}).get("state") or "active") != "active"
]
if unavailable:
raise HTTPException(
status_code=422,
detail=f"Disabled or archived strategy agent skills: {', '.join(unavailable)}",
)
not_global: list[str] = []
for name in normalized:
skill = by_name[name]
if skill.category != SkillCategory.CUSTOM:
continue
record = ownership.get(name)
if record is not None and (
record.get("owner_user_id") is None or bool(record.get("published"))
):
continue
not_global.append(name)
if not_global:
raise HTTPException(
status_code=422,
detail=(
"Strategy agent skills must be globally available; "
f"unpublished or unregistered custom skills: {', '.join(not_global)}"
),
)
return normalized
def _ensure_strategy_agent_deletable(agent_id: str) -> None:
"""Keep fixed strategy role ids alive; their SOUL/skills remain editable."""
if agent_id in _STRATEGY_SELECTION_AGENT_IDS:
raise HTTPException(
status_code=409,
detail=(
f"Strategy role agent '{agent_id}' cannot be deleted; "
"edit its SOUL and skills instead"
),
)
def _write_agent_config(
agent_id: str,
*,
@@ -953,7 +1061,14 @@ async def update_agent(agent_id: str, request: AgentUpdateRequest, http_request:
next_description = update_data.get("description", current.get("description") or "")
existing_extras = _load_config_extras(agent_id)
next_skills = request.skills if "skills" in fields_set else existing_extras["skills"]
if "skills" in fields_set and agent_id in _STRATEGY_SELECTION_AGENT_IDS:
next_skills = await _validate_strategy_agent_skills(
request.skills,
app_config=get_config(http_request),
skill_store=get_skill_store(http_request),
)
else:
next_skills = request.skills if "skills" in fields_set else existing_extras["skills"]
next_model = request.model if "model" in fields_set else existing_extras["model"]
next_tool_groups = request.tool_groups if "tool_groups" in fields_set else existing_extras["tool_groups"]
next_common_questions = request.common_questions if "common_questions" in fields_set else existing_extras["common_questions"]
@@ -1079,6 +1194,7 @@ async def delete_agent(agent_id: str, request: Request) -> None:
_, edit_mode = await _get_editable_or_raise(
store, agent_id, user_id, is_admin=is_admin
)
_ensure_strategy_agent_deletable(agent_id)
if edit_mode == "admin":
deleted = await store.delete_any(agent_id)
@@ -31,13 +31,15 @@ from __future__ import annotations
import asyncio
import json
import logging
from typing import Any, AsyncIterator
from collections.abc import AsyncIterator
from typing import Any
import httpx
from fastapi import APIRouter, Body, HTTPException, Request
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
from app.gateway.roundtable_model_fallback import is_llm_error_message, reason_text
from app.gateway.routers.multi_agent import (
_ROUNDTABLE_THREAD_METADATA,
_auth_headers,
@@ -50,6 +52,7 @@ from app.gateway.routers.multi_agent import (
_stream_upstream,
_validate_agent_id,
)
from deerflow.agents.roundtable_orchestrator.delivery import visible_seat_text
from deerflow.tools.builtins.clarification_utils import resolve_allow_multiple
logger = logging.getLogger(__name__)
@@ -58,6 +61,17 @@ router = APIRouter(prefix="/api/parallel-agents", tags=["parallel-agents"])
# Soft cap on parallel degree — protects remote model concurrency + sandbox.
MAX_PARALLEL_AGENTS = 8
# Strategy roles are expected to return a substantive task/strategy/evaluation,
# not merely punctuation or a broken provider placeholder. Counting Unicode
# alphanumerics keeps the check language-neutral while rejecting outputs such as
# a long run of "!!!", which otherwise look non-empty to the UI.
MIN_MEANINGFUL_CONTENT_CHARS = 20
def _has_substantive_content(content: str) -> bool:
visible = visible_seat_text(content)
return sum(character.isalnum() for character in visible) >= MIN_MEANINGFUL_CONTENT_CHARS
# 禁两类工具:①**写文件**(write_file / str_replace)—— 并行席位互相写文件会打架;
# ②**派活 / 脚本逃逸**(agent_orchestration / bash)—— 本面板里每个智能体只做自己那
# 份分析交付,绝不该扮演「总控」去调度别人。弱模型(deepseek 等)拿到带「总控 / 业务
@@ -231,6 +245,9 @@ async def _run_one_agent(
if isinstance(msg, dict) and (msg.get("type") or "").lower() in ("ai", "aimessage", "aimessagechunk"):
last_ai = msg
break
failure_reason = is_llm_error_message(last_ai)
if failure_reason:
raise RuntimeError(f"模型调用失败:{reason_text(failure_reason)}")
content = _flatten_content(last_ai.get("content", ""))
# 收集**所有** AI 消息的 tool_calls(全量 args,按顺序)—— 用于在收口时补发所有步骤
# (含 ls / skill_list 这类无参/中间步骤),保证步骤条不丢步、且 args 完整。
@@ -250,6 +267,8 @@ async def _run_one_agent(
"tool_calls": final_tool_calls,
}
else:
if not _has_substantive_content(content):
raise RuntimeError("智能体未生成有效正文,请重试或更换全局模型")
yield {
"status": f"子智能体 {agent_id} 完成",
"content": content,
@@ -408,8 +427,24 @@ async def run_parallel_agents_stream(request: Request, payload: dict = Body(...)
await _emit_tool(tc)
if not done_sent:
# 流被抢占/截断,没收到终态帧 —— 用已累积正文兜底收口本席位。
buffered_content = "".join(buffer)
failure_reason = is_llm_error_message(
{"type": "ai", "content": buffered_content}
)
if failure_reason:
raise RuntimeError(
f"模型调用失败:{reason_text(failure_reason)}"
)
if not _has_substantive_content(buffered_content):
raise RuntimeError(
"智能体未生成有效正文,请重试或更换全局模型"
)
await queue.put(
{"type": "agent_done", "agent_id": agent_id, "content": "".join(buffer)}
{
"type": "agent_done",
"agent_id": agent_id,
"content": buffered_content,
}
)
except Exception as exc: # noqa: BLE001 — 单个 agent 失败不拖垮其它
logger.warning("[parallel-agents] %s failed: %r", agent_id, exc)