sync update from LAN repo (source dhk-1 @ 3b1ec5b4)

This commit is contained in:
gozeros committed 2026-11-05 10:56:34 +08:00
1 parent da6521b6cb
commit 264e2200d6
995 files changed
+148105 -13399

No files matched your search

@@ -9,8 +9,8 @@ Each fan-out agent runs as a pure **executing seat**: ``excluded_tools`` =
``_EXCLUDED_TOOLS`` (``write_file`` / ``str_replace`` / ``agent_orchestration`` /
``bash``) so a seat can neither write files (parallel writes would clash) nor
dispatch / run scripts (a weak model fed "总控 / 业务链条" framing would otherwise
mimic the controller and "派活"). Read-only tools + ``ask_clarification`` stay on,
so the step bar and clarification cards still work.
mimic the controller and "派活"). Read-only tools stay on. ``ask_clarification``
is available only to strategy intent, the sole stage with a reply surface.
Unified event protocol (one JSON object per ``data:`` frame)::
@@ -36,13 +36,16 @@ from collections.abc import AsyncIterator
from typing import Any
import httpx
from fastapi import APIRouter, Body, HTTPException, Request
from fastapi import APIRouter, Body, HTTPException, Query, Request, Response
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 import agents as agents_router
from app.gateway.routers._strategy_selection_seed import STRATEGY_AGENT_ID_PREFIX
from app.gateway.routers._strategy_selection_seed import (
STRATEGY_AGENT_ID_PREFIX,
STRATEGY_INTENT_AGENT_ID,
)
from app.gateway.routers.multi_agent import (
_ROUNDTABLE_THREAD_METADATA,
_auth_headers,
@@ -128,7 +131,7 @@ def _has_substantive_content(content: str) -> bool:
# 链条」语气的任务后,会概率性地用 agent_orchestration 真去派活,或绕道 bash 跑脚本
# 调内部接口模仿总控调度(bug:单步单智能体链条里子智能体输出「总控调度指令…」并用
# glob / bash 翻找派活脚本)。物理禁掉这两类即可根治。其余只读工具(ls / read_file /
# 检索)与 ask_clarification(协作卡片)保留:既不互相打架,又能正常出步骤条 / 要澄清。
# 检索)保留;ask_clarification 仅意图阶段保留,因为只有它有可续答的协作卡片。
_EXCLUDED_TOOLS: list[str] = [
"write_file", # 并行不互相写文件打架
"str_replace",
@@ -137,11 +140,27 @@ _EXCLUDED_TOOLS: list[str] = [
]
# ── 专用「绕过常规登录」取 token ──────────────────────────────────────────────
# 内网部署对标准 /api/v1/auth/login/username 有额外操作限制(口令门 / 网关裁剪等),
# 嵌入方拿不到 token。这里给并行多智能体面板单开一个**公共**端点:传用户名直接签发 token
# (账号不存在则自动注册,与 username 登录同一套逻辑)。已在 auth_middleware / csrf_middleware
# 的白名单里放行(公共 + CSRF 豁免)。⚠️ 这是有意的鉴权旁路,仅供内网部署的本功能使用。
def _strategy_stage_allows_clarification(agent_id: str) -> bool:
"""Return whether a strategy-selection stage has a user reply surface.
The workbench renders and resumes clarification cards only for the intent
stage. Angle generation, judging and final synthesis are one-shot stages;
letting those agents call ``ask_clarification`` produces an interrupt that
the UI cannot answer and therefore turns a recoverable run into a failure.
"""
return agent_id.strip().casefold() == STRATEGY_INTENT_AGENT_ID.casefold()
def _excluded_tools_for_agent(agent_id: str) -> list[str]:
excluded = list(_EXCLUDED_TOOLS)
normalized = agent_id.strip().casefold()
if normalized.startswith(STRATEGY_AGENT_ID_PREFIX.casefold()) and not _strategy_stage_allows_clarification(agent_id):
excluded.append("ask_clarification")
return excluded
# ── 并行面板兼容登录:复用单点开关、密码、限速与封禁校验 ────────────────────
class _TokenRequest(BaseModel):
@@ -154,16 +173,45 @@ class _TokenResponse(BaseModel):
user_id: str
@router.post("/auth/token", response_model=_TokenResponse)
async def issue_token(body: _TokenRequest) -> _TokenResponse:
"""传用户名 → 直接签发 access_token(绕过常规登录,公共端点)。"""
# 懒加载,避免与 auth 路由的模块级循环依赖。
from app.gateway.auth import create_access_token
from app.gateway.routers.auth import _get_or_create_user_by_username
def _force_situation_detail_compat_token(username: str) -> _TokenResponse:
"""Return a non-JWT value accepted only by open force-situation detail APIs.
user, _created = await _get_or_create_user_by_username(body.username.strip())
token = create_access_token(str(user.id), token_version=user.token_version)
return _TokenResponse(access_token=token, token_type="bearer", user_id=str(user.id))
Existing task-detail skills call this legacy endpoint before every detail
GET/PUT and require a non-empty value even though those endpoints are now
credential-free. Keeping the compatibility behavior generic avoids
coupling backend routing to a particular skill name or service account.
"""
normalized = username.casefold()
return _TokenResponse(
# Deliberately not a signed JWT: AuthMiddleware rejects it everywhere
# except the explicitly credential-free force-situation detail routes.
access_token=f"force-situation-detail-compat-{normalized}",
token_type="bearer",
user_id=f"external:{normalized}",
)
@router.post("/auth/token", response_model=_TokenResponse)
async def issue_token(body: _TokenRequest, request: Request, response: Response, password: str | None = Query(default=None)) -> _TokenResponse:
"""Issue a normal login token, or detail-route compatibility value on policy rejection."""
username = body.username.strip()
from app.gateway.routers.auth import login_by_username
try:
result = await login_by_username(
request,
response,
password=password,
)
except HTTPException as exc:
# The caller needs this endpoint only as a preflight before the open
# force-situation detail routes. Do not make individual skill names or
# current password/SSO policy a prerequisite for that workflow.
if exc.status_code in {401, 403}:
return _force_situation_detail_compat_token(username)
raise
return _TokenResponse(access_token=result.access_token, token_type="bearer", user_id=result.user_id)
# ── frame normalisation (mirrors multi-agent.ts) ─────────────────────────────
@@ -375,7 +423,7 @@ async def _run_one_agent(
model_name=model_name,
thread_id=thread_id,
new_message=new_message,
excluded_tools=list(_EXCLUDED_TOOLS),
excluded_tools=_excluded_tools_for_agent(agent_id),
skill_stop_names=[],
thinking_enabled=True,
reasoning_effort="medium",
@@ -432,7 +480,7 @@ async def _run_one_agent(
}
def _build_task_message(task_name: str, brief: str) -> str:
def _build_task_message(task_name: str, brief: str, *, agent_id: str = "") -> str:
parts: list[str] = []
if task_name.strip():
parts.append(f"任务名称:{task_name.strip()}")
@@ -447,13 +495,23 @@ def _build_task_message(task_name: str, brief: str) -> str:
"调度对象 / 分配给『…』的任务 / agent_name」之类调度内容,严禁罗列或转派其他席位的任务,严禁调用"
"任何派活 / 调度类工具,也不要用脚本(bash / python)去调用内部接口或翻找派活脚本。"
)
# 澄清护栏:要向用户确认时,必须用 ask_clarification 工具发起(前端据此渲染可点击的协作
# 卡片),不能只把问题写在正文里 —— 否则用户看不到卡片、无法回应。能合理假设就先假设并标注。
parts.append(
"【需要向用户确认时】如果确实缺少完成分析所必需的关键信息,请**调用 `ask_clarification` 工具**"
"发起确认(这样用户会看到一张可点击的协作卡片来回答);**不要只把问题写在正文里**,否则用户无法回应。"
"能基于已有信息合理假设的,就先假设并在正文中标注你的假设;只有当不同假设会显著改变结论时,才发起确认。"
)
# 只有意图阶段有可交互、可恢复的澄清卡片。其余策略阶段均为一次性交付,必须基于已确认
# 的任务继续完成;否则 ask_clarification 会产生前端无法回答的中断并被误报为生成失败。
if agent_id and agent_id.casefold().startswith(STRATEGY_AGENT_ID_PREFIX.casefold()) and not _strategy_stage_allows_clarification(agent_id):
parts.append(
"【本阶段禁止反问】当前是无需用户中途介入的一次性交付阶段。不得调用 `ask_clarification`,"
"不得在正文里向用户提问、要求补充材料或要求点击重试。信息不足时请采用保守的合理假设,"
"明确降低相应结论的置信度,并把缺口列入“数据限制与待核验”,然后直接完成本阶段要求的全部交付;"
"不要重复输出同一正文或多个版本。"
)
else:
# 澄清护栏:要向用户确认时,必须用 ask_clarification 工具发起(前端据此渲染可点击的
# 协作卡片),不能只把问题写在正文里。能合理假设就先假设并标注。
parts.append(
"【需要向用户确认时】如果确实缺少完成分析所必需的关键信息,请**调用 `ask_clarification` 工具**"
"发起确认(这样用户会看到一张可点击的协作卡片来回答);**不要只把问题写在正文里**,否则用户无法回应。"
"能基于已有信息合理假设的,就先假设并在正文中标注你的假设;只有当不同假设会显著改变结论时,才发起确认。"
)
return "\n\n".join(parts)
@@ -521,13 +579,13 @@ async def run_parallel_agents_stream(request: Request, payload: dict = Body(...)
base = _loopback_base(request)
headers = _auth_headers(request)
new_message = _build_task_message(task_name, brief)
async def _consume_agent(
client: Any,
agent_id: str,
queue: asyncio.Queue[dict[str, Any]],
) -> None:
new_message = _build_task_message(task_name, brief, agent_id=agent_id)
await queue.put({"type": "agent_start", "agent_id": agent_id})
last_event = ""
emitted_tools: set[str] = set() # 已发过 step 的 tool_call id(去重)