sync update from LAN repo (source dhk-1 @ 3b1ec5b4)
This commit is contained in:
1 parent
da6521b6cb
commit
264e2200d6
995 files changed
+148105
-13399
No files matched your search
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Literal
|
||||
from urllib.parse import urlparse
|
||||
@@ -11,22 +12,29 @@ from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.gateway.auth.password import hash_password_async
|
||||
from app.gateway.deps import get_optional_user_from_request
|
||||
from app.gateway.deps import get_current_user_from_request, get_optional_user_from_request
|
||||
from deerflow.config import get_app_config
|
||||
from deerflow.config.system_settings import (
|
||||
BUILTIN_THEME_IDS,
|
||||
AppearanceRouteParam,
|
||||
AuthenticationSettings,
|
||||
CompactShortcutButton,
|
||||
ConversationContextSettings,
|
||||
CustomThemePreset,
|
||||
HtmlMapSettings,
|
||||
LeaderboardSettings,
|
||||
ModelConcurrencySettings,
|
||||
ModelPromptSuffix,
|
||||
PluginDomainAgentMapping,
|
||||
PluginManagementSettings,
|
||||
PromptPrefixSettings,
|
||||
PublishSquare,
|
||||
PublishSquaresSettings,
|
||||
RetryKeepPartialSettings,
|
||||
RoundtableRoomLimitSettings,
|
||||
SkillCompressionSettings,
|
||||
StrategyProjectSettings,
|
||||
WordHeadingNumberingStyle,
|
||||
WriteFileCompatibilitySettings,
|
||||
get_module_tag_ids,
|
||||
list_publish_squares,
|
||||
@@ -35,12 +43,138 @@ from deerflow.config.system_settings import (
|
||||
save_system_settings,
|
||||
set_module_tag_ids,
|
||||
)
|
||||
from deerflow.html_runtime.addresses import (
|
||||
html_map_tile_url,
|
||||
html_runtime_base_url,
|
||||
normalize_html_map_tile_url,
|
||||
normalize_html_runtime_base_url,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/api/system-settings", tags=["system-settings"])
|
||||
|
||||
|
||||
@router.get("/model-prompt-suffixes", response_model=dict[str, ModelPromptSuffix])
|
||||
async def get_model_prompt_suffixes(request: Request) -> dict[str, ModelPromptSuffix]:
|
||||
await _require_model_prompt_admin(request)
|
||||
return load_system_settings().model_prompt_suffixes
|
||||
|
||||
|
||||
@router.put("/model-prompt-suffixes/{model_name:path}", response_model=ModelPromptSuffix)
|
||||
async def update_model_prompt_suffix(model_name: str, body: ModelPromptSuffix, request: Request) -> ModelPromptSuffix:
|
||||
await _require_model_prompt_admin(request)
|
||||
current = load_system_settings()
|
||||
# Retain editable entries for temporarily removed models so an administrator
|
||||
# can still disable them. New entries must target a real configured model.
|
||||
if get_app_config().get_model_config(model_name) is None and model_name not in current.model_prompt_suffixes:
|
||||
raise HTTPException(status_code=404, detail="模型不存在")
|
||||
if body.enabled and not body.prompt.strip():
|
||||
raise HTTPException(status_code=422, detail="启用时请填写追加提示词")
|
||||
current.model_prompt_suffixes[model_name] = body
|
||||
save_system_settings(current)
|
||||
return body
|
||||
|
||||
|
||||
async def _require_model_prompt_admin(request: Request) -> None:
|
||||
user = await get_optional_user_from_request(request)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="请先登录")
|
||||
if getattr(user, "system_role", None) != "admin":
|
||||
raise HTTPException(status_code=403, detail="仅管理员可管理模型追加提示词")
|
||||
|
||||
|
||||
class ApiReadCacheResponse(BaseModel):
|
||||
enabled: bool = False
|
||||
redis_configured: bool = False
|
||||
ttl_seconds: int = 300
|
||||
max_value_bytes: int = 524288
|
||||
browser_status_enabled: bool = True
|
||||
collections: list[dict] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ApiReadCacheUpdateRequest(BaseModel):
|
||||
enabled: bool | None = None
|
||||
ttl_seconds: int | None = Field(default=None, ge=1, le=3600)
|
||||
browser_status_enabled: bool | None = None
|
||||
collection_overrides: dict[str, bool] | None = None
|
||||
|
||||
|
||||
async def _require_performance_admin(request: Request) -> None:
|
||||
# Preserve no-auth deployments, but never swallow an invalid/missing login.
|
||||
user = await get_current_user_from_request(request)
|
||||
if user is not None and getattr(user, "system_role", None) != "admin":
|
||||
raise HTTPException(status_code=403, detail="仅管理员可管理接口性能设置")
|
||||
|
||||
|
||||
@router.get("/api-read-cache", response_model=ApiReadCacheResponse)
|
||||
async def get_api_read_cache_setting(request: Request) -> ApiReadCacheResponse:
|
||||
"""Read the persisted administrator-controlled Redis cache switch."""
|
||||
|
||||
await _require_performance_admin(request)
|
||||
from app.gateway.api_read_cache import api_read_cache_redis_configured, get_api_cache_controls, get_api_read_cache_settings
|
||||
|
||||
config = getattr(request.app.state, "config", None)
|
||||
cache_config = getattr(config, "api_read_cache", None)
|
||||
enabled, ttl_seconds = await get_api_read_cache_settings(config, force_refresh=True)
|
||||
return ApiReadCacheResponse(
|
||||
enabled=enabled,
|
||||
redis_configured=api_read_cache_redis_configured(config),
|
||||
ttl_seconds=ttl_seconds,
|
||||
max_value_bytes=int(getattr(cache_config, "max_value_bytes", 524288) or 524288),
|
||||
**await get_api_cache_controls(config),
|
||||
)
|
||||
|
||||
|
||||
@router.put("/api-read-cache", response_model=ApiReadCacheResponse)
|
||||
async def update_api_read_cache_setting(
|
||||
request: Request,
|
||||
body: ApiReadCacheUpdateRequest,
|
||||
) -> ApiReadCacheResponse:
|
||||
"""Save the Redis cache switch to MySQL and apply it immediately."""
|
||||
|
||||
await _require_performance_admin(request)
|
||||
from app.gateway.api_read_cache import (
|
||||
API_READ_CACHE_COLLECTIONS,
|
||||
api_read_cache_redis_configured,
|
||||
get_api_cache_controls,
|
||||
get_api_read_cache_settings,
|
||||
invalidate_cached_collection,
|
||||
save_api_read_cache_settings,
|
||||
)
|
||||
|
||||
config = getattr(request.app.state, "config", None)
|
||||
unknown = set(body.collection_overrides or {}) - set(API_READ_CACHE_COLLECTIONS)
|
||||
if unknown:
|
||||
raise HTTPException(status_code=422, detail=f"未知缓存接口:{', '.join(sorted(unknown))}")
|
||||
try:
|
||||
await save_api_read_cache_settings(
|
||||
body.enabled, body.ttl_seconds, config=config,
|
||||
collection_overrides=body.collection_overrides,
|
||||
browser_status_enabled=body.browser_status_enabled,
|
||||
)
|
||||
await asyncio.gather(
|
||||
*(
|
||||
invalidate_cached_collection(config, collection, force=True)
|
||||
for collection in API_READ_CACHE_COLLECTIONS
|
||||
)
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception("Could not persist API Redis cache setting")
|
||||
raise HTTPException(status_code=503, detail="无法将缓存设置保存到 MySQL") from exc
|
||||
cache_config = getattr(config, "api_read_cache", None)
|
||||
enabled, ttl_seconds = await get_api_read_cache_settings(config, force_refresh=True)
|
||||
return ApiReadCacheResponse(
|
||||
enabled=enabled,
|
||||
redis_configured=api_read_cache_redis_configured(config),
|
||||
ttl_seconds=ttl_seconds,
|
||||
max_value_bytes=int(getattr(cache_config, "max_value_bytes", 524288) or 524288),
|
||||
**await get_api_cache_controls(config),
|
||||
)
|
||||
|
||||
|
||||
class PromptPrefixResponse(BaseModel):
|
||||
image_generation_unavailable_hint_enabled: bool = False
|
||||
python_dependency_delete_protection_enabled: bool = False
|
||||
enabled: bool = Field(..., description="Whether the toggle is exposed to users")
|
||||
switch_label: str = Field(..., description="Toggle label shown in the chat input")
|
||||
prompt_prefix: str = Field(..., description="Prefix text prepended to the first user message")
|
||||
@@ -48,6 +182,10 @@ class PromptPrefixResponse(BaseModel):
|
||||
default=False,
|
||||
description="Whether formal Markdown heading rules are injected into ordinary Q&A system prompts",
|
||||
)
|
||||
word_heading_numbering_style: WordHeadingNumberingStyle = Field(
|
||||
default="hybrid_decimal",
|
||||
description="Heading-numbering preset used by Markdown-to-Word export",
|
||||
)
|
||||
|
||||
|
||||
class KnowledgeBaseProductVersionResponse(BaseModel):
|
||||
@@ -112,10 +250,13 @@ async def update_strategy_project_settings(
|
||||
|
||||
|
||||
class PromptPrefixUpdateRequest(BaseModel):
|
||||
image_generation_unavailable_hint_enabled: bool | None = None
|
||||
python_dependency_delete_protection_enabled: bool | None = None
|
||||
enabled: bool | None = None
|
||||
switch_label: str | None = None
|
||||
prompt_prefix: str | None = None
|
||||
ordinary_qa_markdown_format_enabled: bool | None = None
|
||||
word_heading_numbering_style: WordHeadingNumberingStyle | None = None
|
||||
|
||||
|
||||
class PluginDomainAgentMappingItem(BaseModel):
|
||||
@@ -150,15 +291,35 @@ class PrivateSquareUpdateRequest(BaseModel):
|
||||
|
||||
|
||||
class CitationDisplayResponse(BaseModel):
|
||||
retrieved_files_enabled: bool = True
|
||||
reference_mode_enabled: bool = Field(default=False, description="Whether reference-mode entry points are exposed to users")
|
||||
cleanup_words: list[str] = Field(default_factory=list, description="Global citation cleanup words")
|
||||
|
||||
|
||||
class CitationDisplayUpdateRequest(BaseModel):
|
||||
retrieved_files_enabled: bool | None = None
|
||||
reference_mode_enabled: bool | None = None
|
||||
cleanup_words: list[str] | None = None
|
||||
|
||||
|
||||
class HtmlMapSettingsResponse(BaseModel):
|
||||
engine: Literal["echarts", "leaflet"] = "echarts"
|
||||
|
||||
|
||||
class HtmlMapSettingsUpdateRequest(BaseModel):
|
||||
engine: Literal["echarts", "leaflet"] | None = None
|
||||
|
||||
|
||||
class HtmlRuntimeSettingsResponse(BaseModel):
|
||||
base_url: str
|
||||
map_tile_url: str
|
||||
|
||||
|
||||
class HtmlRuntimeSettingsUpdateRequest(BaseModel):
|
||||
base_url: str
|
||||
map_tile_url: str
|
||||
|
||||
|
||||
class LeaderboardSettingsResponse(BaseModel):
|
||||
exclude_user_ids: list[str] = Field(default_factory=list)
|
||||
include_scheduled: bool = True
|
||||
@@ -177,10 +338,13 @@ class LeaderboardSettingsUpdateRequest(BaseModel):
|
||||
|
||||
def _to_response(settings: PromptPrefixSettings) -> PromptPrefixResponse:
|
||||
return PromptPrefixResponse(
|
||||
image_generation_unavailable_hint_enabled=settings.image_generation_unavailable_hint_enabled,
|
||||
python_dependency_delete_protection_enabled=settings.python_dependency_delete_protection_enabled,
|
||||
enabled=settings.enabled,
|
||||
switch_label=settings.switch_label,
|
||||
prompt_prefix=settings.prompt_prefix,
|
||||
ordinary_qa_markdown_format_enabled=settings.ordinary_qa_markdown_format_enabled,
|
||||
word_heading_numbering_style=settings.word_heading_numbering_style,
|
||||
)
|
||||
|
||||
|
||||
@@ -368,6 +532,91 @@ class WriteFileCompatibilityUpdateRequest(BaseModel):
|
||||
enabled: bool
|
||||
|
||||
|
||||
class RetryKeepPartialResponse(BaseModel):
|
||||
enabled: bool = Field(
|
||||
default=True,
|
||||
description=(
|
||||
"Keep the already-streamed partial answer visible when a model "
|
||||
"call is silently retried"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class RetryKeepPartialUpdateRequest(BaseModel):
|
||||
enabled: bool
|
||||
|
||||
|
||||
class ConversationContextResponse(BaseModel):
|
||||
max_run_steps: int = 1000
|
||||
recent_turn_window_enabled: bool = Field(
|
||||
default=False,
|
||||
description="Whether all lead-agent model requests keep only the latest three dialogue turns",
|
||||
)
|
||||
recent_turns: int = Field(
|
||||
default=3,
|
||||
description="Fixed number of real user turns retained by the sliding window",
|
||||
)
|
||||
max_conversation_rounds: int = Field(
|
||||
default=20,
|
||||
ge=1,
|
||||
le=50,
|
||||
description="Maximum real user turns allowed in one ordinary chat thread",
|
||||
)
|
||||
use_question_as_title: bool = Field(
|
||||
default=False,
|
||||
description="Whether the first user question is the final title, without post-answer title generation",
|
||||
)
|
||||
|
||||
|
||||
class ConversationContextUpdateRequest(BaseModel):
|
||||
max_run_steps: int | None = Field(default=None, ge=20, le=10000, strict=True)
|
||||
recent_turn_window_enabled: bool | None = None
|
||||
max_conversation_rounds: int | None = Field(default=None, ge=1, le=50)
|
||||
use_question_as_title: bool | None = None
|
||||
|
||||
|
||||
class RoundtableRoomLimitResponse(BaseModel):
|
||||
enabled: bool = True
|
||||
max_rooms: int = 3
|
||||
max_hold_minutes: int = 30
|
||||
max_cycles: int = 8
|
||||
write_file_compatibility_enabled: bool = False
|
||||
|
||||
|
||||
class RoundtableRoomLimitUpdateRequest(BaseModel):
|
||||
enabled: bool | None = None
|
||||
max_rooms: int | None = Field(default=None, ge=1, le=20)
|
||||
max_hold_minutes: int | None = Field(default=None, ge=1, le=1440)
|
||||
max_cycles: int | None = Field(default=None, ge=2, le=100)
|
||||
write_file_compatibility_enabled: bool | None = None
|
||||
|
||||
|
||||
class OrdinaryKnowledgeRetrievalResponse(BaseModel):
|
||||
smart_reasoning_enabled: bool = Field(
|
||||
default=False,
|
||||
description="Whether users may select smart multi-round ordinary-knowledge retrieval",
|
||||
)
|
||||
advanced_management_enabled: bool = Field(
|
||||
default=False,
|
||||
description="Whether advanced ordinary-knowledge management entries are exposed",
|
||||
)
|
||||
|
||||
|
||||
class OrdinaryKnowledgeRetrievalUpdateRequest(BaseModel):
|
||||
smart_reasoning_enabled: bool | None = None
|
||||
advanced_management_enabled: bool | None = None
|
||||
|
||||
|
||||
def _knowledge_retrieval_settings_store(request: Request):
|
||||
store = getattr(request.app.state, "knowledge_retrieval_settings_store", None)
|
||||
if store is None:
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Knowledge retrieval settings store is not available",
|
||||
)
|
||||
return store
|
||||
|
||||
|
||||
@router.get("/memory", response_model=MemoryRuntimeResponse)
|
||||
async def get_memory_runtime_setting() -> MemoryRuntimeResponse:
|
||||
return MemoryRuntimeResponse(enabled=load_system_settings().memory.enabled)
|
||||
@@ -418,6 +667,176 @@ async def update_write_file_compatibility_setting(
|
||||
)
|
||||
|
||||
|
||||
@router.get("/retry-keep-partial", response_model=RetryKeepPartialResponse)
|
||||
async def get_retry_keep_partial_setting() -> RetryKeepPartialResponse:
|
||||
"""Return the retry-keeps-partial display switch (readable by chat clients)."""
|
||||
settings = load_system_settings().retry_keep_partial
|
||||
return RetryKeepPartialResponse(enabled=settings.enabled)
|
||||
|
||||
|
||||
@router.put("/retry-keep-partial", response_model=RetryKeepPartialResponse)
|
||||
async def update_retry_keep_partial_setting(
|
||||
body: RetryKeepPartialUpdateRequest,
|
||||
request: Request,
|
||||
) -> RetryKeepPartialResponse:
|
||||
await _require_admin(request)
|
||||
current = load_system_settings()
|
||||
updated = RetryKeepPartialSettings(enabled=body.enabled)
|
||||
saved = save_system_settings(current.model_copy(update={"retry_keep_partial": updated}))
|
||||
logger.info(
|
||||
"Retry-keeps-partial display switch changed: enabled=%s",
|
||||
saved.retry_keep_partial.enabled,
|
||||
)
|
||||
return RetryKeepPartialResponse(enabled=saved.retry_keep_partial.enabled)
|
||||
|
||||
|
||||
def _conversation_context_response(settings: ConversationContextSettings) -> ConversationContextResponse:
|
||||
return ConversationContextResponse(
|
||||
max_run_steps=settings.max_run_steps,
|
||||
recent_turn_window_enabled=settings.recent_turn_window_enabled,
|
||||
recent_turns=3,
|
||||
max_conversation_rounds=settings.max_conversation_rounds,
|
||||
use_question_as_title=settings.use_question_as_title,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/conversation-context", response_model=ConversationContextResponse)
|
||||
async def get_conversation_context_setting() -> ConversationContextResponse:
|
||||
"""Return the global recent-turn window mode (readable by chat clients)."""
|
||||
return _conversation_context_response(load_system_settings().conversation_context)
|
||||
|
||||
|
||||
@router.put("/conversation-context", response_model=ConversationContextResponse)
|
||||
async def update_conversation_context_setting(
|
||||
body: ConversationContextUpdateRequest,
|
||||
request: Request,
|
||||
) -> ConversationContextResponse:
|
||||
"""Update the recent-turn window or ordinary-chat round cap. Admin only."""
|
||||
await _require_admin(request)
|
||||
current = load_system_settings()
|
||||
updated_fields = body.model_dump(exclude_unset=True, exclude_none=True)
|
||||
if not updated_fields:
|
||||
raise HTTPException(status_code=422, detail="至少需要提供一个上下文设置项")
|
||||
updated = current.conversation_context.model_copy(update=updated_fields)
|
||||
saved = save_system_settings(current.model_copy(update={"conversation_context": updated}))
|
||||
logger.info(
|
||||
"Conversation runtime settings changed: recent_turn_window=%s use_question_as_title=%s max_conversation_rounds=%s max_run_steps=%s",
|
||||
saved.conversation_context.recent_turn_window_enabled,
|
||||
saved.conversation_context.use_question_as_title,
|
||||
saved.conversation_context.max_conversation_rounds,
|
||||
saved.conversation_context.max_run_steps,
|
||||
)
|
||||
return _conversation_context_response(saved.conversation_context)
|
||||
|
||||
|
||||
def _roundtable_room_limit_response(settings: RoundtableRoomLimitSettings) -> RoundtableRoomLimitResponse:
|
||||
return RoundtableRoomLimitResponse(
|
||||
enabled=settings.enabled,
|
||||
max_rooms=settings.max_rooms,
|
||||
max_hold_minutes=settings.max_hold_minutes,
|
||||
max_cycles=settings.max_cycles,
|
||||
write_file_compatibility_enabled=settings.write_file_compatibility_enabled,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/roundtable-room-limit", response_model=RoundtableRoomLimitResponse)
|
||||
async def get_roundtable_room_limit_setting() -> RoundtableRoomLimitResponse:
|
||||
"""Return the global step-2 room and closeout settings."""
|
||||
return _roundtable_room_limit_response(load_system_settings().roundtable_room_limit)
|
||||
|
||||
|
||||
@router.put("/roundtable-room-limit", response_model=RoundtableRoomLimitResponse)
|
||||
async def update_roundtable_room_limit_setting(
|
||||
body: RoundtableRoomLimitUpdateRequest,
|
||||
request: Request,
|
||||
) -> RoundtableRoomLimitResponse:
|
||||
"""Update global room limits and the coordinator closeout round. Admin only."""
|
||||
await _require_admin(request)
|
||||
current = load_system_settings()
|
||||
updates: dict[str, object] = {}
|
||||
if body.enabled is not None:
|
||||
updates["enabled"] = body.enabled
|
||||
if body.max_rooms is not None:
|
||||
updates["max_rooms"] = body.max_rooms
|
||||
if body.max_hold_minutes is not None:
|
||||
updates["max_hold_minutes"] = body.max_hold_minutes
|
||||
if body.max_cycles is not None:
|
||||
updates["max_cycles"] = body.max_cycles
|
||||
if body.write_file_compatibility_enabled is not None:
|
||||
updates["write_file_compatibility_enabled"] = body.write_file_compatibility_enabled
|
||||
updated = current.roundtable_room_limit.model_copy(update=updates)
|
||||
saved = save_system_settings(current.model_copy(update={"roundtable_room_limit": updated}))
|
||||
logger.info(
|
||||
"Roundtable runtime limits changed: enabled=%s max_rooms=%s max_hold_minutes=%s max_cycles=%s write_file_compatibility=%s",
|
||||
saved.roundtable_room_limit.enabled,
|
||||
saved.roundtable_room_limit.max_rooms,
|
||||
saved.roundtable_room_limit.max_hold_minutes,
|
||||
saved.roundtable_room_limit.max_cycles,
|
||||
saved.roundtable_room_limit.write_file_compatibility_enabled,
|
||||
)
|
||||
return _roundtable_room_limit_response(saved.roundtable_room_limit)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/ordinary-knowledge-retrieval",
|
||||
response_model=OrdinaryKnowledgeRetrievalResponse,
|
||||
)
|
||||
async def get_ordinary_knowledge_retrieval_setting(
|
||||
request: Request,
|
||||
) -> OrdinaryKnowledgeRetrievalResponse:
|
||||
"""Return the DB-backed smart-reasoning availability flag."""
|
||||
|
||||
store = _knowledge_retrieval_settings_store(request)
|
||||
enabled, advanced_enabled = await asyncio.gather(
|
||||
store.get(),
|
||||
store.get_advanced_management_enabled(),
|
||||
)
|
||||
return OrdinaryKnowledgeRetrievalResponse(
|
||||
smart_reasoning_enabled=enabled,
|
||||
advanced_management_enabled=advanced_enabled,
|
||||
)
|
||||
|
||||
|
||||
@router.put(
|
||||
"/ordinary-knowledge-retrieval",
|
||||
response_model=OrdinaryKnowledgeRetrievalResponse,
|
||||
)
|
||||
async def update_ordinary_knowledge_retrieval_setting(
|
||||
body: OrdinaryKnowledgeRetrievalUpdateRequest,
|
||||
request: Request,
|
||||
) -> OrdinaryKnowledgeRetrievalResponse:
|
||||
"""Enable or disable smart ordinary-knowledge retrieval. Admin only."""
|
||||
|
||||
await _require_admin(request)
|
||||
actor = await get_optional_user_from_request(request)
|
||||
actor_id = getattr(actor, "id", None)
|
||||
actor_value = str(actor_id) if actor_id is not None else None
|
||||
store = _knowledge_retrieval_settings_store(request)
|
||||
if body.smart_reasoning_enabled is not None:
|
||||
await store.set(
|
||||
body.smart_reasoning_enabled,
|
||||
updated_by=actor_value,
|
||||
)
|
||||
if body.advanced_management_enabled is not None:
|
||||
await store.set_advanced_management_enabled(
|
||||
body.advanced_management_enabled,
|
||||
updated_by=actor_value,
|
||||
)
|
||||
enabled, advanced_enabled = await asyncio.gather(
|
||||
store.get(),
|
||||
store.get_advanced_management_enabled(),
|
||||
)
|
||||
logger.info(
|
||||
"Ordinary-knowledge settings changed: smart_reasoning=%s advanced_management=%s",
|
||||
enabled,
|
||||
advanced_enabled,
|
||||
)
|
||||
return OrdinaryKnowledgeRetrievalResponse(
|
||||
smart_reasoning_enabled=enabled,
|
||||
advanced_management_enabled=advanced_enabled,
|
||||
)
|
||||
|
||||
|
||||
def _skill_compression_to_response(settings: SkillCompressionSettings) -> SkillCompressionResponse:
|
||||
return SkillCompressionResponse(
|
||||
enabled=settings.enabled,
|
||||
@@ -599,6 +1018,7 @@ async def get_citation_display() -> CitationDisplayResponse:
|
||||
settings = load_system_settings().citation_display
|
||||
return CitationDisplayResponse(
|
||||
reference_mode_enabled=settings.reference_mode_enabled,
|
||||
retrieved_files_enabled=settings.retrieved_files_enabled,
|
||||
cleanup_words=settings.cleanup_words,
|
||||
)
|
||||
|
||||
@@ -616,16 +1036,73 @@ async def update_citation_display(
|
||||
update: dict[str, object] = {}
|
||||
if "reference_mode_enabled" in fields and fields["reference_mode_enabled"] is not None:
|
||||
update["reference_mode_enabled"] = bool(fields["reference_mode_enabled"])
|
||||
if "retrieved_files_enabled" in fields and fields["retrieved_files_enabled"] is not None:
|
||||
update["retrieved_files_enabled"] = bool(fields["retrieved_files_enabled"])
|
||||
if "cleanup_words" in fields and fields["cleanup_words"] is not None:
|
||||
update["cleanup_words"] = [str(item).strip() for item in fields["cleanup_words"] if str(item).strip()]
|
||||
updated = current.citation_display.model_copy(update=update)
|
||||
saved = save_system_settings(current.model_copy(update={"citation_display": updated}))
|
||||
return CitationDisplayResponse(
|
||||
reference_mode_enabled=saved.citation_display.reference_mode_enabled,
|
||||
retrieved_files_enabled=saved.citation_display.retrieved_files_enabled,
|
||||
cleanup_words=saved.citation_display.cleanup_words,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/html-map", response_model=HtmlMapSettingsResponse)
|
||||
async def get_html_map_settings() -> HtmlMapSettingsResponse:
|
||||
"""Return the map engine used by newly generated HTML pages."""
|
||||
settings: HtmlMapSettings = load_system_settings().html_map
|
||||
return HtmlMapSettingsResponse(engine=settings.engine)
|
||||
|
||||
|
||||
@router.put("/html-map", response_model=HtmlMapSettingsResponse)
|
||||
async def update_html_map_settings(
|
||||
body: HtmlMapSettingsUpdateRequest,
|
||||
request: Request,
|
||||
) -> HtmlMapSettingsResponse:
|
||||
"""Choose ECharts or the Leaflet map webpage for new HTML maps. Admin only."""
|
||||
await _require_admin(request)
|
||||
current = load_system_settings()
|
||||
fields = body.model_dump(exclude_unset=True)
|
||||
engine = fields.get("engine", current.html_map.engine)
|
||||
updated = current.html_map.model_copy(update={"engine": engine or "echarts"})
|
||||
saved = save_system_settings(current.model_copy(update={"html_map": updated}))
|
||||
return HtmlMapSettingsResponse(engine=saved.html_map.engine)
|
||||
|
||||
|
||||
@router.get("/html-runtime", response_model=HtmlRuntimeSettingsResponse)
|
||||
async def get_html_runtime_settings() -> HtmlRuntimeSettingsResponse:
|
||||
"""Return the addresses newly generated HTML pages will use."""
|
||||
return HtmlRuntimeSettingsResponse(
|
||||
base_url=html_runtime_base_url(),
|
||||
map_tile_url=html_map_tile_url(),
|
||||
)
|
||||
|
||||
|
||||
@router.put("/html-runtime", response_model=HtmlRuntimeSettingsResponse)
|
||||
async def update_html_runtime_settings(
|
||||
body: HtmlRuntimeSettingsUpdateRequest,
|
||||
request: Request,
|
||||
) -> HtmlRuntimeSettingsResponse:
|
||||
"""Save the browser-reachable runtime and map-tile addresses. Admin only."""
|
||||
await _require_admin(request)
|
||||
try:
|
||||
base_url = normalize_html_runtime_base_url(body.base_url)
|
||||
map_tile_url = normalize_html_map_tile_url(body.map_tile_url)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
current = load_system_settings()
|
||||
updated = current.html_runtime.model_copy(
|
||||
update={"base_url": base_url, "map_tile_url": map_tile_url}
|
||||
)
|
||||
saved = save_system_settings(current.model_copy(update={"html_runtime": updated}))
|
||||
return HtmlRuntimeSettingsResponse(
|
||||
base_url=saved.html_runtime.base_url,
|
||||
map_tile_url=saved.html_runtime.map_tile_url,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/private-square", response_model=PrivateSquareStatusResponse)
|
||||
async def get_private_square_status() -> PrivateSquareStatusResponse:
|
||||
"""Return whether the private square is enabled and a password is set."""
|
||||
@@ -759,6 +1236,12 @@ class AppearanceResponse(BaseModel):
|
||||
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")
|
||||
default_layout_mode: Literal["full", "compact"] = Field(..., description="System default interface layout — full (sidebar + header) or compact (hidden)")
|
||||
default_composer_width_full: int = Field(..., description="System default composer width percent for full layout. 100 keeps the built-in width.")
|
||||
default_composer_width_compact: int = Field(..., description="System default composer width percent for compact layout. 100 keeps the built-in width.")
|
||||
default_composer_height_full: int = Field(..., description="System default composer height percent for full layout. 100 keeps the built-in height.")
|
||||
default_composer_height_compact: int = Field(..., description="System default composer height percent for compact layout. 100 keeps the built-in height.")
|
||||
default_agent_composer_width: int = Field(..., description="System default agent composer width percent. 100 keeps the built-in width.")
|
||||
default_agent_composer_height: int = Field(..., description="System default agent composer height percent. 100 keeps the built-in height.")
|
||||
compact_shortcut_buttons: list[CompactShortcutButton] = Field(default_factory=list, description="Shortcut buttons rendered in top bars")
|
||||
custom_themes: list[CustomThemePreset] = Field(default_factory=list, description="Administrator-managed runtime theme presets")
|
||||
|
||||
@@ -768,6 +1251,12 @@ class AppearanceUpdateRequest(BaseModel):
|
||||
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)
|
||||
default_composer_width_full: int | None = Field(default=None)
|
||||
default_composer_width_compact: int | None = Field(default=None)
|
||||
default_composer_height_full: int | None = Field(default=None)
|
||||
default_composer_height_compact: int | None = Field(default=None)
|
||||
default_agent_composer_width: int | None = Field(default=None)
|
||||
default_agent_composer_height: int | None = Field(default=None)
|
||||
compact_shortcut_buttons: list[CompactShortcutButton] | None = Field(default=None)
|
||||
custom_themes: list[CustomThemePreset] | None = Field(default=None)
|
||||
|
||||
@@ -841,6 +1330,12 @@ def _appearance_response(appearance) -> AppearanceResponse:
|
||||
default_skill_view=appearance.default_skill_view,
|
||||
default_agent_view=appearance.default_agent_view,
|
||||
default_layout_mode=appearance.default_layout_mode,
|
||||
default_composer_width_full=appearance.default_composer_width_full,
|
||||
default_composer_width_compact=appearance.default_composer_width_compact,
|
||||
default_composer_height_full=appearance.default_composer_height_full,
|
||||
default_composer_height_compact=appearance.default_composer_height_compact,
|
||||
default_agent_composer_width=appearance.default_agent_composer_width,
|
||||
default_agent_composer_height=appearance.default_agent_composer_height,
|
||||
compact_shortcut_buttons=sorted(
|
||||
appearance.compact_shortcut_buttons,
|
||||
key=lambda item: item.sort_order,
|
||||
@@ -899,7 +1394,17 @@ async def update_appearance_settings(body: AppearanceUpdateRequest, request: Req
|
||||
current = load_system_settings()
|
||||
fields = body.model_dump(exclude_unset=True)
|
||||
update: dict[str, object] = {}
|
||||
for key in ("default_skill_view", "default_agent_view", "default_layout_mode"):
|
||||
for key in (
|
||||
"default_skill_view",
|
||||
"default_agent_view",
|
||||
"default_layout_mode",
|
||||
"default_composer_width_full",
|
||||
"default_composer_width_compact",
|
||||
"default_composer_height_full",
|
||||
"default_composer_height_compact",
|
||||
"default_agent_composer_width",
|
||||
"default_agent_composer_height",
|
||||
):
|
||||
if key in fields and fields[key] is not None:
|
||||
update[key] = fields[key]
|
||||
if "compact_shortcut_buttons" in fields and body.compact_shortcut_buttons is not None:
|
||||
@@ -962,6 +1467,27 @@ class LoginWhitelistResponse(BaseModel):
|
||||
enabled: bool = Field(..., description="是否启用登录白名单(关=所有人可登录,开=仅已放行用户/admin 可登录)")
|
||||
|
||||
|
||||
@router.get("/authentication", response_model=AuthenticationSettings)
|
||||
async def get_authentication_settings(request: Request) -> AuthenticationSettings:
|
||||
user = await get_current_user_from_request(request)
|
||||
if user.system_role != "admin":
|
||||
raise HTTPException(status_code=403, detail="仅管理员可设置登录方式")
|
||||
return load_system_settings().authentication
|
||||
|
||||
|
||||
@router.put("/authentication", response_model=AuthenticationSettings)
|
||||
async def update_authentication_settings(body: AuthenticationSettings, request: Request) -> AuthenticationSettings:
|
||||
user = await get_current_user_from_request(request)
|
||||
if user.system_role != "admin":
|
||||
raise HTTPException(status_code=403, detail="仅管理员可设置登录方式")
|
||||
if not body.password_login_enabled and not body.sso_enabled:
|
||||
raise HTTPException(status_code=400, detail="请至少保留一种登录方式")
|
||||
if body.registration_enabled and not body.password_login_enabled:
|
||||
raise HTTPException(status_code=400, detail="开启自助注册前,请先开启账号密码登录")
|
||||
current = load_system_settings()
|
||||
return save_system_settings(current.model_copy(update={"authentication": body})).authentication
|
||||
|
||||
|
||||
class LoginWhitelistUpdateRequest(BaseModel):
|
||||
enabled: bool | None = None
|
||||
|
||||
|
||||
Reference in new issue
Block a user