sync update from LAN repo (source master @ ca48c4ec)

This commit is contained in:
gozeros committed 2026-11-05 10:53:54 +08:00
1 parent 8bc8b0e082
commit ea9dcff9c0
873 files changed
+107866 -14011

No files matched your search

@@ -24,11 +24,14 @@ from deerflow.config.system_settings import (
HtmlMapSettings,
LeaderboardSettings,
ModelConcurrencySettings,
ModelPromptSuffix,
PluginDomainAgentMapping,
PluginManagementSettings,
PromptPrefixSettings,
PublishSquare,
PublishSquaresSettings,
RetryKeepPartialSettings,
RoundtableRoomLimitSettings,
SkillCompressionSettings,
StrategyProjectSettings,
WordHeadingNumberingStyle,
@@ -40,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")
@@ -121,6 +250,8 @@ 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
@@ -179,6 +310,16 @@ 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
@@ -197,6 +338,8 @@ 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,
@@ -389,7 +532,22 @@ 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",
@@ -398,10 +556,39 @@ class ConversationContextResponse(BaseModel):
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):
recent_turn_window_enabled: bool
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):
@@ -480,10 +667,36 @@ 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,
)
@@ -498,20 +711,72 @@ async def update_conversation_context_setting(
body: ConversationContextUpdateRequest,
request: Request,
) -> ConversationContextResponse:
"""Enable or disable the fixed recent-three-turn window. Admin only."""
"""Update the recent-turn window or ordinary-chat round cap. Admin only."""
await _require_admin(request)
current = load_system_settings()
updated = current.conversation_context.model_copy(
update={"recent_turn_window_enabled": body.recent_turn_window_enabled}
)
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 recent-turn window changed: enabled=%s retained_turns=3",
"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,
@@ -806,6 +1071,38 @@ async def update_html_map_settings(
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."""
@@ -939,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")
@@ -948,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)
@@ -1021,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,
@@ -1079,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: