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

@@ -160,6 +160,14 @@ class PromptPrefixSettings(BaseModel):
"""Admin-configurable first-message prompt prefix."""
enabled: bool = Field(default=False, description="Whether the prefix toggle is offered to users at all")
image_generation_unavailable_hint_enabled: bool = Field(
default=False,
description="Tell users image generation is unavailable instead of attempting to generate images.",
)
python_dependency_delete_protection_enabled: bool = Field(
default=False,
description="Inject guidance against standalone Python dependency deletion; installation and replacement remain allowed.",
)
switch_label: str = Field(default="加入立场前缀", description="Toggle label shown in the chat input")
prompt_prefix: str = Field(default="", description="Text prepended to the first user message when enabled")
ordinary_qa_markdown_format_enabled: bool = Field(
@@ -264,6 +272,30 @@ class AppearanceSettings(BaseModel):
default="compact",
description="Default interface layout for users who haven't picked their own — compact (hidden) / full (sidebar + header)",
)
default_composer_width_full: int = Field(
default=100,
description="Default ordinary-chat composer width percent for full layout, used when a user has not chosen their own. 100 keeps the built-in width.",
)
default_composer_width_compact: int = Field(
default=100,
description="Default ordinary-chat composer width percent for compact layout, used when a user has not chosen their own. 100 keeps the built-in width.",
)
default_composer_height_full: int = Field(
default=100,
description="Default ordinary-chat composer height percent for full layout, used when a user has not chosen their own. 100 keeps the built-in height.",
)
default_composer_height_compact: int = Field(
default=100,
description="Default ordinary-chat composer height percent for compact layout, used when a user has not chosen their own. 100 keeps the built-in height.",
)
default_agent_composer_width: int = Field(
default=100,
description="Default agent-chat composer width percent, used when a user has not chosen their own. 100 keeps the built-in width; the page still caps it at the parent column.",
)
default_agent_composer_height: int = Field(
default=100,
description="Default agent-chat composer height percent, used when a user has not chosen their own. 100 keeps the built-in height.",
)
compact_shortcut_buttons: list[CompactShortcutButton] = Field(
default_factory=_default_compact_shortcut_buttons,
description="Shortcut buttons rendered before the theme switcher in top bars",
@@ -274,6 +306,36 @@ class AppearanceSettings(BaseModel):
)
model_config = ConfigDict(extra="ignore")
@staticmethod
def _clamp_scale(value: object, low: int, high: int) -> int:
if value is None or value == "":
return 100
try:
parsed = int(round(float(value))) # type: ignore[arg-type]
except (TypeError, ValueError):
return 100
return min(high, max(low, parsed))
@field_validator("default_composer_width_full", "default_composer_width_compact", mode="before")
@classmethod
def _clamp_default_composer_width(cls, value: object) -> int:
return cls._clamp_scale(value, 60, 150)
@field_validator(
"default_composer_height_full",
"default_composer_height_compact",
"default_agent_composer_height",
mode="before",
)
@classmethod
def _clamp_default_composer_height(cls, value: object) -> int:
return cls._clamp_scale(value, 70, 200)
@field_validator("default_agent_composer_width", mode="before")
@classmethod
def _clamp_default_agent_composer_width(cls, value: object) -> int:
return cls._clamp_scale(value, 60, 400)
@field_validator("default_theme")
@classmethod
def _validate_default_theme(cls, value: str) -> str:
@@ -562,6 +624,37 @@ class MemoryRuntimeSettings(BaseModel):
model_config = ConfigDict(extra="ignore")
class ConversationContextSettings(BaseModel):
"""Deployment-wide short-context policy for chat model requests.
The recent-turn window is deliberately opt-in. When enabled, the lead
agent keeps the persisted conversation intact but sends only the latest
three real user turns (plus their assistant/tool continuations) to the
model. This avoids an extra summarization-model call while preserving the
complete transcript for the UI and checkpoint recovery.
"""
max_run_steps: int = Field(default=1000, ge=20, le=10000, strict=True)
recent_turn_window_enabled: bool = Field(
default=False,
description="Whether model requests use the fixed recent-three-turn 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 used as the final conversation title, "
"skipping post-answer LLM title generation."
),
)
model_config = ConfigDict(extra="ignore")
class WriteFileCompatibilitySettings(BaseModel):
"""Deployment-wide compatibility for gateways buffering tool arguments."""
@@ -575,19 +668,70 @@ class WriteFileCompatibilitySettings(BaseModel):
model_config = ConfigDict(extra="ignore")
class ConversationContextSettings(BaseModel):
"""Deployment-wide short-context policy for chat model requests.
class RetryKeepPartialSettings(BaseModel):
"""Keep already-streamed partial answers visible across silent LLM retries.
The recent-turn window is deliberately opt-in. When enabled, the lead
agent keeps the persisted conversation intact but sends only the latest
three real user turns (plus their assistant/tool continuations) to the
model. This avoids an extra summarization-model call while preserving the
complete transcript for the UI and checkpoint recovery.
The LLM error middleware silently retries failed model calls. The failed
attempt never reaches the checkpoint, so the display reconciliation drops
its already-streamed partial answer — users see the text "cleared" when
the retry starts thinking again. Enabled keeps that partial visible in
the chat (frontend display concern, read at stream time).
"""
recent_turn_window_enabled: bool = Field(
enabled: bool = Field(
default=True,
description=(
"Keep the already-streamed partial answer visible when a model "
"call is silently retried, instead of letting the display "
"reconciliation clear it."
),
)
model_config = ConfigDict(extra="ignore")
class RoundtableRoomLimitSettings(BaseModel):
"""Global runtime limits for multi-agent roundtable step 2.
The count is deployment-wide: every user's foreground step-2 session and
every non-terminal background roundtable job share one pool. One room is
one session, not one seat and not one model call. Turning the switch off
keeps recording occupancy but stops rejecting new entries.
"""
enabled: bool = Field(
default=True,
description="Whether a full roundtable room pool blocks entry into step 2.",
)
max_rooms: int = Field(
default=3,
ge=1,
le=20,
description="Maximum simultaneous step-2 roundtable rooms across all users.",
)
max_hold_minutes: int = Field(
default=30,
ge=1,
le=1440,
description=(
"Hard lifetime of one step-2 room. Heartbeats preserve network liveness "
"but never extend this deadline."
),
)
max_cycles: int = Field(
default=8,
ge=2,
le=100,
description=(
"Coordinator round that switches to tool-free final closeout. "
"The value is captured when an orchestration starts."
),
)
write_file_compatibility_enabled: bool = Field(
default=False,
description="Whether model requests use the fixed recent-three-turn sliding window.",
description=(
"When true, roundtable leader/seat/step-3 runs use buffered-gateway "
"write_file streaming. Ordinary chat keeps the global switch."
),
)
model_config = ConfigDict(extra="ignore")
@@ -625,6 +769,71 @@ class HtmlMapSettings(BaseModel):
model_config = ConfigDict(extra="ignore")
_APP_IDENTITY_LOGO_FILE_RE = re.compile(r"^logo-[a-f0-9]{32}\.(?:png|jpg|webp)$")
class AppIdentitySettings(BaseModel):
"""Name and logo shown in this application's own chrome.
Empty ``system_name`` and a missing logo keep the built-in title and the
static theme logos. This block is independent of generated-page branding.
"""
system_name: str = Field(default="", max_length=80)
logo_filename: str | None = None
logo_media_type: Literal["image/png", "image/jpeg", "image/webp"] | None = None
logo_version: str | None = None
model_config = ConfigDict(extra="ignore")
@field_validator("system_name")
@classmethod
def _normalize_app_system_name(cls, value: str | None) -> str:
normalized = " ".join(str(value or "").split())
return normalized
@field_validator("logo_filename")
@classmethod
def _validate_app_logo_filename(cls, value: str | None) -> str | None:
if value is None:
return None
normalized = str(value).strip().lower()
if not _APP_IDENTITY_LOGO_FILE_RE.fullmatch(normalized):
raise ValueError("Invalid application logo filename")
return normalized
def app_identity_logo_path(
settings: AppIdentitySettings | None = None,
) -> Path | None:
"""Resolve the uploaded application logo without accepting an arbitrary path."""
current = settings or load_system_settings().app_identity
if not current.logo_filename:
return None
path = runtime_home() / "app-identity" / current.logo_filename
return path if path.is_file() else None
class HtmlRuntimeSettings(BaseModel):
"""Addresses written into newly generated HTML pages.
Empty strings mean the settings dialog has not saved this block. Readers
then keep an older config.yaml value, and finally the built-in default.
"""
base_url: str = Field(
default="",
max_length=2048,
description="Browser-reachable Gateway base for ECharts, G6, Leaflet and generated-page images",
)
map_tile_url: str = Field(
default="",
max_length=2048,
description="Leaflet tile template containing {z}, {x} and {y}",
)
model_config = ConfigDict(extra="ignore")
class StrategyProjectSettings(BaseModel):
"""Global visibility controls for the strategy-project experience."""
@@ -635,10 +844,19 @@ class StrategyProjectSettings(BaseModel):
model_config = ConfigDict(extra="ignore")
class ModelPromptSuffix(BaseModel):
"""Administrator-owned instructions appended to one configured model's system prompt."""
enabled: bool = False
prompt: str = Field(default="", max_length=20000)
model_config = ConfigDict(extra="forbid")
class SystemSettings(BaseModel):
"""Top-level system settings document."""
prompt_prefix: PromptPrefixSettings = Field(default_factory=PromptPrefixSettings)
model_prompt_suffixes: dict[str, ModelPromptSuffix] = Field(default_factory=dict)
login_whitelist: LoginWhitelistSettings = Field(default_factory=LoginWhitelistSettings)
authentication: AuthenticationSettings = Field(default_factory=AuthenticationSettings)
private_square: PrivateSquareSettings = Field(default_factory=PrivateSquareSettings)
@@ -653,13 +871,19 @@ class SystemSettings(BaseModel):
concurrency_monitor: ConcurrencyMonitorSettings = Field(default_factory=ConcurrencyMonitorSettings)
model_concurrency: ModelConcurrencySettings = Field(default_factory=ModelConcurrencySettings)
memory: MemoryRuntimeSettings = Field(default_factory=MemoryRuntimeSettings)
conversation_context: ConversationContextSettings = Field(default_factory=ConversationContextSettings)
write_file_compatibility: WriteFileCompatibilitySettings = Field(
default_factory=WriteFileCompatibilitySettings
)
conversation_context: ConversationContextSettings = Field(default_factory=ConversationContextSettings)
retry_keep_partial: RetryKeepPartialSettings = Field(
default_factory=RetryKeepPartialSettings
)
roundtable_room_limit: RoundtableRoomLimitSettings = Field(default_factory=RoundtableRoomLimitSettings)
local_wiki_encoder: LocalWikiEncoderSettings = Field(default_factory=LocalWikiEncoderSettings)
strategy_projects: StrategyProjectSettings = Field(default_factory=StrategyProjectSettings)
html_map: HtmlMapSettings = Field(default_factory=HtmlMapSettings)
html_runtime: HtmlRuntimeSettings = Field(default_factory=HtmlRuntimeSettings)
app_identity: AppIdentitySettings = Field(default_factory=AppIdentitySettings)
llmwiki: LlmWikiRuntimeOverride = Field(default_factory=LlmWikiRuntimeOverride)
skill_knowledge_auto_sync: SkillKnowledgeAutoSyncSettings = Field(default_factory=SkillKnowledgeAutoSyncSettings)
knowledge_base_product_version: Literal["v1", "v2"] = Field(
@@ -679,9 +903,36 @@ def _settings_path() -> Path:
return home / _SETTINGS_FILE
# ── mtime 缓存 ────────────────────────────────────────────────────────────
# ``load_system_settings`` 处在登录等热路径上(一次登录会读 3 次:登录方式
# 开关、白名单、单会话策略),而每次调用都是「整文件读盘 + JSON 解析 +
# pydantic 校验」。按 (路径, mtime) 缓存解析结果:文件未变直接返回缓存值的
# 深拷贝(调用方可能就地改写返回值,不能共享实例);任何写入——
# ``save_system_settings`` 的原子替换——都会更新 mtime,下一次调用自动重读,
# 无需显式清缓存。
_settings_cache_key: tuple[str, int] | None = None
_settings_cache_value: SystemSettings | None = None
def load_system_settings() -> SystemSettings:
"""Read the on-disk system settings, returning defaults when missing."""
"""Read the on-disk system settings, returning defaults when missing.
Parsed results are cached by (path, mtime); unchanged files return a deep
copy so callers may safely mutate the returned model without poisoning the
shared cache.
"""
global _settings_cache_key, _settings_cache_value
path = _settings_path()
try:
mtime = path.stat().st_mtime_ns
except OSError:
return SystemSettings()
key = (str(path), mtime)
if _settings_cache_value is not None and _settings_cache_key == key:
return _settings_cache_value.model_copy(deep=True)
if not path.is_file():
return SystemSettings()
try:
@@ -689,10 +940,13 @@ def load_system_settings() -> SystemSettings:
if not isinstance(raw, dict):
logger.warning("System settings file %s is not a JSON object; ignoring", path)
return SystemSettings()
return SystemSettings.model_validate(raw)
settings = SystemSettings.model_validate(raw)
except Exception as exc:
logger.warning("Failed to read system settings from %s: %s", path, exc)
return SystemSettings()
_settings_cache_key = key
_settings_cache_value = settings
return settings.model_copy(deep=True)
def get_skill_compression_settings() -> SkillCompressionSettings:
@@ -731,6 +985,15 @@ def get_memory_runtime_settings() -> MemoryRuntimeSettings:
return MemoryRuntimeSettings()
def get_conversation_context_settings() -> ConversationContextSettings:
"""Return the admin-controlled recent-turn policy, failing closed."""
try:
return load_system_settings().conversation_context
except Exception:
logger.debug("Failed to read conversation context setting; keeping the recent-turn window disabled", exc_info=True)
return ConversationContextSettings()
def get_write_file_compatibility_settings() -> WriteFileCompatibilitySettings:
"""Return the global buffered-gateway switch, failing closed."""
@@ -744,17 +1007,18 @@ def get_write_file_compatibility_settings() -> WriteFileCompatibilitySettings:
return WriteFileCompatibilitySettings()
def get_conversation_context_settings() -> ConversationContextSettings:
"""Return the admin-controlled recent-turn policy, failing closed."""
def get_roundtable_room_limit_settings() -> RoundtableRoomLimitSettings:
"""Return the admin-controlled roundtable room cap, defaulting to 3 enabled rooms."""
try:
return load_system_settings().conversation_context
return load_system_settings().roundtable_room_limit
except Exception:
logger.debug("Failed to read conversation context setting; keeping the recent-turn window disabled", exc_info=True)
return ConversationContextSettings()
logger.debug("Failed to read roundtable room limit; keeping the default cap", exc_info=True)
return RoundtableRoomLimitSettings()
def save_system_settings(settings: SystemSettings) -> SystemSettings:
"""Persist the settings document atomically, returning the saved value."""
global _settings_cache_key, _settings_cache_value
path = _settings_path()
payload = settings.model_dump(mode="json")
with _lock:
@@ -766,4 +1030,8 @@ def save_system_settings(settings: SystemSettings) -> SystemSettings:
tmp.replace(path)
finally:
tmp.unlink(missing_ok=True)
# mtime 变化本就足以让缓存失效;这里显式清一次,兜底个别文件系统
# mtime 粒度过粗(同一秒内连续保存两次)读回旧值的极端情况。
_settings_cache_key = None
_settings_cache_value = None
return settings