Merge branch 'ji' into master
按钮管理「登录参数」两套实现冲突解决——两分支各自独立给跳转按钮加了登录态追加能力, 二者正交、保留两套,互不影响: - master: login_params (JSON 列 login_params_json,从 userInfo 解析,类似轻应用登录参数) - ji: append_auth + auth_token_param + auth_name_param (token 登录时追加 token1+用户名) 迁移 revision 碰撞修复(两分支都用了 20260625_01):重编号为线性链 20260620_02 → 20260625_01 (login_params) → 20260625_02 (auth_params) → 20260625_03 (users_approved) 并同步 column_additions_mysql.sql 注释里的 migration 编号。 前后端 task_buttons(model/sql/memory/router/前端 type·api·admin 页)均保留两套字段; 两份 CLAUDE.md 文档合并为同时记录两种机制。 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
commit
58357547c9
44 files changed
+1207
-46
No files matched your search
@@ -50,6 +50,7 @@ from app.gateway.routers import (
|
||||
models,
|
||||
multi_agent,
|
||||
notifications,
|
||||
open_3qfx,
|
||||
open_chat,
|
||||
parallel_agent_tasks,
|
||||
parallel_agents,
|
||||
@@ -1478,6 +1479,9 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
|
||||
# 开放问答接口 /api/open/chat —— 无需登录,指定模型 + 智能体做问答,可关闭思考模式
|
||||
app.include_router(open_chat.router)
|
||||
|
||||
# 开放接口 /api/open/3qfx/ask —— 无需登录,按 taskId 直接发起 3qfx 第一次问答(后台运行,落成真实会话)
|
||||
app.include_router(open_3qfx.router)
|
||||
|
||||
# --- ?????????? /page/workspace/roundtable/planning?---
|
||||
# ??? app/gateway/routers/{multi_agent,intent,recommend}.py?
|
||||
# ??? frontend-web/docs/multi-agent-backend-dev.md
|
||||
|
||||
@@ -79,7 +79,7 @@ class LocalAuthProvider(AuthProvider):
|
||||
"""
|
||||
return await self._repo.find_users_by_email_local_part_like(substring, limit=limit)
|
||||
|
||||
async def create_user(self, email: str, password: str | None = None, system_role: str = "user", needs_setup: bool = False) -> User:
|
||||
async def create_user(self, email: str, password: str | None = None, system_role: str = "user", needs_setup: bool = False, approved: bool = False) -> User:
|
||||
"""Create a new local user.
|
||||
|
||||
Args:
|
||||
@@ -87,6 +87,8 @@ class LocalAuthProvider(AuthProvider):
|
||||
password: Plain text password (will be hashed)
|
||||
system_role: Role to assign ("admin" or "user")
|
||||
needs_setup: If True, user must complete setup on first login
|
||||
approved: Login-whitelist 放行标记. Regular self-registered users
|
||||
default to ``False`` (待审批); admins are created ``True``.
|
||||
|
||||
Returns:
|
||||
Created User instance
|
||||
@@ -97,6 +99,7 @@ class LocalAuthProvider(AuthProvider):
|
||||
password_hash=password_hash,
|
||||
system_role=system_role,
|
||||
needs_setup=needs_setup,
|
||||
approved=approved,
|
||||
)
|
||||
return await self._repo.create_user(user)
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ class User(BaseModel):
|
||||
# Auth lifecycle
|
||||
needs_setup: bool = Field(default=False, description="True for auto-created admin until setup completes")
|
||||
token_version: int = Field(default=0, description="Incremented on password change to invalidate old JWTs")
|
||||
approved: bool = Field(default=False, description="登录白名单放行标记;仅当系统设置 login_whitelist.enabled 打开时拦截未放行用户。新普通用户默认待审批(False)。")
|
||||
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
|
||||
@@ -46,6 +46,7 @@ class SQLiteUserRepository(UserRepository):
|
||||
oauth_id=row.oauth_id,
|
||||
needs_setup=row.needs_setup,
|
||||
token_version=row.token_version,
|
||||
approved=row.approved,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -60,6 +61,7 @@ class SQLiteUserRepository(UserRepository):
|
||||
oauth_id=user.oauth_id,
|
||||
needs_setup=user.needs_setup,
|
||||
token_version=user.token_version,
|
||||
approved=user.approved,
|
||||
)
|
||||
|
||||
# ── CRUD ──────────────────────────────────────────────────────────
|
||||
@@ -154,6 +156,7 @@ class SQLiteUserRepository(UserRepository):
|
||||
row.oauth_id = user.oauth_id
|
||||
row.needs_setup = user.needs_setup
|
||||
row.token_version = user.token_version
|
||||
row.approved = user.approved
|
||||
await session.commit()
|
||||
return user
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ owner filtering works automatically via the sentinel pattern.
|
||||
Fine-grained permission checks remain in authz.py decorators.
|
||||
"""
|
||||
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
|
||||
from fastapi import HTTPException, Request, Response
|
||||
@@ -64,6 +65,20 @@ def _is_public(path: str) -> bool:
|
||||
return any(path.startswith(prefix) for prefix in _PUBLIC_PATH_PREFIXES)
|
||||
|
||||
|
||||
# 「发起问答」的 run 创建接口(会真正调用大模型):
|
||||
# POST /api/threads/{id}/runs[/stream|/wait]
|
||||
# POST /api/runs/{stream|wait}
|
||||
# (含 nginx 未改写到的 /api/langgraph/... 前缀,双保险)
|
||||
# 只匹配这些「提交问答」的 POST,不碰 GET 列表 / join / cancel / feedback 等,
|
||||
# 这样登录白名单开启后,未放行用户(凭旧 token)无法再用接口问答,但普通浏览不受影响。
|
||||
_QA_RUN_RE = re.compile(r"^/api/(?:langgraph/)?(?:threads/[^/]+/)?runs(?:/stream|/wait)?$")
|
||||
|
||||
|
||||
def _is_qa_run_request(method: str, path: str) -> bool:
|
||||
"""True for an authenticated「发起问答」run-creation request (see ``_QA_RUN_RE``)."""
|
||||
return method.upper() == "POST" and bool(_QA_RUN_RE.match(path.rstrip("/")))
|
||||
|
||||
|
||||
class AuthMiddleware(BaseHTTPMiddleware):
|
||||
"""Strict auth gate: reject requests without a valid session.
|
||||
|
||||
@@ -148,6 +163,18 @@ class AuthMiddleware(BaseHTTPMiddleware):
|
||||
# JWT-decode + DB-lookup pipeline a second time per request).
|
||||
request.state.user = user
|
||||
request.state.auth = AuthContext(user=user, permissions=_ALL_PERMISSIONS)
|
||||
|
||||
# 登录白名单:开关开启时,未放行用户(非 admin)不仅被拦在登录外,连「接口
|
||||
# 问答」也封掉——已拿到 token 的未放行用户用旧会话直接调问答接口同样被拒。
|
||||
# 仅作用于「发起问答」的 run 接口;内部/渠道调用(internal_user)不受限。
|
||||
if internal_user is None and _is_qa_run_request(request.method, app_relative_path(request)):
|
||||
from app.gateway.routers.auth import enforce_user_approved
|
||||
|
||||
try:
|
||||
enforce_user_approved(user)
|
||||
except HTTPException as exc:
|
||||
return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail})
|
||||
|
||||
token = set_current_user(user)
|
||||
try:
|
||||
return await call_next(request)
|
||||
|
||||
@@ -12,6 +12,7 @@ from fastapi.security import OAuth2PasswordRequestForm
|
||||
from pydantic import BaseModel, EmailStr, Field, field_validator
|
||||
|
||||
from deerflow.config import get_app_config
|
||||
from deerflow.config.system_settings import load_system_settings
|
||||
from deerflow.persistence.agents.base import AgentStore
|
||||
from deerflow.persistence.skills.base import SkillStore
|
||||
|
||||
@@ -145,6 +146,15 @@ class UsernameLoginResponse(BaseModel):
|
||||
system_role: Literal["admin", "user"] = "user"
|
||||
needs_setup: bool = False
|
||||
created: bool = Field(default=False, description="True when the user was auto-registered by this call")
|
||||
username: str | None = Field(
|
||||
default=None,
|
||||
description=(
|
||||
"The login username this call resolved (token login: the value read "
|
||||
"from getTokenInfo; username login: the supplied username). Used by "
|
||||
"the frontend to append ?username= on task-workspace jump links; the "
|
||||
"stored email local-part is lossy (lowercased/normalized)."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class ChangePasswordRequest(BaseModel):
|
||||
@@ -246,7 +256,9 @@ async def _get_or_create_user_by_username(username: str):
|
||||
if user is None:
|
||||
try:
|
||||
role = "admin" if username == "admin" else "user"
|
||||
user = await provider.create_user(email=email, password=None, system_role=role, needs_setup=False)
|
||||
# admin 创建即放行;普通用户自助注册后默认「待审批」(approved=False),
|
||||
# 需管理员在白名单管理页放行——但仅当登录白名单开关打开时才会被拦。
|
||||
user = await provider.create_user(email=email, password=None, system_role=role, needs_setup=False, approved=(role == "admin"))
|
||||
created = True
|
||||
logger.info("Auto-registered passwordless user: %s", email)
|
||||
except ValueError:
|
||||
@@ -267,6 +279,35 @@ async def _get_or_create_user_by_username(username: str):
|
||||
return user, created
|
||||
|
||||
|
||||
def enforce_user_approved(user) -> None:
|
||||
"""登录白名单拦截:开关打开且用户未放行时拒绝登录(注册照常,只是不发 token)。
|
||||
|
||||
规则(三条硬约束防锁死):
|
||||
- 开关关(``login_whitelist.enabled`` 默认 False)→ 直接放行,人人可登录。
|
||||
- admin → 永远放行(避免管理员把自己关在门外)。
|
||||
- 其余:``approved`` 为 False(注册后待审批)→ 403 ``PENDING_APPROVAL``;
|
||||
前端据此提示「等待管理员开通」,且不写任何登录态。
|
||||
|
||||
放在各登录端点拿到 user 之后、签发 JWT 之前调用——账号此时已自助注册完成,
|
||||
被拦只是拿不到 token,管理员可在白名单管理页看到该待审批账号并放行。
|
||||
"""
|
||||
try:
|
||||
enabled = load_system_settings().login_whitelist.enabled
|
||||
except Exception:
|
||||
# 读配置失败时绝不误伤(白名单是附加闸门,故障时回到「不拦截」)。
|
||||
logger.warning("读取登录白名单配置失败,本次登录不拦截", exc_info=True)
|
||||
return
|
||||
if not enabled:
|
||||
return
|
||||
if getattr(user, "system_role", None) == "admin":
|
||||
return
|
||||
if not getattr(user, "approved", False):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail={"code": "PENDING_APPROVAL", "message": "您的账号正在等待管理员开通,请联系管理员"},
|
||||
)
|
||||
|
||||
|
||||
async def _fetch_username_from_token(token: str) -> str:
|
||||
"""Resolve an upstream access token to a username via the configured endpoint.
|
||||
|
||||
@@ -277,6 +318,15 @@ async def _fetch_username_from_token(token: str) -> str:
|
||||
Any upstream failure, non-200 ``state``, or missing username raises HTTP 401.
|
||||
"""
|
||||
config = get_app_config().auth_login.token_login
|
||||
|
||||
# Offline test shortcut: a token listed in ``mock_tokens`` resolves to its
|
||||
# mapped username without ever calling the (possibly unreachable) upstream
|
||||
# ``token_info_url``. Lets token login be exercised end-to-end where the real
|
||||
# getTokenInfo host can't be reached (external networks). Empty in prod.
|
||||
mocked = config.mock_tokens.get(token)
|
||||
if mocked and str(mocked).strip():
|
||||
return str(mocked).strip()
|
||||
|
||||
if not config.token_info_url:
|
||||
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="token 登录未配置(token_info_url 为空)")
|
||||
|
||||
@@ -489,6 +539,7 @@ async def login_local(
|
||||
)
|
||||
|
||||
_record_login_success(client_ip)
|
||||
enforce_user_approved(user)
|
||||
token = create_access_token(str(user.id), token_version=user.token_version)
|
||||
_set_session_cookie(response, token, request)
|
||||
await _sync_user_position(request, user.id)
|
||||
@@ -534,6 +585,7 @@ async def login_by_username(
|
||||
|
||||
user, created = await _get_or_create_user_by_username(body.username)
|
||||
|
||||
enforce_user_approved(user)
|
||||
token = create_access_token(str(user.id), token_version=user.token_version)
|
||||
_set_session_cookie(response, token, request)
|
||||
await _sync_user_position(request, user.id)
|
||||
@@ -547,6 +599,7 @@ async def login_by_username(
|
||||
system_role=user.system_role,
|
||||
needs_setup=user.needs_setup,
|
||||
created=created,
|
||||
username=body.username,
|
||||
)
|
||||
|
||||
|
||||
@@ -585,6 +638,7 @@ async def login_by_token(
|
||||
|
||||
user, created = await _get_or_create_user_by_username(username)
|
||||
|
||||
enforce_user_approved(user)
|
||||
access_token = create_access_token(str(user.id), token_version=user.token_version)
|
||||
_set_session_cookie(response, access_token, request)
|
||||
await _sync_user_position(request, user.id)
|
||||
@@ -598,6 +652,9 @@ async def login_by_token(
|
||||
system_role=user.system_role,
|
||||
needs_setup=user.needs_setup,
|
||||
created=created,
|
||||
# The raw username resolved from getTokenInfo (pre email-normalization),
|
||||
# so the frontend can append the exact ?username= on jump links.
|
||||
username=username,
|
||||
)
|
||||
|
||||
|
||||
@@ -745,7 +802,7 @@ async def initialize_admin(request: Request, response: Response, body: Initializ
|
||||
)
|
||||
|
||||
try:
|
||||
user = await get_local_provider().create_user(email=body.email, password=body.password, system_role="admin", needs_setup=False)
|
||||
user = await get_local_provider().create_user(email=body.email, password=body.password, system_role="admin", needs_setup=False, approved=True)
|
||||
except ValueError:
|
||||
# DB unique-constraint race: another concurrent request beat us.
|
||||
raise HTTPException(
|
||||
@@ -769,6 +826,7 @@ class UserListItem(BaseModel):
|
||||
skill_count: int
|
||||
agent_count: int
|
||||
qa_count: int = 0 # 问答次数: number of runs (one run = one question)
|
||||
approved: bool = True # 登录白名单放行标记(白名单管理页据此放行/取消)
|
||||
|
||||
|
||||
@router.get("/users", response_model=list[UserListItem])
|
||||
@@ -801,11 +859,44 @@ async def list_all_users(
|
||||
skill_count=await skill_store.count_owned(uid),
|
||||
agent_count=await agent_store.count_owned(uid),
|
||||
qa_count=qa_counts.get(uid, 0),
|
||||
approved=getattr(u, "approved", True),
|
||||
)
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
class UserApprovalRequest(BaseModel):
|
||||
approved: bool = Field(..., description="True=放行该用户登录;False=取消放行(下次登录被拦)")
|
||||
|
||||
|
||||
@router.put("/users/{user_id}/approval", response_model=UserListItem)
|
||||
async def set_user_approval(user_id: str, body: UserApprovalRequest, request: Request) -> UserListItem:
|
||||
"""放行 / 取消放行某个注册用户(登录白名单)。Admin only。
|
||||
|
||||
取消放行只拦该用户的下次登录(不动 ``token_version``,现有会话不强制下线)。
|
||||
"""
|
||||
admin = await get_current_user_from_request(request)
|
||||
if admin.system_role != "admin":
|
||||
raise HTTPException(status_code=403, detail="Admin only")
|
||||
|
||||
provider = get_local_provider()
|
||||
target = await provider.get_user(user_id)
|
||||
if target is None:
|
||||
raise HTTPException(status_code=404, detail="用户不存在")
|
||||
|
||||
target.approved = bool(body.approved)
|
||||
saved = await provider.update_user(target)
|
||||
return UserListItem(
|
||||
id=str(saved.id),
|
||||
email=saved.email,
|
||||
system_role=saved.system_role,
|
||||
skill_count=0,
|
||||
agent_count=0,
|
||||
qa_count=0,
|
||||
approved=saved.approved,
|
||||
)
|
||||
|
||||
|
||||
# ── OAuth Endpoints (Future/Placeholder) ─────────────────────────────────
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
"""开放接口:按 taskId 直接发起 3qfx(三情分析)的「第一次问答」(无需登录)。
|
||||
|
||||
外部系统只需把一个 **任务id** 传进来,后端就会:
|
||||
|
||||
1. 解析 ``3Q`` 业务配置的智能体(``business_mapping`` 里 ``business_code=="3Q"`` 那一行的
|
||||
``agent_id``,与前端任务深链 ``goPath=3qfx`` 取的是同一个);
|
||||
2. 按 taskId 拉取任务详情(consumer 的 ``cop-task-detail``,地址 / 鉴权头 / mock 都在
|
||||
``config.yaml`` 的 ``task_deeplink`` 段),拼出与前端深链一致的开场白
|
||||
``任务名称:…\n任务内容:…\n任务id(task_id)为…``;
|
||||
3. **新建一条真实会话**(thread 打 ``metadata.{taskId, agent_id}`` 标签,与前端
|
||||
``taskThreadMetadata`` / ``useTaskThreads`` 的过滤口径一致),以开场白作为第一条用户消息
|
||||
**后台启动一次持久化运行**(写 checkpointer,不阻塞);
|
||||
4. **立即返回** ``{thread_id, run_id, agent_id, status}`` —— 调用方拿到「调用成功」即可,
|
||||
随后在 3qfx 任务工作区的对话列表里就能看到这条问答并实时观看其进展。
|
||||
|
||||
该路由前缀 ``/api/open/`` 已在 ``auth_middleware._PUBLIC_PATH_PREFIXES`` 白名单里(且
|
||||
``csrf_middleware`` 豁免),**绕过登录鉴权**,以 ``"default"`` 用户桶运行;因 thread 带
|
||||
``metadata.taskId``(任务深链对话全局共享、按创建者解析文件路径),任何已登录用户打开该任务
|
||||
都能看到同一条会话。
|
||||
|
||||
请求示例::
|
||||
|
||||
POST /api/open/3qfx/ask
|
||||
{"task_id": "2055"}
|
||||
|
||||
返回::
|
||||
|
||||
{"thread_id": "…", "run_id": "…", "agent_id": "…", "status": "running",
|
||||
"opening_text": "任务名称:…\n任务内容:…\n任务id(task_id)为2055"}
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.gateway.routers.thread_runs import RunCreateRequest
|
||||
from app.gateway.services import start_run
|
||||
from deerflow.config import get_app_config
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/open/3qfx", tags=["open"])
|
||||
|
||||
# 与前端任务深链 goPath=3qfx → businessCode 的映射保持一致。
|
||||
_THREEQ_BUSINESS_CODE = "3Q"
|
||||
|
||||
|
||||
class ThreeQAskRequest(BaseModel):
|
||||
"""3qfx 开放问答请求体。"""
|
||||
|
||||
task_id: str = Field(..., description="任务id(cop-task-detail 的 taskId)", min_length=1)
|
||||
message: str | None = Field(
|
||||
default=None,
|
||||
description="可选:自定义首条问题文本。留空(默认)则后端按 task_id 拉取任务详情自动拼开场白。",
|
||||
)
|
||||
model_name: str | None = Field(default=None, description="可选:覆盖模型(models[] 中的 name)")
|
||||
thinking_enabled: bool = Field(default=False, description="是否开启思考;默认关闭")
|
||||
|
||||
|
||||
class ThreeQAskResponse(BaseModel):
|
||||
thread_id: str
|
||||
run_id: str
|
||||
agent_id: str
|
||||
status: str
|
||||
opening_text: str
|
||||
|
||||
|
||||
class CopTaskDetail(BaseModel):
|
||||
"""consumer ``cop-task-detail`` 返回的 ``data`` 字段(与前端 CopTaskDetail 对齐)。"""
|
||||
|
||||
id: str | int | None = None
|
||||
overview: str = ""
|
||||
task_direction: str = ""
|
||||
task_name: str = ""
|
||||
task_content: str = ""
|
||||
|
||||
|
||||
async def _resolve_threeq_agent_id(request: Request) -> str:
|
||||
"""取 ``business_code=="3Q"`` 配置的智能体 id;未配置 → 503。"""
|
||||
store = getattr(request.app.state, "business_mapping_store", None)
|
||||
if store is None:
|
||||
raise HTTPException(status_code=503, detail="业务映射未就绪(business_mapping_store 不可用)。")
|
||||
mapping = await store.get_mapping(_THREEQ_BUSINESS_CODE)
|
||||
agent_id = (mapping or {}).get("agent_id")
|
||||
if not agent_id:
|
||||
raise HTTPException(status_code=503, detail="3Q(三情分析)业务尚未在「业务链条管理」里配置智能体。")
|
||||
return str(agent_id)
|
||||
|
||||
|
||||
def _parse_cop_task_detail(body: Any) -> CopTaskDetail:
|
||||
"""从 ``{data: {...}}`` 整包里抽出任务详情(字段缺失按空串)。"""
|
||||
data = body.get("data") if isinstance(body, dict) else None
|
||||
if not isinstance(data, dict):
|
||||
return CopTaskDetail()
|
||||
return CopTaskDetail(
|
||||
id=data.get("id"),
|
||||
overview=data.get("overview") if isinstance(data.get("overview"), str) else "",
|
||||
task_direction=data.get("taskDirection") if isinstance(data.get("taskDirection"), str) else "",
|
||||
task_name=data.get("taskName") if isinstance(data.get("taskName"), str) else "",
|
||||
task_content=data.get("taskContent") if isinstance(data.get("taskContent"), str) else "",
|
||||
)
|
||||
|
||||
|
||||
async def _fetch_cop_task_detail(task_id: str) -> CopTaskDetail:
|
||||
"""按 taskId 取任务详情。``cop_task_detail_test`` 为真走 mock;否则打真实 consumer 接口。"""
|
||||
cfg = get_app_config().task_deeplink
|
||||
if cfg.cop_task_detail_test:
|
||||
return _parse_cop_task_detail((cfg.mock or {}).get("cop_task_detail"))
|
||||
|
||||
url = (cfg.cop_task_detail_url or "").strip()
|
||||
if not url:
|
||||
raise HTTPException(status_code=503, detail="未配置任务详情接口(task_deeplink.cop_task_detail_url),无法按 id 拉取。")
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=20.0) as client:
|
||||
resp = await client.get(
|
||||
url,
|
||||
params={"taskId": task_id},
|
||||
headers={"Authorization": cfg.cop_task_detail_authorization or "Bearer admin"},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
body = resp.json()
|
||||
except Exception as exc: # noqa: BLE001 — 开放接口需把上游错误归一成 502
|
||||
logger.warning("拉取 cop-task-detail 失败 (taskId=%s): %s", task_id, exc)
|
||||
raise HTTPException(status_code=502, detail=f"拉取任务详情失败:{exc}") from exc
|
||||
return _parse_cop_task_detail(body)
|
||||
|
||||
|
||||
def build_opening_text(detail: CopTaskDetail, task_id: str) -> str:
|
||||
"""拼 3qfx 开场白,与前端 ``buildOpeningText``(3qfx 分支)逐行对齐。"""
|
||||
parts = [
|
||||
f"任务名称:{detail.task_name}" if detail.task_name else "",
|
||||
f"任务内容:{detail.task_content}" if detail.task_content else "",
|
||||
f"任务id(task_id)为{task_id}" if task_id else "",
|
||||
]
|
||||
return "\n".join(p for p in parts if p)
|
||||
|
||||
|
||||
@router.post("/ask", response_model=ThreeQAskResponse)
|
||||
async def ask_3qfx(body: ThreeQAskRequest, request: Request) -> ThreeQAskResponse:
|
||||
"""按 taskId 直接发起 3qfx 第一次问答;后台运行,立即返回 thread_id。"""
|
||||
task_id = body.task_id.strip()
|
||||
if not task_id:
|
||||
raise HTTPException(status_code=422, detail="task_id 不能为空。")
|
||||
|
||||
agent_id = await _resolve_threeq_agent_id(request)
|
||||
|
||||
# 首条问题:默认按 id 自动拉取任务详情拼开场白;显式传 message 则用它覆盖。
|
||||
if body.message and body.message.strip():
|
||||
opening_text = body.message.strip()
|
||||
else:
|
||||
detail = await _fetch_cop_task_detail(task_id)
|
||||
opening_text = build_opening_text(detail, task_id)
|
||||
if not opening_text:
|
||||
raise HTTPException(status_code=502, detail="任务详情为空,无法生成首条问题(可改用 message 显式传入)。")
|
||||
|
||||
thread_id = str(uuid.uuid4())
|
||||
context: dict[str, Any] = {"agent_id": agent_id, "thinking_enabled": body.thinking_enabled}
|
||||
if body.model_name:
|
||||
context["model_name"] = body.model_name
|
||||
|
||||
run_body = RunCreateRequest(
|
||||
assistant_id=agent_id,
|
||||
input={"messages": [{"role": "user", "content": opening_text}]},
|
||||
# taskId + agent_id 让该会话被 3qfx 任务工作区的 useTaskThreads 过滤命中(按任务+业务隔离),
|
||||
# 且 metadata.taskId 触发后端「任务深链对话全局共享 / 按创建者解析文件」语义。
|
||||
metadata={"taskId": task_id, "agent_id": agent_id},
|
||||
context=context,
|
||||
multitask_strategy="reject",
|
||||
)
|
||||
|
||||
# enforce_access=False:开放接口已自行解析 admin 配置的 3Q 智能体,不再按当前(无)登录用户做可见性校验。
|
||||
record = await start_run(run_body, thread_id, request, enforce_access=False)
|
||||
|
||||
return ThreeQAskResponse(
|
||||
thread_id=record.thread_id,
|
||||
run_id=record.run_id,
|
||||
agent_id=agent_id,
|
||||
status=record.status.value,
|
||||
opening_text=opening_text,
|
||||
)
|
||||
@@ -451,6 +451,36 @@ class AgentModuleConfigUpdateRequest(BaseModel):
|
||||
tag_ids: list[str] = Field(default_factory=list, description="Full replacement list of selected agent tag ids")
|
||||
|
||||
|
||||
class LoginWhitelistResponse(BaseModel):
|
||||
enabled: bool = Field(..., description="是否启用登录白名单(关=所有人可登录,开=仅已放行用户/admin 可登录)")
|
||||
|
||||
|
||||
class LoginWhitelistUpdateRequest(BaseModel):
|
||||
enabled: bool | None = None
|
||||
|
||||
|
||||
@router.get("/login-whitelist", response_model=LoginWhitelistResponse)
|
||||
async def get_login_whitelist(request: Request) -> LoginWhitelistResponse:
|
||||
"""Return the login-whitelist master switch. Admin only (它驱动谁能登录,不公开)."""
|
||||
await _require_admin(request)
|
||||
return LoginWhitelistResponse(enabled=load_system_settings().login_whitelist.enabled)
|
||||
|
||||
|
||||
@router.put("/login-whitelist", response_model=LoginWhitelistResponse)
|
||||
async def update_login_whitelist(body: LoginWhitelistUpdateRequest, request: Request) -> LoginWhitelistResponse:
|
||||
"""Toggle the login-whitelist master switch. Admin only."""
|
||||
await _require_admin(request)
|
||||
|
||||
current = load_system_settings()
|
||||
update: dict[str, object] = {}
|
||||
fields = body.model_dump(exclude_unset=True)
|
||||
if "enabled" in fields and fields["enabled"] is not None:
|
||||
update["enabled"] = bool(fields["enabled"])
|
||||
updated = current.login_whitelist.model_copy(update=update)
|
||||
saved = save_system_settings(current.model_copy(update={"login_whitelist": updated}))
|
||||
return LoginWhitelistResponse(enabled=saved.login_whitelist.enabled)
|
||||
|
||||
|
||||
@router.get("/agent-modules/{key}", response_model=AgentModuleConfigResponse)
|
||||
async def get_agent_module_config(key: str) -> AgentModuleConfigResponse:
|
||||
"""Return the agent tag ids configured for ``key`` (readable by any user —
|
||||
|
||||
@@ -62,6 +62,11 @@ class TaskButton(BaseModel):
|
||||
open_mode: str = Field(default="blank", max_length=16)
|
||||
# url 外链追加的登录参数列表(key + 取值来源)。
|
||||
login_params: list[TaskButtonLoginParam] = Field(default_factory=list)
|
||||
# url 跳转是否追加登录态(token 登录的上游 token + 登录用户名)。仅 token 登录时实际拼上。
|
||||
append_auth: bool = False
|
||||
# 追加 token / 用户名的查询参数名。
|
||||
auth_token_param: str = Field(default="token", max_length=64)
|
||||
auth_name_param: str = Field(default="username", max_length=64)
|
||||
enabled: bool = True
|
||||
sort_order: int = 0
|
||||
|
||||
|
||||
@@ -529,6 +529,8 @@ async def start_run(
|
||||
body: Any,
|
||||
thread_id: str,
|
||||
request: Request,
|
||||
*,
|
||||
enforce_access: bool = True,
|
||||
) -> RunRecord:
|
||||
"""Create a RunRecord and launch the background agent task.
|
||||
|
||||
@@ -560,7 +562,13 @@ async def start_run(
|
||||
disconnect = DisconnectMode.cancel if body.on_disconnect == "cancel" else DisconnectMode.continue_
|
||||
|
||||
t_pre_enforce = time.perf_counter()
|
||||
await _enforce_agent_access(body, request)
|
||||
# ``enforce_access=False`` is for intentionally open/unauthenticated entry
|
||||
# points (e.g. /api/open/3qfx/ask) that resolve the agent themselves from an
|
||||
# admin-configured mapping rather than from a per-user-visible assistant_id.
|
||||
# Those run under the "default" bucket, where a user-owned unpublished agent
|
||||
# would otherwise 404 the access check.
|
||||
if enforce_access:
|
||||
await _enforce_agent_access(body, request)
|
||||
t_post_enforce = time.perf_counter()
|
||||
|
||||
try:
|
||||
|
||||
Reference in new issue
Block a user