From efd5bb8f4fd9b13eaa57aefd945f2d25c483934e Mon Sep 17 00:00:00 2001 From: Beluga737 Date: Sun, 22 Nov 2026 20:45:08 +0700 Subject: [PATCH] =?UTF-8?q?=D0=BF=D0=B5=D1=80=D0=B5=D1=80=D0=B0=D0=B1?= =?UTF-8?q?=D0=BE=D1=82=D0=B0=D0=BD=20=D0=B2=D0=B8=D0=B7=D1=83=D0=B0=D0=BB?= =?UTF-8?q?,=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D1=8B=20?= =?UTF-8?q?=D0=BF=D0=BE=D0=B4=D0=B4=D0=B5=D1=80=D0=B6=D0=BA=D0=B8=20=D0=B4?= =?UTF-8?q?=D1=80=D1=83=D0=B3=D0=B8=D1=85=20=D0=B4=D0=B2=D0=B8=D0=B6=D0=BA?= =?UTF-8?q?=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- XUI/app.py | 68 +-- XUI/assets/_runtime_dark.json | 11 + XUI/assets/_runtime_light.json | 11 + XUI/components/controls.py | 4 +- XUI/components/icons.py | 3 + XUI/components/settings_popup.py | 181 ------ XUI/components/settings_window.py | 629 ++++++++++++++++++++ XUI/components/sidebar.py | 34 +- XUI/components/statusbar.py | 31 +- XUI/components/topbar.py | 2 +- XUI/core/api_server.py | 941 +++++++++++++++++++++++++++++ XUI/core/config.py | 111 ++++ XUI/core/engine.py | 759 +++++++++++++----------- XUI/core/engines/__init__.py | 0 XUI/core/engines/base.py | 143 +++++ XUI/core/engines/native.py | 261 ++++++++ XUI/core/engines/ollama.py | 210 +++++++ XUI/core/engines/openai_compat.py | 201 +++++++ XUI/core/mcp/__init__.py | 18 + XUI/core/mcp/client.py | 468 +++++++++++++++ XUI/core/mcp/fs_server.py | 950 ++++++++++++++++++++++++++++++ XUI/core/mcp/manager.py | 146 +++++ XUI/core/state.py | 3 + XUI/theme.py | 11 + XUI/views/chat.py | 269 +++++++-- XUI/views/dev.py | 12 +- XUI/views/models.py | 337 ++++++----- XUI/views/modes.py | 15 +- XUI/views/server.py | 263 +++++++-- XUI/views/training.py | 190 +++++- XUI/views/user.py | 2 +- xenith_server.py | 128 ++++ 32 files changed, 5528 insertions(+), 884 deletions(-) delete mode 100644 XUI/components/settings_popup.py create mode 100644 XUI/components/settings_window.py create mode 100644 XUI/core/api_server.py create mode 100644 XUI/core/config.py create mode 100644 XUI/core/engines/__init__.py create mode 100644 XUI/core/engines/base.py create mode 100644 XUI/core/engines/native.py create mode 100644 XUI/core/engines/ollama.py create mode 100644 XUI/core/engines/openai_compat.py create mode 100644 XUI/core/mcp/__init__.py create mode 100644 XUI/core/mcp/client.py create mode 100644 XUI/core/mcp/fs_server.py create mode 100644 XUI/core/mcp/manager.py create mode 100644 xenith_server.py diff --git a/XUI/app.py b/XUI/app.py index 89d4eee..9c38c5e 100644 --- a/XUI/app.py +++ b/XUI/app.py @@ -10,18 +10,15 @@ from .core import prefs from .components.sidebar import Sidebar from .components.topbar import TopBar from .components.statusbar import StatusBar -from .components.settings_popup import SettingsPopup +from .components.settings_window import SettingsWindow from . import theme from .views.base import ViewBase from .views.chat import ChatView from .views.models import ModelsView -from .views.model_settings import ModelSettingsView from .views.interactions import InteractionsView -from .views.modes import ModesView from .views.server import ServerView from .views.training import TrainingView -from .views.user import UserView from .views.dev import DevView @@ -35,7 +32,7 @@ class App(ctk.CTk): self.app_state = AppState() self.engine = XenithEngine(self.app_state) - self.settings_popup = None + self.settings_window = None # Пользовательские настройки интерфейса (тема/масштаб) — между запусками. saved = prefs.load() @@ -109,12 +106,9 @@ class App(ctk.CTk): view_classes = { "chat": ChatView, "models": ModelsView, - "model_settings": ModelSettingsView, "interactions": InteractionsView, - "modes": ModesView, "server": ServerView, "training": TrainingView, - "user": UserView, "dev": DevView, } @@ -167,7 +161,7 @@ class App(ctk.CTk): return False prev = self.current_view_key or "chat" - self.close_settings_popup() + self.close_settings() for attr in ("sidebar", "main", "statusbar"): w = getattr(self, attr, None) @@ -221,9 +215,9 @@ class App(ctk.CTk): if view is None: return - # Любая навигация закрывает выпадающее меню настроек. + # Любая навигация закрывает окно настроек. try: - self.close_settings_popup() + self.close_settings() except Exception: pass @@ -303,46 +297,44 @@ class App(ctk.CTk): except Exception: pass - def open_settings_popup(self, anchor=None): - popup = getattr(self, "settings_popup", None) - if popup is not None: + def open_settings(self, category: str = "appearance"): + win = getattr(self, "settings_window", None) + if win is not None: try: - if popup.winfo_exists(): - return popup + if win.winfo_exists(): + win.show(category) + win.lift() + return win except Exception: pass - self.settings_popup = None - - anchor = anchor or getattr(getattr(self, "topbar", None), "gear_btn", None) - if anchor is None: - return None + self.settings_window = None try: - self.settings_popup = SettingsPopup(self, anchor) - return self.settings_popup + self.settings_window = SettingsWindow(self, category) + return self.settings_window except Exception as e: - self.app_state.log(f"[UI] settings popup: {e}") + self.app_state.log(f"[UI] settings window: {e}") return None - def close_settings_popup(self): - popup = getattr(self, "settings_popup", None) - if popup is None: + def close_settings(self): + win = getattr(self, "settings_window", None) + if win is None: return - self.settings_popup = None + self.settings_window = None try: - popup.close() + win.close() except Exception: pass - def toggle_settings_popup(self): - popup = getattr(self, "settings_popup", None) - if popup is not None: + def toggle_settings(self): + win = getattr(self, "settings_window", None) + if win is not None: try: - if popup.winfo_exists(): - self.close_settings_popup() + if win.winfo_exists(): + self.close_settings() return except Exception: - self.settings_popup = None - self.open_settings_popup() + self.settings_window = None + self.open_settings("appearance") def report_callback_exception(self, exc, val, tb): """Ловим ошибки в обработчиках Tk: пишем в лог (вкладка «Разработчик») и в stderr.""" @@ -370,6 +362,8 @@ class App(ctk.CTk): # чтобы их after-циклы не пытались обращаться к Tk после закрытия. for view in list(getattr(self, "views", {}).values()): try: + if hasattr(view, "shutdown"): + view.shutdown() view.destroy() except Exception: pass @@ -380,7 +374,7 @@ class App(ctk.CTk): except Exception: pass try: - self.close_settings_popup() + self.close_settings() except Exception: pass super().destroy() diff --git a/XUI/assets/_runtime_dark.json b/XUI/assets/_runtime_dark.json index f3f3bc0..d288c5f 100644 --- a/XUI/assets/_runtime_dark.json +++ b/XUI/assets/_runtime_dark.json @@ -55,6 +55,17 @@ "button_color": "#3a3530", "button_hover_color": "#4a443c" }, + "CTkSwitch": { + "corner_radius": 1000, + "border_width": 3, + "button_length": 0, + "fg_color": "#2d2925", + "progress_color": "#d08a4b", + "button_color": "#efe9de", + "button_hover_color": "#ffffff", + "text_color": "#efe9de", + "text_color_disabled": "#8a847a" + }, "CTkSlider": { "corner_radius": 1000, "button_corner_radius": 1000, diff --git a/XUI/assets/_runtime_light.json b/XUI/assets/_runtime_light.json index e0c5c70..8219f67 100644 --- a/XUI/assets/_runtime_light.json +++ b/XUI/assets/_runtime_light.json @@ -55,6 +55,17 @@ "button_color": "#d6ccbd", "button_hover_color": "#c6baa8" }, + "CTkSwitch": { + "corner_radius": 1000, + "border_width": 3, + "button_length": 0, + "fg_color": "#e5ded2", + "progress_color": "#a45f26", + "button_color": "#1f1b16", + "button_hover_color": "#3a332a", + "text_color": "#1f1b16", + "text_color_disabled": "#7b7266" + }, "CTkSlider": { "corner_radius": 1000, "button_corner_radius": 1000, diff --git a/XUI/components/controls.py b/XUI/components/controls.py index 860cdea..3e328c4 100644 --- a/XUI/components/controls.py +++ b/XUI/components/controls.py @@ -280,7 +280,7 @@ class ModelChip(_Interactive): self._dot = Dot(self, 8, c("text_faint"), c("card")) self._dot.pack(side="left", padx=(12, 8)) - self._label = ctk.CTkLabel(self, text="Модель не выбрана", font=ui_font(12), + self._label = ctk.CTkLabel(self, text="Модель не загружена", font=ui_font(12), text_color=c("text_dim")) self._label.pack(side="left", padx=(0, 12)) @@ -293,7 +293,7 @@ class ModelChip(_Interactive): self._label.configure(text=label) self._dot.set(color=c("success")) else: - self._label.configure(text="Модель не выбрана") + self._label.configure(text="Модель не загружена") self._dot.set(color=c("text_faint")) self._set_hover(False) diff --git a/XUI/components/icons.py b/XUI/components/icons.py index 59d4f5b..6ac83f3 100644 --- a/XUI/components/icons.py +++ b/XUI/components/icons.py @@ -90,6 +90,9 @@ def draw(canvas: tk.Canvas, name: str, size: int = 18, color: str = "#ffffff", line([6, 11, 12, 5, 18, 11]) elif name == "chevron_down": line([8, 10, 12, 14, 16, 10]) + elif name == "close": + line([6, 6, 18, 18]) + line([18, 6, 6, 18]) elif name == "dot": circle(12, 12, 5, True) else: diff --git a/XUI/components/settings_popup.py b/XUI/components/settings_popup.py deleted file mode 100644 index b15a574..0000000 --- a/XUI/components/settings_popup.py +++ /dev/null @@ -1,181 +0,0 @@ -import customtkinter as ctk - -from .. import theme -from ..theme import c, mono_font, ui_font - - -class SettingsPopup(ctk.CTkFrame): - """Выпадающее меню настроек интерфейса (открывается шестерёнкой в топбаре).""" - - WIDTH = 304 - - def __init__(self, app, anchor, **kwargs): - super().__init__( - app, - width=self.WIDTH, - fg_color=c("card"), - corner_radius=12, - border_width=1, - border_color=c("border_strong"), - **kwargs, - ) - self.app = app - self._anchor = anchor - self._binds = [] - - pad = 14 - - ctk.CTkLabel(self, text="Настройки интерфейса", font=ui_font(13), text_color=c("text")).pack( - anchor="w", padx=pad, pady=(12, 2) - ) - ctk.CTkLabel(self, text="Тема", font=ui_font(11), text_color=c("text_dim")).pack( - anchor="w", padx=pad, pady=(12, 4) - ) - self.theme_menu = ctk.CTkOptionMenu( - self, - values=[spec.name for spec in theme.available()], - command=self._on_theme, - width=self.WIDTH - 2 * pad, - height=30, - font=ui_font(11), - dropdown_font=ui_font(11), - ) - self.theme_menu.pack(fill="x", padx=pad, pady=(0, 10)) - try: - self.theme_menu.set(theme.active().name) - except Exception: - pass - - ctk.CTkLabel(self, text="Масштаб", font=ui_font(11), text_color=c("text_dim")).pack( - anchor="w", padx=pad, pady=(0, 4) - ) - self.scale = ctk.CTkSegmentedButton( - self, - values=["90%", "100%", "110%", "120%"], - command=self._on_scale, - height=28, - width=self.WIDTH - 2 * pad, - font=ui_font(11), - ) - self.scale.pack(fill="x", padx=pad, pady=(0, 12)) - try: - cur = int(round(float(getattr(app.app_state, "ui_scale", 1.0)) * 100)) - self.scale.set(f"{cur}%") - except Exception: - self.scale.set("100%") - - ctk.CTkFrame(self, fg_color=c("border"), height=1, corner_radius=0).pack(fill="x", padx=pad, pady=(0, 10)) - - ctk.CTkButton( - self, - text="Параметры моделей", - anchor="w", - width=self.WIDTH - 2 * pad, - height=34, - corner_radius=8, - fg_color=c("accent_soft"), - hover_color=c("card_hover"), - text_color=c("accent_text"), - font=ui_font(11), - command=lambda: self._open_view("model_settings"), - ).pack(fill="x", padx=pad, pady=(0, 10)) - - engine_text = self._engine_text() - if engine_text: - ctk.CTkLabel( - self, - text=engine_text, - font=mono_font(9), - text_color=c("text_faint"), - anchor="w", - ).pack(fill="x", padx=pad, pady=(0, 12)) - - self._reposition() - self.lift() - - self._binds.append(("", self.app.bind("", self._maybe_close, add="+"))) - self._binds.append(("", self.app.bind("", self._on_escape, add="+"))) - - # ---------- позиционирование / закрытие ---------- - def _engine_text(self): - try: - engine = self.app.engine - v = engine.version() if engine else "" - bt = engine.build_type() if engine else "" - except Exception: - v, bt = "", "" - if not v: - return "" - return f"ДВИЖОК {v}" + (f" · {bt}" if bt else "") - - def _reposition(self, *args): - try: - self.update_idletasks() - ax = self._anchor.winfo_rootx() - self.app.winfo_rootx() - ay = self._anchor.winfo_rooty() - self.app.winfo_rooty() - aw = self._anchor.winfo_width() - w = self.winfo_reqwidth() or self.WIDTH - x = ax + aw - w - y = ay + self._anchor.winfo_height() + 8 - max_x = max(8, self.app.winfo_width() - w - 8) - self.place(x=max(8, min(x, max_x)), y=y) - self.lift() - except Exception: - pass - - def _maybe_close(self, event=None): - try: - if not self.winfo_exists(): - return - except Exception: - return - widget = getattr(event, "widget", None) - while widget is not None: - if widget is self or widget is self._anchor: - return - widget = getattr(widget, "master", None) - self.close() - - def _on_escape(self, event=None): - self.close() - - def close(self): - for seq, fid in self._binds: - try: - self.app.unbind(seq, fid) - except Exception: - pass - self._binds.clear() - try: - if getattr(self.app, "settings_popup", None) is self: - self.app.settings_popup = None - except Exception: - pass - try: - self.destroy() - except Exception: - pass - - # ---------- действия ---------- - def _on_theme(self, name): - spec = theme.by_name(name) - if spec is None: - return - ok = self.app.set_theme(spec.key) - if not ok: - try: - self.theme_menu.set(theme.active().name) - except Exception: - pass - - def _on_scale(self, value): - try: - scale = float(str(value).replace("%", "").strip()) / 100.0 - except Exception: - return - self.app.set_ui_scale(scale) - self.after(120, self._reposition) - - def _open_view(self, key): - self.close() - self.app.switch_view(key) diff --git a/XUI/components/settings_window.py b/XUI/components/settings_window.py new file mode 100644 index 0000000..4247c04 --- /dev/null +++ b/XUI/components/settings_window.py @@ -0,0 +1,629 @@ +"""Единое окно настроек Xenith Studio (в духе LM Studio).""" + +import os +import threading +import time +from tkinter import filedialog, messagebox + +import customtkinter as ctk + +from .. import theme +from ..theme import c, mono_font, ui_font +from .controls import IconButton + +ENGINE_TYPES = { + "ollama": "Ollama", + "llamacpp": "llama.cpp / LM Studio", + "openai": "OpenAI-совместимый", + "xenith": "Xenith (встроенный)", +} + +_OPENAI_LABELS = (ENGINE_TYPES["llamacpp"], ENGINE_TYPES["openai"]) + +MCP_MODES = { + "Умный": "smart", + "Полный доступ": "full", + "Ограниченный": "restricted", +} + + +class SettingsWindow(ctk.CTkToplevel): + def __init__(self, app, category: str = "appearance", **kwargs): + super().__init__(app, **kwargs) + self.app = app + self._closed = False + self._category = category + self._engine_form_id = None + self._test_jobs = {} + + self.title("Настройки — Xenith Studio") + self.geometry("920x640") + self.minsize(780, 540) + self.configure(fg_color=c("bg")) + self.transient(app) + try: + self.attributes("-type", "dialog") + except Exception: + pass + self._center_over_app(920, 640) + self.after(80, self._raise) + + self.grid_columnconfigure(1, weight=1) + self.grid_rowconfigure(1, weight=1) + + # header + head = ctk.CTkFrame(self, fg_color="transparent") + head.grid(row=0, column=0, columnspan=2, sticky="ew", padx=20, pady=(16, 8)) + ctk.CTkLabel(head, text="Настройки", font=ui_font(18), text_color=c("text")).pack(side="left") + self.close_btn = IconButton(head, "close", self.close, size=32, icon_size=16, + bg=c("bg"), hover=c("card_hover")) + self.close_btn.pack(side="right") + + # left navigation + self.nav = ctk.CTkFrame(self, fg_color=c("sidebar"), corner_radius=12, + border_width=1, border_color=c("border")) + self.nav.grid(row=1, column=0, sticky="ns", padx=(20, 10), pady=(0, 20)) + self.nav_buttons = {} + categories = [ + ("appearance", "Внешний вид"), + ("engines", "Движки"), + ("mcp", "MCP"), + ("about", "О программе"), + ] + for key, label in categories: + btn = ctk.CTkButton(self.nav, text=label, anchor="w", height=34, + corner_radius=8, fg_color="transparent", + hover_color=c("sidebar_hover"), font=ui_font(12), + text_color=c("text_dim"), + command=lambda k=key: self.show(k)) + btn.pack(fill="x", padx=8, pady=2) + self.nav_buttons[key] = btn + + # content + self.content = ctk.CTkFrame(self, fg_color=c("card"), corner_radius=12, + border_width=1, border_color=c("border")) + self.content.grid(row=1, column=1, sticky="nsew", padx=(0, 20), pady=(0, 20)) + self.content.grid_rowconfigure(0, weight=1) + self.content.grid_columnconfigure(0, weight=1) + + self.frames = { + "appearance": self._build_appearance(), + "engines": self._build_engines(), + "mcp": self._build_mcp(), + "about": self._build_about(), + } + for f in self.frames.values(): + f.grid(row=0, column=0, sticky="nsew") + + self.show(category) + + self.bind("", lambda e: self.close()) + self.protocol("WM_DELETE_WINDOW", self.close) + + def _center_over_app(self, w, h): + try: + self.update_idletasks() + ax = self.app.winfo_rootx() + ay = self.app.winfo_rooty() + aw = self.app.winfo_width() + ah = self.app.winfo_height() + x = ax + max(0, (aw - w) // 2) + y = ay + max(0, (ah - h) // 2) + self.geometry(f"{w}x{h}+{x}+{y}") + except Exception: + pass + + def _raise(self): + try: + self.lift() + self.focus_force() + except Exception: + pass + + def close(self): + self._closed = True + try: + if getattr(self.app, "settings_window", None) is self: + self.app.settings_window = None + except Exception: + pass + try: + self.destroy() + except Exception: + pass + + def show(self, key): + if key not in self.frames: + return + self._category = key + for k, btn in self.nav_buttons.items(): + try: + if k == key: + btn.configure(fg_color=c("control"), text_color=c("text")) + else: + btn.configure(fg_color="transparent", text_color=c("text_dim")) + except Exception: + pass + for k, frame in self.frames.items(): + try: + (frame.grid if k == key else frame.grid_remove)() + except Exception: + pass + if key == "engines": + self.refresh_engines() + if key == "mcp": + self._refresh_mcp() + + # ================================================================== + # Внешний вид + # ================================================================== + def _section_title(self, parent, text, hint=""): + box = ctk.CTkFrame(parent, fg_color="transparent") + box.pack(fill="x", padx=20, pady=(18, 6)) + ctk.CTkLabel(box, text=text, font=ui_font(13), text_color=c("text")).pack(anchor="w") + if hint: + ctk.CTkLabel(box, text=hint, font=ui_font(11), text_color=c("text_faint")).pack(anchor="w", pady=(2, 0)) + return box + + def _build_appearance(self): + frame = ctk.CTkFrame(self.content, fg_color="transparent") + + self._section_title(frame, "Тема", "Применяется сразу") + + self.theme_var = ctk.StringVar(value=theme.active().name) + names = [spec.name for spec in theme.available()] + menu = ctk.CTkOptionMenu(frame, values=names, variable=self.theme_var, + command=self._on_theme, width=260, height=34, + dynamic_resizing=False, + font=ui_font(12), dropdown_font=ui_font(12)) + menu.pack(anchor="w", padx=20, pady=(0, 12)) + + self._section_title(frame, "Масштаб интерфейса", "90–120%") + self._pad = 0 + self.scale = ctk.CTkSegmentedButton( + frame, values=["90%", "100%", "110%", "120%"], + command=self._on_scale, height=30, width=320, font=ui_font(11), + ) + self.scale.pack(anchor="w", padx=20, pady=(0, 14)) + try: + self.scale.set(f"{int(round(float(self.app.app_state.ui_scale) * 100))}%") + except Exception: + self.scale.set("100%") + + note = ctk.CTkLabel( + frame, + text="Тёмная и светлая темы используют общую сетку, типографику и иконки. " + "Свои темы добавляются в XUI/theme.py и появляются в списке автоматически.", + font=ui_font(11), text_color=c("text_faint"), anchor="w", justify="left", + wraplength=520, + ) + note.pack(anchor="w", padx=20, pady=(4, 20)) + return frame + + def _on_theme(self, name): + spec = theme.by_name(name) + if spec is None: + return + ok = self.app.set_theme(spec.key) + if ok: + # Интерфейс пересобран — окно пересоздаём в новой теме. + self.close() + self.app.after(120, lambda: self.app.open_settings("appearance")) + else: + try: + self.theme_var.set(theme.active().name) + except Exception: + pass + + def _on_scale(self, value): + try: + scale = float(str(value).replace("%", "")) / 100.0 + except Exception: + return + self.app.set_ui_scale(scale) + + # ================================================================== + # Движки + # ================================================================== + def _build_engines(self): + frame = ctk.CTkFrame(self.content, fg_color="transparent") + frame.grid_rowconfigure(0, weight=0) + frame.grid_rowconfigure(1, weight=1) + frame.grid_columnconfigure(0, weight=1) + + top = ctk.CTkFrame(frame, fg_color="transparent") + top.grid(row=0, column=0, sticky="ew", padx=20, pady=(16, 6)) + ctk.CTkLabel(top, text="Движки", font=ui_font(13), text_color=c("text")).pack(side="left") + ctk.CTkButton(top, text="Добавить", width=100, height=32, + command=lambda: self.open_engine_form(None)).pack(side="right") + + self.engines_list = ctk.CTkScrollableFrame(frame, fg_color="transparent") + self.engines_list.grid(row=1, column=0, sticky="nsew", padx=12, pady=(0, 6)) + + self.engine_form = ctk.CTkFrame(frame, fg_color=c("panel"), corner_radius=12, + border_width=1, border_color=c("border")) + self.engine_form.grid(row=2, column=0, sticky="ew", padx=20, pady=(0, 16)) + self.engine_form.grid_remove() + self._build_engine_form() + + self.engine_status = ctk.CTkLabel(frame, text="", font=ui_font(11), + text_color=c("text_faint")) + self.engine_status.grid(row=3, column=0, sticky="w", padx=20, pady=(0, 12)) + return frame + + def _build_engine_form(self): + f = self.engine_form + f.grid_columnconfigure(1, weight=1) + + ctk.CTkLabel(f, text="Тип", font=ui_font(11), text_color=c("text_dim")).grid( + row=0, column=0, sticky="w", padx=14, pady=(12, 4)) + self.form_type = ctk.CTkOptionMenu(f, values=[ENGINE_TYPES["ollama"], ENGINE_TYPES["llamacpp"], ENGINE_TYPES["openai"]], + height=32, width=240, dynamic_resizing=False, + font=ui_font(11), + command=lambda v: self._sync_form_fields()) + self.form_type.grid(row=0, column=1, sticky="w", padx=10, pady=(12, 4)) + + ctk.CTkLabel(f, text="Название", font=ui_font(11), text_color=c("text_dim")).grid( + row=1, column=0, sticky="w", padx=14, pady=4) + self.form_name = ctk.CTkEntry(f, height=32, font=ui_font(12)) + self.form_name.grid(row=1, column=1, sticky="ew", padx=10, pady=4) + + ctk.CTkLabel(f, text="Base URL", font=ui_font(11), text_color=c("text_dim")).grid( + row=2, column=0, sticky="w", padx=14, pady=4) + self.form_url = ctk.CTkEntry(f, height=32, font=ui_font(12), + placeholder_text="http://127.0.0.1:11434") + self.form_url.grid(row=2, column=1, sticky="ew", padx=10, pady=4) + + ctk.CTkLabel(f, text="API-ключ", font=ui_font(11), text_color=c("text_dim")).grid( + row=3, column=0, sticky="w", padx=14, pady=4) + self.form_key = ctk.CTkEntry(f, height=32, font=ui_font(12), + placeholder_text="необязательно") + self.form_key.grid(row=3, column=1, sticky="ew", padx=10, pady=4) + + ctk.CTkLabel(f, text="Модель", font=ui_font(11), text_color=c("text_dim")).grid( + row=4, column=0, sticky="w", padx=14, pady=4) + self.form_model = ctk.CTkEntry(f, height=32, font=ui_font(12), + placeholder_text="необязательно; выберется в «Моделях»") + self.form_model.grid(row=4, column=1, sticky="ew", padx=10, pady=4) + + ctk.CTkLabel( + f, + text="Ollama — http://127.0.0.1:11434 · llama.cpp — http://127.0.0.1:8080/v1 · LM Studio — http://127.0.0.1:1234/v1", + font=ui_font(10), text_color=c("text_faint"), anchor="w", justify="left", + wraplength=560, + ).grid(row=5, column=0, columnspan=2, sticky="w", padx=14, pady=(2, 0)) + + self.form_enabled = ctk.BooleanVar(value=True) + ctk.CTkCheckBox(f, text="Включён", variable=self.form_enabled, + font=ui_font(11)).grid(row=6, column=1, sticky="w", padx=10, pady=(6, 4)) + + actions = ctk.CTkFrame(f, fg_color="transparent") + actions.grid(row=7, column=0, columnspan=2, sticky="e", padx=14, pady=(8, 12)) + ctk.CTkButton(actions, text="Отмена", width=90, height=32, + command=self.close_engine_form).pack(side="left", padx=6) + ctk.CTkButton(actions, text="Сохранить", width=110, height=32, + fg_color=c("action_bg"), hover_color=c("action_hover"), + text_color=c("action_fg"), font=ui_font(12), + command=self.save_engine).pack(side="left") + + self._sync_form_fields() + + def _sync_form_fields(self): + try: + label = self.form_type.get() + is_openai = label in _OPENAI_LABELS + except Exception: + label = "" + is_openai = False + try: + self.form_key.configure(state=("normal" if is_openai else "disabled")) + except Exception: + pass + defaults = { + ENGINE_TYPES["ollama"]: "http://127.0.0.1:11434", + ENGINE_TYPES["llamacpp"]: "http://127.0.0.1:8080/v1", + ENGINE_TYPES["openai"]: "http://127.0.0.1:1234/v1", + } + try: + cur = self.form_url.get().strip() + if not cur or cur in set(defaults.values()): + new = defaults.get(label) + if new and new != cur: + self.form_url.delete(0, "end") + self.form_url.insert(0, new) + except Exception: + pass + + def refresh_engines(self): + for w in self.engines_list.winfo_children(): + w.destroy() + try: + engines = self.app.engine.engines() + except Exception as e: + ctk.CTkLabel(self.engines_list, text=str(e), font=ui_font(11), + text_color=c("danger")).pack(anchor="w", padx=8, pady=8) + return + for item in engines: + self._engine_row(item) + + def _engine_row(self, item): + row = ctk.CTkFrame(self.engines_list, fg_color=c("panel"), corner_radius=10, + border_width=1, border_color=c("border")) + row.pack(fill="x", padx=4, pady=4) + row.grid_columnconfigure(0, weight=1) + + info = ctk.CTkFrame(row, fg_color="transparent") + info.grid(row=0, column=0, sticky="w", padx=12, pady=8) + title = item.get("name") or item.get("id") + if item.get("active"): + title += " · активный" + ctk.CTkLabel(info, text=title, font=ui_font(12), + text_color=c("text")).pack(anchor="w") + ctk.CTkLabel(info, text=item.get("describe") or item.get("type"), + font=ui_font(10), text_color=c("text_faint")).pack(anchor="w") + + actions = ctk.CTkFrame(row, fg_color="transparent") + actions.grid(row=0, column=1, sticky="e", padx=8, pady=6) + + self._row_action(actions, "Проверить", + lambda eid=item["id"]: self.test_engine(eid)).pack(side="left", padx=2) + if not item.get("active"): + self._row_action(actions, "Сделать активным", + lambda eid=item["id"]: self.activate_engine(eid), width=120).pack(side="left", padx=2) + self._row_action(actions, "Изменить", + lambda eid=item["id"]: self.open_engine_form(eid)).pack(side="left", padx=2) + if item.get("id") != "xenith": + self._row_action(actions, "Удалить", + lambda eid=item["id"]: self.delete_engine(eid), + color=c("danger")).pack(side="left", padx=2) + + def _row_action(self, parent, text, command, width=88, color=None): + return ctk.CTkButton( + parent, text=text, width=width, height=30, + fg_color="transparent", hover_color=c("card_hover"), + text_color=color or c("text_dim"), font=ui_font(11), + command=command, + ) + + def open_engine_form(self, engine_id): + self._engine_form_id = engine_id + conf = {} + if engine_id: + conf = dict((self.app.engine.config.get("engines") or {}).get(engine_id, {})) + typ = conf.get("type", "ollama") + label = ENGINE_TYPES.get(typ, ENGINE_TYPES["ollama"]) + if typ == "openai": + url_hint = str(conf.get("base_url") or "") + if "8080" in url_hint or "llama" in str(conf.get("name", "")).lower(): + label = ENGINE_TYPES["llamacpp"] + try: + self.form_type.set(label) + except Exception: + pass + self.form_name.delete(0, "end") + self.form_name.insert(0, conf.get("name", "")) + self.form_url.delete(0, "end") + default_url = "http://127.0.0.1:11434" if typ == "ollama" else "http://127.0.0.1:1234/v1" + if typ == "openai" and self.form_type.get() == ENGINE_TYPES["llamacpp"]: + default_url = "http://127.0.0.1:8080/v1" + self.form_url.insert(0, conf.get("base_url", default_url)) + self.form_key.delete(0, "end") + self.form_key.insert(0, conf.get("api_key", "")) + self.form_model.delete(0, "end") + self.form_model.insert(0, conf.get("model", "")) + try: + self.form_enabled.set(bool(conf.get("enabled", True))) + except Exception: + pass + self._sync_form_fields() + try: + self.engine_form.grid() + except Exception: + pass + + def close_engine_form(self): + self._engine_form_id = None + try: + self.engine_form.grid_remove() + except Exception: + pass + + def _form_type_key(self): + return "openai" if self.form_type.get() in _OPENAI_LABELS else "ollama" + + def save_engine(self): + typ = self._form_type_key() + name = self.form_name.get().strip() or ( + ENGINE_TYPES["llamacpp"] if typ == "openai" and self.form_type.get() == ENGINE_TYPES["llamacpp"] + else ENGINE_TYPES[typ] + ) + url = self.form_url.get().strip() + if typ == "ollama" and not url: + url = "http://127.0.0.1:11434" + if typ == "openai" and not url: + self.engine_status.configure(text="Укажите base URL", text_color=c("danger")) + return + conf = { + "type": typ, + "name": name, + "base_url": url, + "enabled": bool(self.form_enabled.get()), + } + key = self.form_key.get().strip() + if key: + conf["api_key"] = key + model = self.form_model.get().strip() + if model: + conf["model"] = model + + engine_id = self._engine_form_id + if not engine_id: + base = f"{typ}-{name.lower().replace(' ', '-')}" + engine_id = "".join(ch for ch in base if ch.isalnum() or ch in "-_.") or typ + existing = set((self.app.engine.config.get("engines") or {}).keys()) + candidate = engine_id + i = 2 + while candidate in existing: + candidate = f"{engine_id}-{i}" + i += 1 + engine_id = candidate + try: + self.app.engine.upsert_engine(engine_id, conf) + except Exception as e: + self.engine_status.configure(text=f"Ошибка: {e}", text_color=c("danger")) + return + self.engine_status.configure(text="Сохранено", text_color=c("text_faint")) + self.close_engine_form() + self.refresh_engines() + self.app.sidebar.update_status(self.app.app_state, self.app.engine.is_ready()) + self.app._update_status_bar() + + def activate_engine(self, engine_id): + if self.app.engine.set_active_engine(engine_id): + self.refresh_engines() + self.app.sidebar.update_status(self.app.app_state, self.app.engine.is_ready()) + self.app._update_status_bar() + self.engine_status.configure(text="Активный движок изменён", text_color=c("text_faint")) + try: + tv = self.app.views.get("training") + if tv is not None: + tv._apply_engine_gate() + except Exception: + pass + + def delete_engine(self, engine_id): + if not messagebox.askyesno("Удалить движок", f"Удалить «{engine_id}»?", parent=self): + return + if self.app.engine.remove_engine(engine_id): + self.refresh_engines() + self.app._update_status_bar() + + def test_engine(self, engine_id): + self.engine_status.configure(text=f"Проверка {engine_id}…", text_color=c("text_faint")) + + def task(): + ok, msg = self.app.engine.test_engine(engine_id) + def done(): + if not self._closed: + self.engine_status.configure( + text=f"{engine_id}: {'OK' if ok else 'ошибка'} · {msg}"[:160], + text_color=(c("success") if ok else c("danger")), + ) + try: + self.app.post_ui(done) + except Exception: + pass + + threading.Thread(target=task, daemon=True).start() + + # ================================================================== + # MCP + # ================================================================== + def _build_mcp(self): + frame = ctk.CTkFrame(self.content, fg_color="transparent") + self._section_title(frame, "MCP", "Доступ к файлам и инструментам") + ctk.CTkLabel( + frame, + text="Файловый MCP-сервер встроен. В чате включите переключатель «Файлы» — агент сможет " + "читать и создавать файлы в разрешённых папках. Опасные операции подтверждаются.", + font=ui_font(11), text_color=c("text_faint"), anchor="w", justify="left", + wraplength=560, + ).pack(anchor="w", padx=20, pady=(0, 12)) + + ctk.CTkLabel(frame, text="Режим разрешений", font=ui_font(11), + text_color=c("text_dim")).pack(anchor="w", padx=20, pady=(4, 4)) + self.mcp_mode = ctk.CTkSegmentedButton( + frame, values=list(MCP_MODES.keys()), command=self._save_mcp, + height=30, width=520, font=ui_font(11), + ) + self.mcp_mode.pack(anchor="w", padx=20, pady=(0, 4)) + self.mcp_hint = ctk.CTkLabel(frame, text="", font=ui_font(10), + text_color=c("text_faint"), anchor="w", justify="left", + wraplength=560) + self.mcp_hint.pack(anchor="w", padx=20, pady=(0, 10)) + + ctk.CTkLabel(frame, text="Разрешённые папки", font=ui_font(11), + text_color=c("text_dim")).pack(anchor="w", padx=20, pady=(8, 4)) + self.roots_box = ctk.CTkTextbox(frame, height=120, wrap="none", font=mono_font(10)) + self.roots_box.pack(fill="x", padx=20, pady=(0, 8)) + row = ctk.CTkFrame(frame, fg_color="transparent") + row.pack(fill="x", padx=20, pady=(0, 16)) + ctk.CTkButton(row, text="Добавить папку", height=32, + command=self._add_mcp_root).pack(side="left") + ctk.CTkButton(row, text="Сохранить", height=32, + fg_color=c("action_bg"), hover_color=c("action_hover"), + text_color=c("action_fg"), font=ui_font(12), + command=self._save_mcp).pack(side="left", padx=8) + + self._refresh_mcp() + return frame + + def _refresh_mcp(self): + try: + conf = self.app.engine.config.get("mcp") or {} + mode = conf.get("mode", "smart") + for label, key in MCP_MODES.items(): + if key == mode: + self.mcp_mode.set(label) + break + hints = { + "smart": "Безопасные операции (чтение, список) — автоматически. Запись, удаление, перемещение — с подтверждением.", + "full": "Всё внутри разрешённых папок — автоматически. Используйте осознанно.", + "restricted": "Любое действие требует подтверждения.", + } + self.mcp_hint.configure(text=hints.get(mode, "")) + roots = conf.get("roots") or [] + self.roots_box.configure(state="normal") + self.roots_box.delete("1.0", "end") + self.roots_box.insert("1.0", "\n".join(str(r) for r in roots)) + self.roots_box.configure(state="disabled") + except Exception: + pass + + def _add_mcp_root(self): + d = filedialog.askdirectory(title="Разрешённая папка для MCP", parent=self) + if not d: + return + d = os.path.abspath(d) + conf = self.app.engine.config.setdefault("mcp", {}) + roots = conf.setdefault("roots", []) + if d not in roots: + roots.append(d) + self._save_mcp() + + def _save_mcp(self, *_): + try: + for label, key in MCP_MODES.items(): + if label == self.mcp_mode.get(): + self.app.engine.config.setdefault("mcp", {})["mode"] = key + break + roots = [line.strip() for line in self.roots_box.get("1.0", "end").splitlines() if line.strip()] + self.app.engine.config.setdefault("mcp", {})["roots"] = roots + self.app.engine.save_config() + self._refresh_mcp() + self.engine_status.configure(text="MCP сохранён", text_color=c("text_faint")) + except Exception as e: + self.engine_status.configure(text=f"Ошибка MCP: {e}", text_color=c("danger")) + + # ================================================================== + # О программе + # ================================================================== + def _build_about(self): + frame = ctk.CTkFrame(self.content, fg_color="transparent") + self._section_title(frame, "О программе") + lines = [ + "Xenith Studio — локальная мастерская моделей.", + "", + f"Движок: {self.app.engine.describe()}", + f"Активный движок: {self.app.engine.active_name()}", + f"Версия приложения: 0.2", + f"Конфиг: {os.path.join(os.path.expanduser('~'), '.config', 'xenith-studio', 'config.json')}", + ] + for line in lines: + ctk.CTkLabel(frame, text=line, font=ui_font(11), text_color=c("text_dim"), + anchor="w").pack(anchor="w", padx=20, pady=1) + ctk.CTkLabel(frame, text="", height=8).pack() + ctk.CTkButton(frame, text="Открыть «Разработчик»", height=32, + command=lambda: (self.close(), self.app.switch_view("dev"))).pack( + anchor="w", padx=20, pady=(8, 18)) + return frame diff --git a/XUI/components/sidebar.py b/XUI/components/sidebar.py index 350e508..8ff6fa2 100644 --- a/XUI/components/sidebar.py +++ b/XUI/components/sidebar.py @@ -57,16 +57,13 @@ class Sidebar(ctk.CTkFrame): ("Основное", [ ("chat", "Чат", "chat"), ("models", "Модели", "layers"), - ("model_settings", "Параметры моделей", "sliders"), ]), ("Работа", [ ("interactions", "Взаимодействия", "swap"), - ("modes", "Режимы", "play"), - ("server", "Сервер", "server"), ("training", "Обучение", "chart"), + ("server", "Сервер", "server"), ]), ("Система", [ - ("user", "Пользователь", "user"), ("dev", "Разработчик", "code"), ]), ] @@ -135,27 +132,24 @@ class Sidebar(ctk.CTkFrame): def update_status(self, state, engine_ready: bool): try: - if state.model_loaded and state.current_model_name: - name = state.current_model_name - if len(name) > 26: - name = name[:25] + "…" - self.model_label.configure(text=name, text_color=c("text")) - self.dot_label.set(color=c("success")) - else: - self.model_label.configure(text="Модель не загружена", text_color=c("text_dim")) - self.dot_label.set(color=c("text_faint")) - - version = "" + engine_name = "" try: - version = self.app.engine.version() if self.app.engine else "" + if self.app.engine: + engine_name = self.app.engine.active_name() except Exception: pass + if len(engine_name) > 26: + engine_name = engine_name[:25] + "…" + self.model_label.configure( + text=engine_name or "Движок", + text_color=(c("text") if engine_ready else c("danger")), + ) + self.dot_label.set(color=(c("success") if engine_ready else c("danger"))) - if engine_ready: - text = f"Движок {version}" if version else "Движок" - self.engine_label.configure(text=text, text_color=c("text_faint")) + if state.model_loaded: + self.engine_label.configure(text="Модель загружена", text_color=c("text_faint")) else: - self.engine_label.configure(text="Движок не найден", text_color=c("danger")) + self.engine_label.configure(text="Модель не загружена", text_color=c("text_faint")) losses = [] try: diff --git a/XUI/components/statusbar.py b/XUI/components/statusbar.py index 096e20b..3074c70 100644 --- a/XUI/components/statusbar.py +++ b/XUI/components/statusbar.py @@ -42,10 +42,8 @@ class StatusBar(ctk.CTkFrame): right = ctk.CTkFrame(self, fg_color="transparent") right.pack(side="right", padx=16) - self.m_ctx = self._metric(right, "Контекст", "—") self.m_ram = self._metric(right, "RAM", "—") self.m_cpu = self._metric(right, "CPU", "—") - self.m_engine = self._metric(right, "Движок", "—") self.m_server = self._metric(right, "Сервер", "—", last=True) self._last_wall = time.time() @@ -56,6 +54,7 @@ class StatusBar(ctk.CTkFrame): v = self.app.engine.version() if getattr(self.app, "engine", None) else "" except Exception: v = "" + v = (v or "").split("·")[0].strip() return f"Xenith {v}" if v else "Xenith" def _dot(self, parent, padx=(0, 0)): @@ -80,7 +79,7 @@ class StatusBar(ctk.CTkFrame): def _metric(self, parent, title, value, last=False): box = ctk.CTkFrame(parent, fg_color="transparent") - box.pack(side="left", padx=(0 if last else 16, 0)) + box.pack(side="left", padx=(16, 0)) ctk.CTkLabel(box, text=title, font=ui_font(10), text_color=c("text_faint")).pack(side="left", padx=(0, 6)) val = ctk.CTkLabel(box, text=value, font=mono_font(11), @@ -111,17 +110,14 @@ class StatusBar(ctk.CTkFrame): def _context_text(self): state = getattr(self.app, "app_state", None) engine = getattr(self.app, "engine", None) - if not state or not state.model_loaded or not engine or engine.model is None: + if not state or not state.model_loaded or not engine: return "—", 0.0 try: - h = engine.model.chat_history() - if isinstance(h, dict): - used = h.get("context_used") - limit = h.get("context_max") - if used is not None and limit: - return f"{int(used)} / {int(limit)}", float(used) / float(limit) - if limit: - return f"— / {int(limit)}", 0.0 + used, limit, _ = engine.context_info() + if used is not None and limit: + return f"{int(used)} / {int(limit)}", float(used) / float(limit) + if limit: + return f"— / {int(limit)}", 0.0 except Exception: pass return "—", 0.0 @@ -135,19 +131,8 @@ class StatusBar(ctk.CTkFrame): self.brand_label.configure(text=self._brand_text()) - ctx_text, ctx_ratio = self._context_text() - self.m_ctx.configure( - text=ctx_text, - text_color=(c("danger") if ctx_ratio >= 1.0 else - (c("warn") if ctx_ratio >= 0.9 else c("text_dim"))), - ) self.m_ram.configure(text=_fmt_mb(self._process_ram_mb())) self.m_cpu.configure(text=f"{self._cpu_percent():.1f}%") - - ok = bool(engine and engine.is_ready()) - self.m_engine.configure(text="OK" if ok else "Нет", - text_color=(c("success") if ok else c("danger"))) - srv = bool(state.server_running) self.m_server.configure(text="Вкл" if srv else "Выкл", text_color=(c("success") if srv else c("text_faint"))) diff --git a/XUI/components/topbar.py b/XUI/components/topbar.py index f2c046d..08fa10d 100644 --- a/XUI/components/topbar.py +++ b/XUI/components/topbar.py @@ -30,7 +30,7 @@ class TopBar(ctk.CTkFrame): self.refresh_btn.pack(side="left", padx=(0, 4)) self.gear_btn = IconButton( - right, "gear", self.app.toggle_settings_popup, size=32, icon_size=17, + right, "gear", self.app.toggle_settings, size=32, icon_size=17, bg=c("content"), hover=c("card_hover"), ) self.gear_btn.pack(side="left") diff --git a/XUI/core/api_server.py b/XUI/core/api_server.py new file mode 100644 index 0000000..1ad257c --- /dev/null +++ b/XUI/core/api_server.py @@ -0,0 +1,941 @@ +"""HTTP API для Xenith Studio — только стандартная библиотека Python. + +Сервер предназначен для локального использования и будущего мобильного +приложения. Он не знает ничего о UI: вся работа с моделью выполняется через +переданные callable-объекты. + +Маршруты: + GET /health — проверка доступности (без токена); + GET /v1/models — список моделей в формате OpenAI; + POST /v1/chat/completions — чат в формате OpenAI (обычный и SSE-стрим); + GET /api/tags — список моделей в формате Ollama; + POST /api/chat — чат в формате Ollama (обычный и NDJSON-стрим). + +Особенности: + * Bearer-токен (или ?token=) для всех маршрутов, кроме /health; + * CORS для запросов из другого origin (например, из WebView телефона); + * ограничение тела запроса 2 МБ; + * один общий lock на вызовы модели — локальный движок не любит + параллельную генерацию. +""" + +from __future__ import annotations + +import json +import queue +import secrets +import threading +import time +import traceback +import uuid +from datetime import datetime, timezone +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Any, Callable, Optional +from urllib.parse import parse_qs, urlparse + +__all__ = ["ApiServer", "parse_messages"] + +MAX_BODY_BYTES = 2 * 1024 * 1024 +MAX_LOG_LINES = 300 +DEFAULT_MODEL = "xenith" +CORS_ALLOW_HEADERS = "Authorization, Content-Type, Accept, Origin, X-Requested-With" + +ChatCallable = Callable[ + [list[dict[str, Any]], dict[str, Any], Optional[Callable[[str], None]]], + str, +] +ModelsCallable = Callable[[], list[dict[str, Any]]] + + +# --------------------------------------------------------------------------- +# Нормализация сообщений +# --------------------------------------------------------------------------- + + +def _content_to_text(content: Any) -> str: + """Приводит content (строка / список частей / объект) к обычному тексту.""" + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): + return "".join(_content_to_text(part) for part in content) + if isinstance(content, dict): + # OpenAI: {"type": "text", "text": "..."} + # Некоторые клиенты присылают {"content": "..."}. + for key in ("text", "content"): + if key in content: + return _content_to_text(content[key]) + return "" + return str(content) + + +def parse_messages(messages: Any) -> list[dict[str, str]]: + """Нормализует сообщения OpenAI/Ollama в [{"role": ..., "content": ...}]. + + Поддерживаются: + * строка вместо массива сообщений; + * content-строка; + * content-массив текстовых частей (multimodal-формат OpenAI). + + Нетекстовые части (например, image_url) пропускаются — движок текстовый. + """ + if messages is None: + return [] + if isinstance(messages, str): + return [{"role": "user", "content": messages}] + if not isinstance(messages, list): + raise ValueError("messages должен быть массивом сообщений") + + result: list[dict[str, str]] = [] + for item in messages: + if isinstance(item, str): + result.append({"role": "user", "content": item}) + continue + if not isinstance(item, dict): + continue + role = str(item.get("role") or "user").strip().lower() or "user" + result.append( + { + "role": role, + "content": _content_to_text(item.get("content")), + } + ) + return result + + +# --------------------------------------------------------------------------- +# Вспомогательные функции +# --------------------------------------------------------------------------- + + +def _normalize_path(path: str) -> str: + """Убирает завершающие слеши, кроме корневого.""" + path = path or "/" + if len(path) > 1: + path = path.rstrip("/") + return path or "/" + + +def _as_float(value: Any, default: float) -> float: + try: + if value is None: + return default + return float(value) + except (TypeError, ValueError): + return default + + +def _as_int(value: Any, default: int) -> int: + try: + if value is None: + return default + return int(value) + except (TypeError, ValueError): + return default + + +def _lookup(sources: tuple[Any, ...], keys: tuple[str, ...], default: Any = None) -> Any: + for source in sources: + if not isinstance(source, dict): + continue + for key in keys: + value = source.get(key) + if value is not None: + return value + return default + + +def _build_params( + body: dict[str, Any], + options: Any = None, + *, + stream: bool = False, +) -> dict[str, Any]: + """Собирает params для chat_callable из OpenAI- или Ollama-запроса.""" + opts = options if isinstance(options, dict) else {} + sources = (body, opts) + + temperature = _as_float(_lookup(sources, ("temperature",), 0.7), 0.7) + top_p = _as_float(_lookup(sources, ("top_p",), 0.9), 0.9) + max_tokens = _as_int( + _lookup(sources, ("max_tokens", "max_completion_tokens", "num_predict"), 256), + 256, + ) + + # Держим значения в разумных пределах, чтобы не сломать движок. + temperature = max(0.0, min(temperature, 5.0)) + top_p = max(0.0, min(top_p, 1.0)) + max_tokens = max(1, min(max_tokens, 32768)) + + return { + "temperature": temperature, + "top_p": top_p, + "max_tokens": max_tokens, + "n": max_tokens, # совместимость с XenithEngine + "stream": bool(stream), + } + + +def _utc_now() -> str: + """Время в формате Ollama, например 2026-11-22T12:00:00Z.""" + return ( + datetime.now(timezone.utc) + .isoformat(timespec="seconds") + .replace("+00:00", "Z") + ) + + +class _ApiError(Exception): + """Ошибка запроса с HTTP-статусом (обрабатывается в do_POST/do_GET).""" + + def __init__(self, status: int, message: str) -> None: + super().__init__(message) + self.status = status + + +def _result_text(result: Any, collected: list[str]) -> str: + """Возвращает текст ответа, даже если движок отдал его только через on_token.""" + if isinstance(result, str): + text = result + elif result is None: + text = "" + else: + text = str(result) + return text or "".join(collected) + + +# --------------------------------------------------------------------------- +# Сервер +# --------------------------------------------------------------------------- + + +class ApiServer: + """Потоковый HTTP API-сервер Xenith. + + chat_callable(messages, params, on_token) -> str + Синхронный вызов модели. Может занимать секунды, вызывается из + отдельного потока запроса. on_token(piece) можно вызывать много раз. + models_callable() -> list[dict] + Список моделей; у элементов должны быть поля id и name. + """ + + def __init__( + self, + chat_callable: ChatCallable, + models_callable: ModelsCallable, + host: str = "127.0.0.1", + port: int = 1234, + token: str = "", + ) -> None: + if not callable(chat_callable): + raise TypeError("chat_callable должен быть вызываемым") + if not callable(models_callable): + raise TypeError("models_callable должен быть вызываемым") + + self.chat_callable = chat_callable + self.models_callable = models_callable + self.host = str(host) + self.port = int(port) + self.token = str(token or "") + self.engine_name = "xenith" + + # Последние строки лога (не более MAX_LOG_LINES) и необязательный callback. + self.log: list[str] = [] + self.log_callback: Optional[Callable[[str], None]] = None + + self._state_lock = threading.Lock() + self._log_lock = threading.Lock() + self._chat_lock = threading.Lock() + self._server: Optional[_ApiHTTPServer] = None + self._thread: Optional[threading.Thread] = None + + # -- состояние --------------------------------------------------------- + + @property + def is_running(self) -> bool: + thread = self._thread + return bool(thread is not None and thread.is_alive()) + + @property + def address(self) -> str: + host = self.host + if ":" in host and not host.startswith("["): + host = f"[{host}]" # IPv6 + return f"{host}:{self.port}" + + def _emit_log(self, message: str) -> None: + line = f"{time.strftime('%H:%M:%S')} {message}" + with self._log_lock: + self.log.append(line) + if len(self.log) > MAX_LOG_LINES: + del self.log[: len(self.log) - MAX_LOG_LINES] + callback = self.log_callback + if callback is not None: + try: + callback(line) + except Exception: + # Ошибка в пользовательском логгере не должна ронять сервер. + pass + + def start(self) -> None: + """Запускает сервер в фоновом потоке. Не блокирует вызывающий код.""" + with self._state_lock: + if self.is_running: + self._emit_log("API-сервер уже запущен") + return + + try: + httpd = _ApiHTTPServer((self.host, self.port), _ApiHandler) + except OSError as exc: + raise RuntimeError( + f"Не удалось запустить API-сервер на {self.host}:{self.port}: " + f"порт занят или недоступен ({exc})" + ) from exc + + httpd.api = self + httpd.daemon_threads = True + httpd.allow_reuse_address = True + self._server = httpd + + # Если был запрошен port=0, узнаём реальный порт. + self.port = int(httpd.server_address[1]) + self._thread = threading.Thread( + target=httpd.serve_forever, + kwargs={"poll_interval": 0.2}, + name="xenith-api", + daemon=True, + ) + self._thread.start() + address = self.address + + self._emit_log(f"API-сервер запущен: http://{address}") + if not self.token and self.host not in ("127.0.0.1", "localhost", "::1"): + self._emit_log("Внимание: API доступен без токена не только с localhost") + + def stop(self) -> None: + """Корректно останавливает сервер и ждёт завершения его потока.""" + with self._state_lock: + httpd = self._server + thread = self._thread + self._server = None + self._thread = None + + if httpd is None: + return + + self._emit_log("Остановка API-сервера...") + try: + httpd.shutdown() + except Exception as exc: + self._emit_log(f"shutdown: {exc}") + try: + httpd.server_close() + except Exception as exc: + self._emit_log(f"server_close: {exc}") + + if thread is not None and thread is not threading.current_thread(): + thread.join(timeout=5.0) + if thread.is_alive(): + self._emit_log("Поток API-сервера не завершился за 5 секунд") + + self._emit_log("API-сервер остановлен") + + # -- данные для маршрутов --------------------------------------------- + + def _load_models(self) -> list[dict[str, str]]: + try: + raw = self.models_callable() + except Exception as exc: + self._emit_log(f"models_callable: {exc}") + return [] + + if not isinstance(raw, list): + return [] + + result: list[dict[str, str]] = [] + for item in raw: + if isinstance(item, str): + model_id = name = item.strip() + elif isinstance(item, dict): + model_id = str(item.get("id") or item.get("name") or "").strip() + name = str(item.get("name") or model_id).strip() + else: + continue + if model_id: + result.append({"id": model_id, "name": name or model_id}) + return result + + def default_model(self) -> str: + models = self._load_models() + return models[0]["id"] if models else DEFAULT_MODEL + + def _is_authorized(self, headers: Any, query: dict[str, list[str]]) -> bool: + if not self.token: + return True + + supplied = "" + authorization = headers.get("Authorization") or "" + parts = authorization.split(None, 1) + if len(parts) == 2 and parts[0].lower() == "bearer": + supplied = parts[1].strip() + elif authorization: + supplied = authorization.strip() + + # Совместимость: ?token=... (удобно для простых клиентов/WebView). + if not supplied: + values = query.get("token") or [] + if values: + supplied = str(values[0]) + + return secrets.compare_digest( + supplied.encode("utf-8"), + self.token.encode("utf-8"), + ) + + +# --------------------------------------------------------------------------- +# HTTP-сервер и обработчик +# --------------------------------------------------------------------------- + + +class _ApiHTTPServer(ThreadingHTTPServer): + daemon_threads = True + allow_reuse_address = True + request_queue_size = 64 + api: "ApiServer" + + +class _ApiHandler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + server_version = "XenithAPI/1.0" + sys_version = "" + timeout = 60 # не держим «зависшие» соединения вечно + + _headers_sent = False + _disconnect_logged = False + + # -- инфраструктура ---------------------------------------------------- + + @property + def api(self) -> ApiServer: + return self.server.api # type: ignore[attr-defined] + + def setup(self) -> None: + super().setup() + self._headers_sent = False + self._disconnect_logged = False + + def handle_one_request(self) -> None: + # Флаги сбрасываются на каждый запрос при keep-alive. + self._headers_sent = False + self._disconnect_logged = False + super().handle_one_request() + + def finish(self) -> None: + try: + super().finish() + except OSError: + # Клиент мог закрыть соединение раньше нас — это нормально. + self.close_connection = True + + def log_message(self, format: str, *args: Any) -> None: + try: + self.api._emit_log(f"{self.client_address[0]} — {format % args}") + except Exception: + pass + + def _send_cors(self, allow_headers: Optional[str] = None) -> None: + self.send_header("Access-Control-Allow-Origin", "*") + self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") + self.send_header( + "Access-Control-Allow-Headers", + allow_headers or CORS_ALLOW_HEADERS, + ) + self.send_header("Access-Control-Expose-Headers", "Content-Type") + + def _send_json( + self, + status: int, + payload: Any, + *, + extra_headers: Optional[dict[str, str]] = None, + ) -> None: + if self._headers_sent: + return + body = json.dumps(payload, ensure_ascii=False).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + self._send_cors() + if extra_headers: + for key, value in extra_headers.items(): + self.send_header(key, value) + if self.close_connection: + self.send_header("Connection", "close") + self.end_headers() + self._headers_sent = True + try: + self.wfile.write(body) + self.wfile.flush() + except OSError: + self.close_connection = True + + def _send_error_json( + self, + status: int, + message: str, + *, + ollama: bool = False, + extra_headers: Optional[dict[str, str]] = None, + ) -> None: + self.api._emit_log(f"Ошибка {status}: {message}") + if ollama: + # Ollama-клиенты ожидают error строкой. + payload: Any = {"error": message} + else: + payload = { + "error": { + "message": message, + "type": "invalid_request_error" if status < 500 else "server_error", + "code": status, + } + } + self._send_json(status, payload, extra_headers=extra_headers) + + def _log_disconnect(self, exc: BaseException) -> None: + self.close_connection = True + if self._disconnect_logged: + return + self._disconnect_logged = True + self.api._emit_log(f"Клиент отключился во время потоковой передачи: {exc}") + + def _write_sse(self, payload: Optional[dict[str, Any]]) -> bool: + """Пишет SSE-событие. Возвращает False, если клиент отключился.""" + if payload is None: + raw = b"data: [DONE]\n\n" + else: + raw = ( + "data: " + + json.dumps(payload, ensure_ascii=False) + + "\n\n" + ).encode("utf-8") + try: + self.wfile.write(raw) + self.wfile.flush() + return True + except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError) as exc: + # BrokenPipeError/ConnectionResetError — штатный уход клиента. + self._log_disconnect(exc) + return False + + def _write_ndjson(self, payload: dict[str, Any]) -> bool: + raw = (json.dumps(payload, ensure_ascii=False) + "\n").encode("utf-8") + try: + self.wfile.write(raw) + self.wfile.flush() + return True + except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError) as exc: + self._log_disconnect(exc) + return False + + # -- чтение и проверка запроса ---------------------------------------- + + def _check_auth(self, parsed: Any) -> bool: + query = parse_qs(parsed.query) + if self.api._is_authorized(self.headers, query): + return True + # Тело POST не читаем — соединение нужно закрыть, иначе остаток тела + # будет воспринят как следующий HTTP-запрос. + if self.command == "POST": + self.close_connection = True + self._send_error_json( + 401, + "Неверный или отсутствующий токен", + extra_headers={"WWW-Authenticate": "Bearer"}, + ) + return False + + def _read_json(self) -> dict[str, Any]: + transfer_encoding = (self.headers.get("Transfer-Encoding") or "").lower() + if "chunked" in transfer_encoding: + self.close_connection = True + raise _ApiError(400, "Chunked-запросы не поддерживаются, укажите Content-Length") + + raw_length = self.headers.get("Content-Length") + if raw_length is None or not raw_length.strip(): + return {} + + try: + length = int(raw_length) + except ValueError: + self.close_connection = True + raise _ApiError(400, "Некорректный заголовок Content-Length") from None + + if length < 0: + self.close_connection = True + raise _ApiError(400, "Content-Length не может быть отрицательным") + if length > MAX_BODY_BYTES: + self.close_connection = True + raise _ApiError( + 413, + f"Тело запроса больше {MAX_BODY_BYTES // (1024 * 1024)} МБ", + ) + if length == 0: + return {} + + raw = self.rfile.read(length) + if len(raw) != length: + self.close_connection = True + raise _ApiError(400, "Не удалось прочитать тело запроса целиком") + + try: + text = raw.decode("utf-8") + except UnicodeDecodeError as exc: + raise _ApiError(400, f"Тело запроса не в UTF-8: {exc}") from None + + try: + payload = json.loads(text) + except json.JSONDecodeError as exc: + raise _ApiError( + 400, + f"Некорректный JSON: {exc.msg} (строка {exc.lineno})", + ) from None + + if not isinstance(payload, dict): + raise _ApiError(400, "Тело запроса должно быть JSON-объектом") + return payload + + def _prepare_chat( + self, + *, + default_stream: bool, + ) -> tuple[list[dict[str, Any]], dict[str, Any], str, bool, dict[str, Any]]: + body = self._read_json() + + raw_messages = body.get("messages") + if not isinstance(raw_messages, list) or not raw_messages: + raise _ApiError(400, "Поле messages обязательно и должно быть непустым массивом") + + try: + messages = parse_messages(raw_messages) + except ValueError as exc: + raise _ApiError(400, str(exc)) from None + if not messages: + raise _ApiError(400, "После нормализации не осталось ни одного сообщения") + + stream = bool(body.get("stream", default_stream)) + model = str(body.get("model") or "").strip() or self.api.default_model() + options = body.get("options") + params = _build_params( + body, + options if isinstance(options, dict) else None, + stream=stream, + ) + return messages, params, model, stream, body + + def _collect_chat( + self, + messages: list[dict[str, Any]], + params: dict[str, Any], + ) -> str: + collected: list[str] = [] + + def on_token(piece: str) -> None: + if piece: + collected.append(str(piece)) + + with self.api._chat_lock: + result = self.api.chat_callable(messages, params, on_token) + return _result_text(result, collected) + + def _start_chat_events( + self, + messages: list[dict[str, Any]], + params: dict[str, Any], + ) -> "queue.Queue[tuple[str, str]]": + """Запускает chat_callable в отдельном потоке и отдаёт очередь событий. + + События: ("token", piece), ("done", ""), ("error", message). + Очередь не ограничена, поэтому медленный/отключившийся клиент не + блокирует поток модели. + """ + events: "queue.Queue[tuple[str, str]]" = queue.Queue() + + def worker() -> None: + emitted = False + + def on_token(piece: str) -> None: + nonlocal emitted + if not piece: + return + emitted = True + events.put(("token", str(piece))) + + try: + with self.api._chat_lock: + result = self.api.chat_callable(messages, params, on_token) + text = "" if result is None else (result if isinstance(result, str) else str(result)) + if not emitted and text: + # Движок не умеет стримить — отдаём весь ответ одним куском. + events.put(("token", text)) + events.put(("done", "")) + except Exception as exc: + self.api._emit_log(f"Ошибка chat_callable: {exc}") + self.api._emit_log(traceback.format_exc().strip()) + events.put(("error", str(exc))) + + threading.Thread( + target=worker, + name="xenith-api-chat", + daemon=True, + ).start() + return events + + # -- GET --------------------------------------------------------------- + + def do_GET(self) -> None: + parsed = urlparse(self.path) + path = _normalize_path(parsed.path) + + # /health доступен без токена: удобно для проверки «жив ли сервер». + if path == "/health": + self._send_json( + 200, + { + "status": "ok", + "engine": self.api.engine_name, + "auth_required": bool(self.api.token), + }, + ) + return + + if not self._check_auth(parsed): + return + + try: + if path == "/v1/models": + models = self.api._load_models() + self._send_json( + 200, + { + "object": "list", + "data": [ + { + "id": model["id"], + "object": "model", + "owned_by": "xenith", + } + for model in models + ], + }, + ) + elif path == "/api/tags": + models = self.api._load_models() + self._send_json( + 200, + { + "models": [ + {"name": model["id"], "model": model["id"]} + for model in models + ] + }, + ) + else: + self.close_connection = True + self._send_error_json(404, f"Маршрут не найден: {path}") + except Exception as exc: + self.api._emit_log(f"Ошибка GET {path}: {exc}") + self._send_error_json(500, str(exc)) + + # -- POST -------------------------------------------------------------- + + def do_POST(self) -> None: + parsed = urlparse(self.path) + path = _normalize_path(parsed.path) + + if not self._check_auth(parsed): + return + + try: + if path == "/v1/chat/completions": + self._handle_openai_chat() + elif path == "/api/chat": + self._handle_ollama_chat() + else: + # Тело неизвестного маршрута не читаем — закрываем соединение. + self.close_connection = True + self._send_error_json(404, f"Маршрут не найден: {path}") + except _ApiError as exc: + self._send_error_json( + exc.status, + str(exc), + ollama=(path == "/api/chat"), + ) + except (BrokenPipeError, ConnectionResetError): + self.close_connection = True + self.api._emit_log("Соединение с клиентом потеряно") + except Exception as exc: + # Любая ошибка модели/обработки — JSON 500, сервер продолжает жить. + self.api._emit_log(f"Необработанная ошибка POST {path}: {exc}") + self.api._emit_log(traceback.format_exc().strip()) + self._send_error_json(500, str(exc), ollama=(path == "/api/chat")) + + def _handle_openai_chat(self) -> None: + messages, params, model, stream, _body = self._prepare_chat(default_stream=False) + + if stream: + self._stream_openai(messages, params, model) + return + + text = self._collect_chat(messages, params) + completion_id = f"chatcmpl-{uuid.uuid4().hex}" + self._send_json( + 200, + { + "id": completion_id, + "object": "chat.completion", + "created": int(time.time()), + "model": model, + "choices": [ + { + "index": 0, + "message": {"role": "assistant", "content": text}, + "finish_reason": "stop", + } + ], + "usage": { + "prompt_tokens": 0, + "completion_tokens": 0, + "total_tokens": 0, + }, + }, + ) + + def _stream_openai( + self, + messages: list[dict[str, Any]], + params: dict[str, Any], + model: str, + ) -> None: + completion_id = f"chatcmpl-{uuid.uuid4().hex}" + created = int(time.time()) + + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Cache-Control", "no-cache") + self.send_header("X-Accel-Buffering", "no") + self._send_cors() + self.send_header("Connection", "close") + self.end_headers() + self._headers_sent = True + self.close_connection = True + + def chunk(delta: dict[str, Any], finish_reason: Optional[str] = None) -> dict[str, Any]: + return { + "id": completion_id, + "object": "chat.completion.chunk", + "created": created, + "model": model, + "choices": [ + { + "index": 0, + "delta": delta, + "finish_reason": finish_reason, + } + ], + } + + # Первый чанк — роль, как в OpenAI. + if not self._write_sse(chunk({"role": "assistant", "content": ""})): + return + + events = self._start_chat_events(messages, params) + while True: + kind, value = events.get() + + if kind == "token": + if not self._write_sse(chunk({"content": value})): + return + elif kind == "error": + if self._write_sse( + {"error": {"message": value, "type": "server_error"}} + ): + self._write_sse(None) + return + else: # done + if self._write_sse(chunk({}, "stop")): + self._write_sse(None) + return + + def _handle_ollama_chat(self) -> None: + # Ollama по умолчанию стримит, поэтому default_stream=True. + messages, params, model, stream, _body = self._prepare_chat(default_stream=True) + + if stream: + self._stream_ollama(messages, params, model) + return + + text = self._collect_chat(messages, params) + self._send_json( + 200, + { + "model": model, + "created_at": _utc_now(), + "message": {"role": "assistant", "content": text}, + "done": True, + }, + ) + + def _stream_ollama( + self, + messages: list[dict[str, Any]], + params: dict[str, Any], + model: str, + ) -> None: + created_at = _utc_now() + + self.send_response(200) + self.send_header("Content-Type", "application/x-ndjson") + self.send_header("Cache-Control", "no-cache") + self.send_header("X-Accel-Buffering", "no") + self._send_cors() + self.send_header("Connection", "close") + self.end_headers() + self._headers_sent = True + self.close_connection = True + + def line(content: str, done: bool) -> dict[str, Any]: + return { + "model": model, + "created_at": created_at, + "message": {"role": "assistant", "content": content}, + "done": done, + } + + events = self._start_chat_events(messages, params) + while True: + kind, value = events.get() + + if kind == "token": + if not self._write_ndjson(line(value, False)): + return + elif kind == "error": + # Формат ошибки Ollama: одна JSON-строка с полем error. + self._write_ndjson({"error": value, "done": True}) + return + else: # done + self._write_ndjson(line("", True)) + return + + # -- OPTIONS (CORS preflight) ----------------------------------------- + + def do_OPTIONS(self) -> None: + # Preflight не содержит Authorization, поэтому токен здесь не проверяем. + requested = self.headers.get("Access-Control-Request-Headers") + self.send_response(204) + self._send_cors(requested or CORS_ALLOW_HEADERS) + self.send_header("Access-Control-Max-Age", "86400") + self.send_header("Content-Length", "0") + self.end_headers() diff --git a/XUI/core/config.py b/XUI/core/config.py new file mode 100644 index 0000000..203ced9 --- /dev/null +++ b/XUI/core/config.py @@ -0,0 +1,111 @@ +"""Конфигурация Xenith Studio: движки, сервер, MCP, UI. + +Единый JSON в ~/.config/xenith-studio/config.json. +Секреты (API-ключи, токен сервера) хранятся там же с правами 0600. +""" + +import copy +import json +import os +import threading + +_DIR = os.path.join(os.path.expanduser("~"), ".config", "xenith-studio") +_PATH = os.path.join(_DIR, "config.json") + +_LOCK = threading.Lock() + +DEFAULT_CONFIG = { + "version": 1, + "active_engine": "xenith", + "engines": { + "xenith": { + "type": "xenith", + "name": "Xenith", + "enabled": True, + }, + "ollama-local": { + "type": "ollama", + "name": "Ollama", + "base_url": "http://127.0.0.1:11434", + "enabled": True, + }, + }, + "server": { + "host": "127.0.0.1", + "port": 1234, + "token": "", + "enabled": False, + }, + "mcp": { + "mode": "smart", # smart | full | restricted + "roots": [], + "servers": {}, + }, +} + + +def _merge(base, override): + out = copy.deepcopy(base) + if not isinstance(override, dict): + return out + for k, v in override.items(): + if isinstance(v, dict) and isinstance(out.get(k), dict): + out[k] = _merge(out[k], v) + else: + out[k] = copy.deepcopy(v) + return out + + +def load() -> dict: + _migrate_prefs() + try: + with open(_PATH, "r", encoding="utf-8") as f: + data = json.load(f) + except Exception: + data = {} + cfg = _merge(DEFAULT_CONFIG, data if isinstance(data, dict) else {}) + try: + eng = (cfg.get("engines") or {}).get("xenith") + if isinstance(eng, dict) and eng.get("name") in ("Xenith (локальный)", "Xenith (local)"): + eng["name"] = "Xenith" + except Exception: + pass + return cfg + + +def save(cfg: dict) -> bool: + try: + os.makedirs(_DIR, exist_ok=True) + tmp = _PATH + ".tmp" + with _LOCK: + with open(tmp, "w", encoding="utf-8") as f: + json.dump(cfg, f, ensure_ascii=False, indent=2) + try: + os.chmod(tmp, 0o600) + except Exception: + pass + os.replace(tmp, _PATH) + return True + except Exception: + return False + + +def _migrate_prefs(): + """Перенести старый ui.json в новую структуру один раз.""" + if os.path.exists(_PATH): + return + old = os.path.join(_DIR, "ui.json") + if not os.path.exists(old): + return + try: + with open(old, "r", encoding="utf-8") as f: + ui = json.load(f) + except Exception: + return + cfg = copy.deepcopy(DEFAULT_CONFIG) + if isinstance(ui, dict): + cfg["ui"] = { + "theme": ui.get("theme", "dark"), + "ui_scale": ui.get("ui_scale", 1.0), + } + save(cfg) diff --git a/XUI/core/engine.py b/XUI/core/engine.py index e5adf32..c0389c9 100644 --- a/XUI/core/engine.py +++ b/XUI/core/engine.py @@ -1,24 +1,238 @@ -import os -import queue -import threading -from typing import Optional, Callable, Any +"""Менеджер движков Xenith Studio. + +Совместим с прежним API XenithEngine (chat/generate/load_model/...), +но внутри выбирает адаптер: Xenith native, Ollama или OpenAI-совместимый. +""" + +import os +import threading + +from . import config as app_config +from .engines.base import EngineError, normalize_messages, normalize_params +from .engines.native import XenithAdapter +from .engines.openai_compat import OpenAICompatAdapter +from .engines.ollama import OllamaAdapter +from .state import AppState + +ADAPTER_TYPES = { + "xenith": XenithAdapter, + "ollama": OllamaAdapter, + "openai": OpenAICompatAdapter, +} -try: - import xenith_engine as xe -except Exception as e: - xe = None - print(f"[XenithEngine] не удалось импортировать xenith_engine: {e}") class XenithEngine: - def __init__(self, state=None): + def __init__(self, state: AppState = None): self.app_state = state - self.state = state # совместимость - self.model = None - self.backend = "cpu" - self.backend_info = "CPU" + self.state = state + self.config = app_config.load() + self._adapters = {} + self._active_id = None self._lock = threading.Lock() - self._queue = queue.Queue() - self._init_backend() + self._busy = False + self._training = False + self.last_error = "" + self._build_adapters() + self.set_active_engine(self.config.get("active_engine") or "xenith", persist=False) + + # ---------- конфиг и адаптеры ---------- + def _build_adapters(self): + self._adapters = {} + engines = self.config.get("engines") or {} + for eid, conf in engines.items(): + if not isinstance(conf, dict): + continue + typ = str(conf.get("type") or "") + cls = ADAPTER_TYPES.get(typ) + if cls is None: + continue + try: + self._adapters[eid] = cls(eid, conf, self.app_state) + except Exception as e: + self.log(f"Не удалось создать движок {eid}: {e}") + if "xenith" not in self._adapters: + conf = {"type": "xenith", "name": "Xenith (локальный)", "enabled": True} + self._adapters["xenith"] = XenithAdapter("xenith", conf, self.app_state) + self.config.setdefault("engines", {})["xenith"] = conf + + def save_config(self): + app_config.save(self.config) + + def engines(self): + out = [] + for eid, ad in self._adapters.items(): + conf = (self.config.get("engines") or {}).get(eid, {}) + out.append({ + "id": eid, + "name": ad.name, + "type": ad.type, + "enabled": bool(conf.get("enabled", True)), + "active": eid == self._active_id, + "describe": ad.describe(), + }) + return out + + def get_engine(self, engine_id: str): + return self._adapters.get(str(engine_id)) + + def active(self): + return self._adapters.get(self._active_id) + + @property + def active_id(self) -> str: + return self._active_id or "" + + def active_name(self) -> str: + ad = self.active() + return ad.name if ad else "—" + + def set_active_engine(self, engine_id: str, persist: bool = True) -> bool: + engine_id = str(engine_id or "") + ad = self._adapters.get(engine_id) + if ad is None: + # fallback на Xenith + engine_id = "xenith" + ad = self._adapters.get("xenith") + if ad is None: + return False + self._active_id = engine_id + self.config["active_engine"] = engine_id + conf = (self.config.get("engines") or {}).get(engine_id, {}) + conf["active"] = True + if self.app_state is not None: + self.app_state.current_engine_id = engine_id + self.app_state.current_engine_name = ad.name + if ad.type != "xenith": + # Удалённый движок не имеет локального файла модели. + if ad.model_id: + self.app_state.model_loaded = True + self.app_state.current_model_name = ad.model_id + self.app_state.current_model_path = "" + else: + self.app_state.model_loaded = False + if persist: + self.save_config() + self.log(f"Активный движок: {ad.name}") + return True + + def upsert_engine(self, engine_id: str, conf: dict) -> bool: + engine_id = str(engine_id or "").strip() + if not engine_id: + return False + typ = str((conf or {}).get("type") or "") + cls = ADAPTER_TYPES.get(typ) + if cls is None: + raise EngineError(f"Неизвестный тип движка: {typ}") + self.config.setdefault("engines", {})[engine_id] = dict(conf) + try: + self._adapters[engine_id] = cls(engine_id, dict(conf), self.app_state) + except Exception as e: + raise EngineError(str(e)) + self.save_config() + self.log(f"Сохранён движок {engine_id} ({typ})") + return True + + def remove_engine(self, engine_id: str) -> bool: + if engine_id == "xenith": + return False + self._adapters.pop(engine_id, None) + (self.config.get("engines") or {}).pop(engine_id, None) + if self._active_id == engine_id: + self.set_active_engine("xenith") + self.save_config() + return True + + def test_engine(self, engine_id: str): + ad = self.get_engine(engine_id) + if ad is None: + return False, "Движок не найден" + try: + return ad.health() + except Exception as e: + return False, str(e) + + # ---------- статус ---------- + def is_ready(self) -> bool: + return self.active() is not None + + def is_busy(self) -> bool: + return self._busy + + def is_training(self) -> bool: + return self._training + + def set_training(self, value: bool): + self._training = bool(value) + + def capabilities(self): + ad = self.active() + return ad.capabilities() if ad else None + + def can_train(self) -> bool: + caps = self.capabilities() + return bool(caps and caps.train) + + @property + def model(self): + ad = self.active() + if ad is not None and ad.type == "xenith": + return getattr(ad, "model", None) + return None + + def native_model(self): + ad = self._adapters.get("xenith") + return getattr(ad, "model", None) if ad else None + + def set_native_model(self, model): + """Подставить модель, созданную/обученную в памяти, в нативный адаптер.""" + ad = self._adapters.get("xenith") + if ad is None: + return + ad._model = model + try: + path = getattr(model, "path", "") or "" + except Exception: + path = "" + ad.model_id = path + if self.app_state is not None: + self.app_state.model_loaded = True + if path: + self.app_state.current_model_path = path + self.app_state.current_model_name = os.path.basename(path) + self.app_state.current_engine_id = "xenith" + self.app_state.current_engine_name = ad.name + + def version(self) -> str: + ad = self.active() + return ad.version() if ad else "" + + def build_type(self) -> str: + return "" + + def describe(self) -> str: + ad = self.active() + return ad.describe() if ad else "—" + + def info(self) -> dict: + ad = self.active() + if ad is None: + return {} + out = { + "engine_id": ad.id, + "engine_type": ad.type, + "engine_name": ad.name, + "engine_version": ad.version(), + "model_id": ad.model_id, + "busy": self._busy, + "training": self._training, + } + m = self.model + if m is not None and hasattr(m, "info"): + try: + out["model_info"] = m.info() + except Exception: + pass + return out def log(self, msg: str): if self.app_state is not None: @@ -26,140 +240,57 @@ class XenithEngine: else: print(f"[ENGINE] {msg}") - def _init_backend(self): - """Поднять Vulkan-бэкенд, если движок собран с ним и есть GPU. + # ---------- модели ---------- + def list_models(self, engine_id: str = None): + ad = self.get_engine(engine_id) if engine_id else self.active() + if ad is None: + raise EngineError("Движок не выбран") + return ad.list_models() - Движок сам выбирает дискретную видеокарту при device_index=-1. - При любой ошибке остаёмся на CPU — приложение продолжает работать. - """ - if xe is None: - return - try: - if not getattr(xe, "vulkan_available", lambda: False)(): - self.log("Движок собран без Vulkan — работа на CPU") - return - res = xe.init_vulkan(-1) - ok = bool(res.get("ok")) if isinstance(res, dict) else bool(res) - if ok: - self.backend = "vulkan" - self.backend_info = str(res.get("device") or "GPU") - self.log(f"GPU-бэкенд Vulkan: {self.backend_info}") - else: - err = res.get("error") if isinstance(res, dict) else "" - self.log(f"Vulkan не инициализировался ({err or 'неизвестная ошибка'}) — CPU") - except Exception as e: - self.log(f"Vulkan init: {e} — CPU") - - def reset_chat(self): - try: - if self.model is not None and hasattr(self.model, "chat_reset"): - self.model.chat_reset() - self.log("История чата модели сброшена") - except Exception as e: - self.log(f"reset_chat: {e}") - - def set_system_prompt(self, prompt: str): - try: - if self.model is not None and hasattr(self.model, "chat_set_system"): - self.model.chat_set_system(prompt or "") - if prompt: - self.log("Системный промпт установлен") - else: - self.log("Системный промпт очищен") - except Exception as e: - self.log(f"set_system_prompt: {e}") - - def is_ready(self) -> bool: - return xe is not None - - def version(self) -> str: - """Версия самого движка Xenith (не приложения).""" - try: - if xe is not None and hasattr(xe, "version"): - return str(xe.version()) - except Exception: - pass - return "" - - def build_type(self) -> str: - try: - if xe is not None and hasattr(xe, "build_type"): - return str(xe.build_type()) - except Exception: - pass - return "" - - def _model_dirs(self): - """Каталоги, где XUI ищет модели, в порядке приоритета.""" - dirs = [] - - # Модели внутри установленного Python-пакета (если import xenith сработал). - try: - import xenith - pkg = getattr(xenith, "__file__", None) - if pkg: - dirs.append(os.path.join(os.path.dirname(os.path.abspath(pkg)), "models")) - except Exception as e: - self.log(f"scan_models: {e}") - - # Корень проекта: XUI/core/engine.py -> - root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - dirs.append(os.path.join(root, "xenith", "models")) # /xenith/models - dirs.append(os.path.join(root, "models")) # /models - dirs.append(os.path.join(os.getcwd(), "models")) # ./models от текущего каталога - - return dirs + def models_by_engine(self): + out = {} + for eid, ad in self._adapters.items(): + try: + out[eid] = ad.list_models() + except Exception as e: + out[eid] = e + return out def scan_models(self, extra_paths=None): - paths = [] - for mdir in self._model_dirs(): - try: - if not os.path.isdir(mdir): - continue - for f in os.listdir(mdir): - full = os.path.join(mdir, f) - if os.path.isfile(full) and f.lower().endswith((".xnh", ".gguf", ".safetensors")): - paths.append(full) - except Exception as e: - self.log(f"scan_models: {e}") + """Совместимость: локальные файлы нативного движка.""" + ad = self._adapters.get("xenith") + if ad is None: + return [] + try: + return [m.path for m in ad.list_models() if m.path] + except Exception: + return [] - if extra_paths: - for p in extra_paths: - if os.path.isfile(p): - paths.append(p) - elif os.path.isdir(p): - for f in os.listdir(p): - full = os.path.join(p, f) - if os.path.isfile(full): - paths.append(full) + def load_model(self, model_id: str, on_done=None, engine_id: str = None): + ad = self.get_engine(engine_id) if engine_id else self.active() + if ad is None: + self._set_error("Движок не выбран") + if on_done: + on_done() + return - # Один и тот же файл может попасть из нескольких каталогов (models -> xenith/models). - seen = set() - uniq = [] - for p in paths: - ap = os.path.abspath(p) - key = os.path.realpath(ap) - if key not in seen: - seen.add(key) - uniq.append(ap) - return uniq - def load_model(self, model_path: str, on_done: Optional[Callable] = None): - def _task(): + def task(): try: - with self._lock: - self.log(f"Загрузка модели: {model_path}") - try: - self.model = xe.Model(model_path) - except TypeError: - self.model = xe.Model() - if hasattr(self.model, "load"): - self.model.load(model_path) - if self.app_state is not None: - self.app_state.current_model_path = model_path - self.app_state.current_model_name = os.path.basename(model_path) - self.app_state.model_loaded = True - self.log("Модель загружена") + self.log(f"Загрузка модели: {model_id} ({ad.name})") + ad.load_model(model_id) + if self.app_state is not None: + self.app_state.model_loaded = True + if ad.type == "xenith": + self.app_state.current_model_name = os.path.basename(str(model_id)) + self.app_state.current_model_path = str(model_id) + else: + self.app_state.current_model_name = ad.model_id or str(model_id) + self.app_state.current_model_path = "" + self.app_state.current_engine_id = ad.id + self.app_state.current_engine_name = ad.name + self.log("Модель загружена") except Exception as e: + self._set_error(str(e)) self.log(f"Ошибка загрузки: {e}") if self.app_state is not None: self.app_state.model_loaded = False @@ -169,224 +300,154 @@ class XenithEngine: on_done() except Exception: pass - t = threading.Thread(target=_task, daemon=True) - t.start() - def _normalize_gen_params(self, params: dict = None) -> dict: - """Приводит имена параметров к вариантам, которые ожидает xenith_engine.""" - p = dict(params or {}) - # В UI храним max_new_tokens, но xenith.generate/chat часто принимает n - if "n" not in p: - if "max_new_tokens" in p: - p["n"] = p.get("max_new_tokens") - elif "max_tokens" in p: - p["n"] = p.get("max_tokens") - # Разумный лимит по умолчанию, чтобы не уходить в бесконечную генерацию - try: - if "n" not in p or p["n"] is None: - p["n"] = 256 - p["n"] = max(1, min(int(p["n"]), 4096)) - except Exception: - p["n"] = 256 - return p + threading.Thread(target=task, daemon=True).start() - def generate(self, promt: str, params: dict = None, on_result: Optional[Callable[[str], None]] = None): - if self.model is None: - self.log("generate: модель не загружена") - msg = "[ОШИБКА] Модель не загружена. Загрузите модель во вкладке 'Модели'." - if self.app_state: - try: - self.app_state.add_interaction("generate", input_text=promt, output_text=msg, params=params or {}, ok=False, error=msg) - except Exception: - pass - if on_result: - on_result(msg) - return + def load_engine_model(self, engine_id: str, model_id: str, on_done=None): + self.load_model(model_id, on_done=on_done, engine_id=engine_id) - params = self._normalize_gen_params(params) + def _set_error(self, msg: str): + self.last_error = str(msg) - def _task(): + # ---------- чат/генерация ---------- + def _prepare_messages(self, messages, ad): + msgs = normalize_messages(messages) + if ad.type != "xenith" and self.app_state is not None: + system = getattr(self.app_state, "system_prompt", "") or "" + if system and not any(m.get("role") == "system" for m in msgs): + msgs = [{"role": "system", "content": system}] + msgs + return msgs + + def _run_async(self, kind: str, fn, on_result, prompt_for_log: str, params: dict, on_token=None): + if on_result is None: + on_result = lambda _t: None + with self._lock: + if self._busy: + on_result("[ОШИБКА] Движок занят другой операцией") + return + self._busy = True + + def task(): + text = "" + err = "" try: - self.log(f"Генерация... n={params.get('n')}") - res = None - # Сначала пробуем явные аргументы (самый совместимый вариант для xenith) + text = fn() + self.log(f"{kind}: готово ({len(text)} символов)") + except Exception as e: + err = str(e) + text = f"[ОШИБКА] {err}" + self.log(f"{kind}: {err}") + finally: + self._busy = False + if self.app_state is not None: try: - res = self.model.generate( - promt, - n=params.get("n", 256), - temperature=params.get("temperature", 0.7), - top_p=params.get("top_p", 0.9), - seed=params.get("seed"), + self.app_state.add_interaction( + kind, input_text=prompt_for_log, output_text=text, + params=params, ok=not err, error=err, + meta={"engine": self.active_name(), "model": getattr(self.app_state, "current_model_name", "")}, ) - except TypeError: - # Убираем None seed и пробуем снова - try: - res = self.model.generate( - promt, - n=params.get("n", 256), - temperature=params.get("temperature", 0.7), - top_p=params.get("top_p", 0.9), - ) - except Exception: - # Последний фолбэк: как есть - try: - res = self.model.generate(promt, **params) - except Exception: - res = self.model.generate(promt, n=params.get("n", 256)) - text = "" - if res is None: - text = "" - elif isinstance(res, str): - text = res - else: - for attr in ("text", "output", "response", "content"): - if hasattr(res, attr): - v = getattr(res, attr) - text = v() if callable(v) else v - break - if not text and hasattr(res, "__str__"): - text = str(res) - self.log("Генерация завершена") - if self.app_state: - try: - is_err = isinstance(text, str) and text.startswith("[ОШИБКА]") - self.app_state.add_interaction("generate", input_text=promt, output_text=text, params=params, ok=not is_err, error=text if is_err else "") - except Exception: - pass - if on_result: - on_result(text) - except Exception as e: - self.log(f"Ошибка генерации: {e}") - err = f"[ОШИБКА] {e}" - if self.app_state: - try: - self.app_state.add_interaction("generate", input_text=promt, output_text=err, params=params, ok=False, error=str(e)) - except Exception: - pass - if on_result: - on_result(err) - - t = threading.Thread(target=_task, daemon=True) - t.start() - def chat(self, messages, params: dict = None, on_result: Optional[Callable[[str], None]] = None): - if self.model is None: - self.log("chat: модель не загружена") - msg = "[ОШИБКА] Модель не загружена. Загрузите модель во вкладке 'Модели'." - prompt = messages if isinstance(messages, str) else str(messages) - if self.app_state: - try: - self.app_state.add_interaction("chat", input_text=prompt, output_text=msg, params=params or {}, ok=False, error=msg) except Exception: pass - if on_result: - on_result(msg) - return - - params = self._normalize_gen_params(params) - n = params.get("n", 256) - temperature = params.get("temperature", 0.7) - top_p = params.get("top_p", 0.9) - top_k = params.get("top_k", 40) - repeat_penalty = params.get("repeat_penalty", 1.0) - - def extract_prompt(msgs): - if isinstance(msgs, str): - return msgs - if isinstance(msgs, list): - for m in reversed(msgs): - if isinstance(m, dict) and m.get("role") == "user": - return m.get("content", "") or "" - parts = [] - for m in msgs: - if isinstance(m, dict): - c = m.get("content", "") - if c: - parts.append(str(c)) - return "\n".join(parts) - return str(msgs) - - def _task(): - prompt = extract_prompt(messages) try: - self.log(f"Chat... n={n}") - res = None + on_result(text) + except Exception: + pass - # Системный промпт (если поддерживается моделью Xenith) - try: - if self.app_state and getattr(self.app_state, "system_prompt", "") and hasattr(self.model, "chat_set_system"): - self.model.chat_set_system(self.app_state.system_prompt) - except Exception: - pass + threading.Thread(target=task, daemon=True).start() - if hasattr(self.model, "chat"): - try: - res = self.model.chat( - prompt, - n=n, - temperature=temperature, - top_k=top_k, - top_p=top_p, - repeat_penalty=repeat_penalty, - ) - except TypeError: - res = self.model.chat(prompt, n=n, temperature=temperature) - else: - # generate() сам залогирует взаимодействие - self.generate(prompt, params, on_result) - return + def chat(self, messages, params: dict = None, on_result=None, on_token=None): + ad = self.active() + if ad is None: + if on_result: + on_result("[ОШИБКА] Движок не выбран") + return + p = normalize_params(params) + msgs = self._prepare_messages(messages, ad) + log_prompt = "" + for m in reversed(msgs): + if m.get("role") == "user": + log_prompt = m.get("content", "") + break - text = "" - if isinstance(res, str): - text = res - elif res is not None: - for attr in ("text", "output", "response", "content", "message", "answer"): - if hasattr(res, attr): - v = getattr(res, attr) - if callable(v): - try: - v = v() - except Exception: - pass - if isinstance(v, dict) and "content" in v: - text = v["content"] - break - text = "" if v is None else v - break - if not isinstance(text, str): - text = str(text) + def fn(): + return ad.chat(msgs, p, on_token=on_token) - self.log("Chat завершён") - if self.app_state: - try: - is_err = isinstance(text, str) and text.startswith("[ОШИБКА]") - self.app_state.add_interaction("chat", input_text=prompt, output_text=text, params=params, ok=not is_err, error=text if is_err else "") - except Exception: - pass - if on_result: - on_result(text) - except Exception as e: - msg = str(e) - # Некоторые импортированные GGUF-модели не имеют Xenith chat-маркеров. - # В этом случае chat()/finetune() недоступны, но generate() может работать. - low = msg.lower() - if ("" in low and "" in low) or ("chat" in low and "недоступ" in low) or ("fine-tune" in low and "недоступ" in low): - try: - fallback_prompt = f"User: {prompt}\nAssistant:" - self.log(f"chat() недоступен для этой модели, fallback на generate(). Причина: {msg}") - # generate() сам залогирует взаимодействие - self.generate(fallback_prompt, params, on_result) - return - except Exception: - pass - self.log(f"ошибка chat: {e}") - err = f"[ОШИБКА] {e}" - if self.app_state: - try: - self.app_state.add_interaction("chat", input_text=prompt, output_text=err, params=params, ok=False, error=str(e)) - except Exception: - pass - if on_result: - on_result(err) + self._run_async("chat", fn, on_result, log_prompt, p, on_token) - t = threading.Thread(target=_task, daemon=True) - t.start() + def generate(self, prompt: str, params: dict = None, on_result=None, on_token=None): + ad = self.active() + if ad is None: + if on_result: + on_result("[ОШИБКА] Движок не выбран") + return + p = normalize_params(params) + + def fn(): + return ad.generate(str(prompt), p, on_token=on_token) + + self._run_async("generate", fn, on_result, str(prompt), p, on_token) + + def generate_sync(self, prompt: str, params: dict = None) -> str: + ad = self.active() + if ad is None: + raise EngineError("Движок не выбран") + with self._lock: + if self._busy or self._training: + raise EngineError("Движок занят другой операцией") + self._busy = True + try: + p = normalize_params(params) + return ad.generate(str(prompt), p) + finally: + with self._lock: + self._busy = False + + def chat_sync(self, messages, params: dict = None, on_token=None) -> str: + """Синхронный чат для HTTP API/сервера. Сериализует доступ к движку.""" + ad = self.active() + if ad is None: + raise EngineError("Движок не выбран") + with self._lock: + if self._busy or self._training: + raise EngineError("Движок занят другой операцией") + self._busy = True + try: + p = normalize_params(params) + msgs = self._prepare_messages(messages, ad) + return ad.chat(msgs, p, on_token=on_token) + finally: + with self._lock: + self._busy = False + + def stop(self): + ad = self.active() + if ad is not None: + try: + ad.stop() + except Exception: + pass + + def reset_chat(self): + ad = self.active() + if ad is not None: + try: + ad.reset_chat() + except Exception: + pass + + def set_system_prompt(self, prompt: str): + ad = self.active() + if ad is not None: + try: + ad.set_system_prompt(prompt or "") + except Exception: + pass + + def context_info(self): + ad = self.active() + if ad is None: + return None, None, True + try: + return ad.context_info() + except Exception: + return None, None, True diff --git a/XUI/core/engines/__init__.py b/XUI/core/engines/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/XUI/core/engines/base.py b/XUI/core/engines/base.py new file mode 100644 index 0000000..f2bcdc4 --- /dev/null +++ b/XUI/core/engines/base.py @@ -0,0 +1,143 @@ +"""Базовые типы движков Xenith Studio.""" + +from dataclasses import dataclass, field +from typing import Callable, Dict, List, Optional + + +class EngineError(Exception): + """Ошибка движка, пригодная для показа пользователю.""" + + +@dataclass +class Capabilities: + chat: bool = True + stream: bool = False + train: bool = False + finetune: bool = False + tools: bool = False + manage_models: bool = False + context_info: bool = False + + +@dataclass +class ModelInfo: + engine_id: str + id: str + name: str + path: str = "" + size: int = 0 + kind: str = "" + loaded: bool = False + meta: Dict = field(default_factory=dict) + + def label(self) -> str: + return self.name or self.id + + +def normalize_params(params: Optional[dict]) -> dict: + p = dict(params or {}) + n = p.get("n", p.get("max_new_tokens", p.get("max_tokens", 256))) + try: + n = int(n) + except Exception: + n = 256 + p["n"] = max(1, min(n, 8192)) + for key in ("temperature", "top_p"): + try: + p[key] = float(p.get(key, 0.7 if key == "temperature" else 0.9)) + except Exception: + p[key] = 0.7 if key == "temperature" else 0.9 + try: + p["top_k"] = int(p.get("top_k", 40)) + except Exception: + p["top_k"] = 40 + try: + p["repeat_penalty"] = float(p.get("repeat_penalty", 1.0)) + except Exception: + p["repeat_penalty"] = 1.0 + return p + + +def normalize_messages(messages) -> List[dict]: + if isinstance(messages, str): + return [{"role": "user", "content": messages}] + out = [] + if isinstance(messages, list): + for m in messages: + if isinstance(m, dict): + role = str(m.get("role", "user")) + content = m.get("content", "") + if isinstance(content, list): + parts = [] + for part in content: + if isinstance(part, dict) and part.get("type") == "text": + parts.append(str(part.get("text", ""))) + elif isinstance(part, str): + parts.append(part) + content = "\n".join(parts) + out.append({"role": role, "content": "" if content is None else str(content)}) + elif isinstance(m, str): + out.append({"role": "user", "content": m}) + return out or [{"role": "user", "content": ""}] + + +class EngineAdapter: + type = "base" + + def __init__(self, engine_id: str, conf: dict, app_state=None): + self.id = engine_id + self.conf = dict(conf or {}) + self.app_state = app_state + self.model_id: str = str(self.conf.get("model") or "") + self._stop = False + + # ---------- идентификация ---------- + @property + def name(self) -> str: + return str(self.conf.get("name") or self.type) + + def capabilities(self) -> Capabilities: + return Capabilities() + + def version(self) -> str: + return "" + + def describe(self) -> str: + return self.name + + # ---------- health/models ---------- + def health(self) -> tuple: + return True, "OK" + + def list_models(self) -> List[ModelInfo]: + return [] + + def load_model(self, model_id: str) -> None: + self.model_id = str(model_id) + + def unload_model(self) -> None: + self.model_id = "" + + # ---------- inference ---------- + def chat(self, messages, params: dict, on_token: Optional[Callable[[str], None]] = None) -> str: + raise EngineError(f"Движок {self.name} не поддерживает чат") + + def generate(self, prompt: str, params: dict, on_token: Optional[Callable[[str], None]] = None) -> str: + raise EngineError(f"Движок {self.name} не поддерживает генерацию") + + def reset_chat(self) -> None: + pass + + def set_system_prompt(self, text: str) -> None: + pass + + def context_info(self): + """(used, limit, estimated) или (None, None, True).""" + return None, None, True + + # ---------- управление ---------- + def stop(self) -> None: + self._stop = True + + def close(self) -> None: + pass diff --git a/XUI/core/engines/native.py b/XUI/core/engines/native.py new file mode 100644 index 0000000..65f5c7b --- /dev/null +++ b/XUI/core/engines/native.py @@ -0,0 +1,261 @@ +"""Адаптер встроенного движка Xenith (.xnh).""" + +import os +from typing import Callable, List, Optional + +from .base import Capabilities, EngineError, ModelInfo, normalize_params + +try: + import xenith_engine as xe +except Exception: + xe = None + + +class XenithAdapter: + type = "xenith" + + def __init__(self, engine_id: str, conf: dict, app_state=None): + self.id = engine_id + self.conf = dict(conf or {}) + self.app_state = app_state + self._model = None + self.model_id = str(self.conf.get("model") or "") + self._stop = False + + @property + def name(self) -> str: + return str(self.conf.get("name") or "Xenith") + + @property + def model(self): + return self._model + + def capabilities(self) -> Capabilities: + return Capabilities(chat=True, stream=True, train=True, finetune=True, + tools=False, manage_models=True, context_info=True) + + def version(self) -> str: + try: + if xe is not None: + v = str(xe.version()) + b = str(xe.build_type()) if hasattr(xe, "build_type") else "" + return f"{v} · {b}" if b else v + except Exception: + pass + return "" + + def describe(self) -> str: + v = self.version() + return f"Xenith {v}" if v else "Xenith" + + def health(self) -> tuple: + return (xe is not None), ("OK" if xe is not None else "xenith_engine не найден") + + def _model_dirs(self) -> List[str]: + dirs = [] + try: + import xenith + base = os.path.dirname(os.path.abspath(xenith.__file__)) + dirs.append(os.path.join(base, "models")) + except Exception: + pass + dirs.append(os.path.join(os.getcwd(), "models")) + for p in (getattr(self.app_state, "extra_model_paths", None) or []): + if os.path.isdir(p): + dirs.append(p) + for p in (self.conf.get("model_dirs") or []): + if os.path.isdir(p): + dirs.append(p) + return dirs + + def list_models(self) -> List[ModelInfo]: + out = [] + seen = set() + for d in self._model_dirs(): + try: + names = sorted(os.listdir(d)) + except Exception: + continue + for name in names: + full = os.path.join(d, name) + if not os.path.isfile(full): + continue + ap = os.path.abspath(full) + if ap in seen: + continue + seen.add(ap) + ext = os.path.splitext(name)[1].lower().lstrip(".") or "file" + try: + size = os.path.getsize(ap) + except Exception: + size = 0 + loaded = bool(self._model is not None and getattr(self._model, "path", None) == ap) + out.append(ModelInfo(engine_id=self.id, id=ap, name=name, path=ap, + size=size, kind=ext, loaded=loaded)) + # Явно добавленные файлы из AppState (могут быть вне папок). + for ap in (getattr(self.app_state, "extra_model_paths", None) or []): + if os.path.isfile(ap): + ap = os.path.abspath(ap) + if ap in seen: + continue + seen.add(ap) + try: + size = os.path.getsize(ap) + except Exception: + size = 0 + out.append(ModelInfo(engine_id=self.id, id=ap, name=os.path.basename(ap), + path=ap, size=size, + kind=os.path.splitext(ap)[1].lstrip(".") or "file", + loaded=False)) + return out + + def load_model(self, model_id: str) -> None: + if xe is None: + raise EngineError("xenith_engine не найден") + path = str(model_id) + if not os.path.isfile(path): + raise EngineError(f"Файл модели не найден: {path}") + try: + model = xe.Model(path) + except TypeError: + model = xe.Model() + model.load(path) + self._model = model + self.model_id = path + self._stop = False + + def unload_model(self) -> None: + self._model = None + self.model_id = "" + + def _apply_system(self): + try: + if self._model is not None and self.app_state is not None: + text = getattr(self.app_state, "system_prompt", "") or "" + if text and hasattr(self._model, "chat_set_system"): + self._model.chat_set_system(text) + except Exception: + pass + + def chat(self, messages, params: dict, on_token: Optional[Callable[[str], None]] = None) -> str: + if self._model is None: + raise EngineError("Модель не загружена") + self._stop = False + p = normalize_params(params) + self._apply_system() + + # Для нативного чата отправляем последнее сообщение пользователя: + # история хранится внутри модели между вызовами. + prompt = "" + if isinstance(messages, list): + for m in reversed(messages): + if isinstance(m, dict) and m.get("role") == "user": + prompt = str(m.get("content", "") or "") + break + if not prompt and messages and isinstance(messages[-1], dict): + prompt = str(messages[-1].get("content", "") or "") + else: + prompt = str(messages) + + def token_cb(tid, piece): + if self._stop: + return + if on_token and piece: + on_token(str(piece)) + + try: + if hasattr(self._model, "chat"): + res = self._model.chat( + prompt, + n=p["n"], + temperature=p["temperature"], + top_k=p["top_k"], + top_p=p["top_p"], + repeat_penalty=p["repeat_penalty"], + on_token=token_cb, + ) + else: + res = self._model.generate(prompt, n=p["n"], temperature=p["temperature"], + top_p=p["top_p"], on_token=token_cb) + except TypeError: + # Старые сборки/модели без on_token. + res = self._model.chat(prompt, n=p["n"], temperature=p["temperature"]) + except Exception as e: + msg = str(e) + low = msg.lower() + if ("" in low and "" in low) or ("chat" in low and "недоступ" in low): + fallback = f"User: {prompt}\nAssistant:" + return self.generate(fallback, p, on_token) + raise EngineError(msg) + + text = getattr(res, "text", res) + return "" if text is None else str(text) + + def generate(self, prompt: str, params: dict, on_token: Optional[Callable[[str], None]] = None) -> str: + if self._model is None: + raise EngineError("Модель не загружена") + self._stop = False + p = normalize_params(params) + + def token_cb(tid, piece): + if self._stop: + return + if on_token and piece: + on_token(str(piece)) + + try: + res = self._model.generate( + prompt, + n=p["n"], + temperature=p["temperature"], + top_k=p["top_k"], + top_p=p["top_p"], + repeat_penalty=p["repeat_penalty"], + on_token=token_cb, + ) + except TypeError: + res = self._model.generate(prompt, n=p["n"], temperature=p["temperature"], top_p=p["top_p"]) + except Exception as e: + raise EngineError(str(e)) + text = getattr(res, "text", res) + return "" if text is None else str(text) + + def reset_chat(self) -> None: + try: + if self._model is not None and hasattr(self._model, "chat_reset"): + self._model.chat_reset() + except Exception: + pass + + def set_system_prompt(self, text: str) -> None: + try: + if self._model is not None and hasattr(self._model, "chat_set_system"): + self._model.chat_set_system(text or "") + except Exception: + pass + + def context_info(self): + try: + if self._model is not None and hasattr(self._model, "chat_history"): + h = self._model.chat_history() + if isinstance(h, dict): + used = h.get("context_used") + limit = h.get("context_max") or h.get("context_size") or h.get("ctx") + if used is not None: + return int(used), (int(limit) if limit else None), False + if limit: + return None, int(limit), False + except Exception: + pass + return None, None, True + + def stop(self) -> None: + self._stop = True + try: + if self._model is not None and hasattr(self._model, "stop"): + self._model.stop() + except Exception: + pass + + def close(self) -> None: + pass diff --git a/XUI/core/engines/ollama.py b/XUI/core/engines/ollama.py new file mode 100644 index 0000000..5ffa18d --- /dev/null +++ b/XUI/core/engines/ollama.py @@ -0,0 +1,210 @@ +"""Ollama API: локальные модели, стриминг, инструменты.""" + +import json +import urllib.error +import urllib.request +from typing import Callable, List, Optional + +from .base import Capabilities, EngineError, ModelInfo, normalize_params + + +class OllamaAdapter: + type = "ollama" + + def __init__(self, engine_id: str, conf: dict, app_state=None): + self.id = engine_id + self.conf = dict(conf or {}) + self.app_state = app_state + self.model_id = str(self.conf.get("model") or "") + self._system = "" + self._stop = False + self._resp = None + self._ctx_cache = {} + + @property + def name(self) -> str: + return str(self.conf.get("name") or "Ollama") + + def capabilities(self) -> Capabilities: + return Capabilities(chat=True, stream=True, train=False, finetune=False, + tools=True, manage_models=True, context_info=True) + + def describe(self) -> str: + return self.name + + def _base(self) -> str: + base = str(self.conf.get("base_url") or "http://127.0.0.1:11434").strip().rstrip("/") + return base + + def _headers(self) -> dict: + h = {"Content-Type": "application/json"} + key = str(self.conf.get("api_key") or "").strip() + if key: + h["Authorization"] = f"Bearer {key}" + return h + + def _open(self, path: str, body=None, timeout=300): + url = self._base() + path + data = None + method = "GET" + if body is not None: + data = json.dumps(body, ensure_ascii=False).encode("utf-8") + method = "POST" + req = urllib.request.Request(url, data=data, headers=self._headers(), method=method) + try: + return urllib.request.urlopen(req, timeout=timeout) + except urllib.error.HTTPError as e: + detail = "" + try: + detail = e.read().decode("utf-8", "replace")[:400] + except Exception: + pass + raise EngineError(f"HTTP {e.code}: {detail or e.reason}") + except urllib.error.URLError as e: + raise EngineError(f"Ollama недоступен ({url}): {e.reason}") + except Exception as e: + raise EngineError(str(e)) + + def health(self) -> tuple: + try: + models = self.list_models() + return True, f"OK · моделей: {len(models)}" + except Exception as e: + return False, str(e) + + def list_models(self) -> List[ModelInfo]: + resp = self._open("/api/tags", timeout=6) + data = json.loads(resp.read().decode("utf-8", "replace") or "{}") + items = data.get("models") if isinstance(data, dict) else None + if not isinstance(items, list): + raise EngineError("Ответ Ollama /api/tags не распознан") + out = [] + for it in items: + if not isinstance(it, dict): + continue + mid = str(it.get("model") or it.get("name") or "") + if not mid: + continue + size = int(it.get("size") or 0) + out.append(ModelInfo(engine_id=self.id, id=mid, name=mid, kind="ollama", + size=size, loaded=(mid == self.model_id), + meta={"details": it.get("details") or {}})) + return out + + def load_model(self, model_id: str) -> None: + self.model_id = str(model_id) + self.conf["model"] = self.model_id + + def unload_model(self) -> None: + mid = self.model_id + if mid: + try: + self._open("/api/generate", {"model": mid, "keep_alive": 0}, timeout=10) + except Exception: + pass + self.model_id = "" + self.conf["model"] = "" + + def _context_limit(self) -> Optional[int]: + if not self.model_id: + return None + if self.model_id in self._ctx_cache: + return self._ctx_cache[self.model_id] + limit = None + try: + resp = self._open("/api/show", {"model": self.model_id}, timeout=8) + data = json.loads(resp.read().decode("utf-8", "replace") or "{}") + info = data.get("model_info") if isinstance(data, dict) else None + if isinstance(info, dict): + for k, v in info.items(): + if k.endswith(".context_length") and v: + limit = int(v) + break + except Exception: + pass + self._ctx_cache[self.model_id] = limit + return limit + + def chat(self, messages, params: dict, on_token: Optional[Callable[[str], None]] = None) -> str: + if not self.model_id: + raise EngineError("Модель Ollama не выбрана") + p = normalize_params(params) + msgs = [] + if self._system: + msgs.append({"role": "system", "content": self._system}) + for m in (messages or []): + if isinstance(m, dict): + role = m.get("role", "user") + if role == "system" and self._system: + continue + msgs.append({"role": role, "content": m.get("content", "")}) + body = { + "model": self.model_id, + "messages": msgs, + "stream": on_token is not None, + "options": { + "temperature": p["temperature"], + "top_p": p["top_p"], + "num_predict": p["n"], + "repeat_penalty": p["repeat_penalty"], + }, + } + keep = self.conf.get("keep_alive") + if keep: + body["keep_alive"] = keep + self._stop = False + resp = self._open("/api/chat", body=body, timeout=300) + self._resp = resp + try: + if on_token is not None: + parts = [] + for raw in resp: + if self._stop: + break + line = raw.decode("utf-8", "replace").strip() + if not line: + continue + try: + data = json.loads(line) + except Exception: + continue + msg = data.get("message") or {} + piece = msg.get("content") + if piece: + parts.append(str(piece)) + try: + on_token(str(piece)) + except Exception: + pass + if data.get("done"): + break + return "".join(parts) + data = json.loads(resp.read().decode("utf-8", "replace") or "{}") + msg = data.get("message") or {} + return str(msg.get("content") or "") + finally: + self._resp = None + try: + resp.close() + except Exception: + pass + + def generate(self, prompt: str, params: dict, on_token: Optional[Callable[[str], None]] = None) -> str: + return self.chat([{"role": "user", "content": str(prompt)}], params, on_token=on_token) + + def set_system_prompt(self, text: str) -> None: + self._system = text or "" + + def reset_chat(self) -> None: + pass + + def context_info(self): + return None, self._context_limit(), True + + def stop(self) -> None: + self._stop = True + try: + if self._resp is not None: + self._resp.close() + except Exception: + pass diff --git a/XUI/core/engines/openai_compat.py b/XUI/core/engines/openai_compat.py new file mode 100644 index 0000000..5978234 --- /dev/null +++ b/XUI/core/engines/openai_compat.py @@ -0,0 +1,201 @@ +"""OpenAI-совместимый движок: LM Studio, llama.cpp server, vLLM, OpenRouter, OpenAI.""" + +import json +import urllib.error +import urllib.request +from typing import Callable, List, Optional + +from .base import Capabilities, EngineError, ModelInfo, normalize_params + + +class OpenAICompatAdapter: + type = "openai" + + def __init__(self, engine_id: str, conf: dict, app_state=None): + self.id = engine_id + self.conf = dict(conf or {}) + self.app_state = app_state + self.model_id = str(self.conf.get("model") or "") + self._system = "" + self._stop = False + self._resp = None + + @property + def name(self) -> str: + return str(self.conf.get("name") or "OpenAI-совместимый") + + def capabilities(self) -> Capabilities: + return Capabilities(chat=True, stream=True, train=False, finetune=False, + tools=True, manage_models=False, context_info=False) + + def describe(self) -> str: + return self.name + + def _base(self) -> str: + base = str(self.conf.get("base_url") or "").strip().rstrip("/") + if not base: + raise EngineError("Не задан base_url") + if not base.endswith("/v1"): + base += "/v1" + return base + + def _headers(self) -> dict: + h = {"Content-Type": "application/json", "Accept": "application/json"} + key = str(self.conf.get("api_key") or "").strip() + if key: + h["Authorization"] = f"Bearer {key}" + extra = self.conf.get("headers") + if isinstance(extra, dict): + for k, v in extra.items(): + h[str(k)] = str(v) + return h + + def _open(self, path: str, body=None, timeout=120, stream=False): + url = self._base() + path + data = None + method = "GET" + if body is not None: + data = json.dumps(body, ensure_ascii=False).encode("utf-8") + method = "POST" + req = urllib.request.Request(url, data=data, headers=self._headers(), method=method) + try: + return urllib.request.urlopen(req, timeout=timeout) + except urllib.error.HTTPError as e: + detail = "" + try: + detail = e.read().decode("utf-8", "replace")[:400] + except Exception: + pass + raise EngineError(f"HTTP {e.code}: {detail or e.reason}") + except urllib.error.URLError as e: + raise EngineError(f"Нет соединения с {url}: {e.reason}") + except Exception as e: + raise EngineError(str(e)) + + def health(self) -> tuple: + try: + models = self.list_models() + return True, f"OK · моделей: {len(models)}" + except Exception as e: + return False, str(e) + + def list_models(self) -> List[ModelInfo]: + try: + resp = self._open("/models", timeout=6) + data = json.loads(resp.read().decode("utf-8", "replace") or "{}") + except Exception as e: + if isinstance(e, EngineError): + raise + raise EngineError(str(e)) + items = data.get("data") if isinstance(data, dict) else None + if not isinstance(items, list): + raise EngineError("Ответ /models не похож на OpenAI API") + out = [] + for it in items: + if not isinstance(it, dict): + continue + mid = str(it.get("id") or "") + if not mid: + continue + out.append(ModelInfo(engine_id=self.id, id=mid, name=mid, kind="http", + loaded=(mid == self.model_id))) + return out + + def load_model(self, model_id: str) -> None: + self.model_id = str(model_id) + self.conf["model"] = self.model_id + + def unload_model(self) -> None: + self.model_id = "" + self.conf["model"] = "" + + def chat(self, messages, params: dict, on_token: Optional[Callable[[str], None]] = None) -> str: + if not self.model_id: + raise EngineError("Модель не выбрана") + p = normalize_params(params) + msgs = [] + if self._system: + msgs.append({"role": "system", "content": self._system}) + for m in (messages or []): + if isinstance(m, dict): + role = m.get("role", "user") + if role == "system" and self._system: + continue + msgs.append({"role": role, "content": m.get("content", "")}) + stream = on_token is not None + body = { + "model": self.model_id, + "messages": msgs, + "temperature": p["temperature"], + "top_p": p["top_p"], + "max_tokens": p["n"], + "stream": stream, + } + self._stop = False + resp = self._open("/chat/completions", body=body, timeout=300) + self._resp = resp + try: + if stream: + return self._read_stream(resp, on_token) + raw = resp.read().decode("utf-8", "replace") + data = json.loads(raw or "{}") + choices = data.get("choices") or [] + if choices and isinstance(choices[0], dict): + msg = choices[0].get("message") or {} + return str(msg.get("content") or "") + raise EngineError("Пустой ответ движка") + finally: + self._resp = None + try: + resp.close() + except Exception: + pass + + def _read_stream(self, resp, on_token) -> str: + parts = [] + for raw in resp: + if self._stop: + break + line = raw.decode("utf-8", "replace").strip() + if not line: + continue + if line.startswith("data:"): + line = line[5:].strip() + if line == "[DONE]": + break + try: + data = json.loads(line) + except Exception: + continue + choices = data.get("choices") or [] + if not choices: + continue + delta = choices[0].get("delta") or {} + piece = delta.get("content") + if piece: + parts.append(str(piece)) + try: + on_token(str(piece)) + except Exception: + pass + return "".join(parts) + + def generate(self, prompt: str, params: dict, on_token: Optional[Callable[[str], None]] = None) -> str: + return self.chat([{"role": "user", "content": str(prompt)}], params, on_token=on_token) + + def set_system_prompt(self, text: str) -> None: + self._system = text or "" + + def reset_chat(self) -> None: + pass + + def context_info(self): + return None, None, True + + def stop(self) -> None: + self._stop = True + try: + if self._resp is not None: + self._resp.close() + except Exception: + pass diff --git a/XUI/core/mcp/__init__.py b/XUI/core/mcp/__init__.py new file mode 100644 index 0000000..4c81c83 --- /dev/null +++ b/XUI/core/mcp/__init__.py @@ -0,0 +1,18 @@ +"""Встроенный MCP: сервер файловой системы и минимальный stdio-клиент. + +Пакет не зависит от остального XUI и использует только стандартную библиотеку. +""" + +from .client import ( + MCPError, + MCPStdioClient, + MCPTimeoutError, + start_fs_server, +) + +__all__ = [ + "MCPError", + "MCPStdioClient", + "MCPTimeoutError", + "start_fs_server", +] diff --git a/XUI/core/mcp/client.py b/XUI/core/mcp/client.py new file mode 100644 index 0000000..1daa6c0 --- /dev/null +++ b/XUI/core/mcp/client.py @@ -0,0 +1,468 @@ +"""Минимальный MCP-клиент поверх stdio. + +Клиент запускает внешний процесс, обменивается с ним построчными +JSON-RPC 2.0 сообщениями, маршрутизирует ответы по id из отдельного +потока-читателя и поддерживает таймауты запросов. + +Пример: + from XUI.core.mcp.client import start_fs_server + + client = start_fs_server(["/tmp/project"]) + client.start() + tools = client.list_tools() + result = client.call_tool("read_file", {"path": "README.md"}) + client.stop() +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +import threading +from collections import deque +from dataclasses import dataclass, field +from typing import Any, Callable + +PROTOCOL_VERSION = "2025-06-18" +CLIENT_NAME = "xenith-mcp-client" +CLIENT_VERSION = "1.0" + + +class MCPError(RuntimeError): + """Ошибка MCP-протокола или транспорта.""" + + def __init__(self, message: str, *, code: int | None = None, data: Any = None): + super().__init__(message) + self.code = code + self.data = data + + +class MCPTimeoutError(MCPError, TimeoutError): + """Истёк таймаут ожидания ответа.""" + + +@dataclass +class _Pending: + method: str + event: threading.Event = field(default_factory=threading.Event) + result: Any = None + error: dict[str, Any] | None = None + + +NotificationCallback = Callable[[dict[str, Any]], None] +StderrCallback = Callable[[str], None] + + +class MCPStdioClient: + """Потокобезопасный клиент для MCP-сервера, работающего через stdio.""" + + def __init__( + self, + command: list[str], + env: dict[str, str] | None = None, + cwd: str | None = None, + on_notification: NotificationCallback | None = None, + on_stderr: StderrCallback | None = None, + ): + if not command or not all(isinstance(part, str) for part in command): + raise ValueError("command must be a non-empty list of strings") + + self.command = list(command) + self.env = dict(env) if env is not None else None + self.cwd = cwd + self.on_notification = on_notification + self.on_stderr = on_stderr + + self._proc: subprocess.Popen[str] | None = None + self._next_id = 0 + self._pending: dict[int, _Pending] = {} + self._lock = threading.RLock() + self._write_lock = threading.Lock() + + self._reader: threading.Thread | None = None + self._stderr_thread: threading.Thread | None = None + self._stderr_lines: deque[str] = deque(maxlen=1000) + self._notifications: deque[dict[str, Any]] = deque(maxlen=100) + + self._init_result: dict[str, Any] | None = None + + # ---- Управление процессом -------------------------------------------- + + @property + def is_running(self) -> bool: + with self._lock: + proc = self._proc + return proc is not None and proc.poll() is None + + @property + def initialize_result(self) -> dict[str, Any] | None: + return self._init_result + + @property + def notifications(self) -> list[dict[str, Any]]: + with self._lock: + return list(self._notifications) + + def stderr_text(self) -> str: + with self._lock: + return "".join(self._stderr_lines) + + def start(self) -> dict[str, Any]: + """Запускает процесс, выполняет initialize и шлёт notifications/initialized.""" + with self._lock: + if self._proc is not None: + raise MCPError("client is already started") + + full_env = os.environ.copy() + if self.env: + full_env.update({str(key): str(value) for key, value in self.env.items()}) + + try: + proc = subprocess.Popen( + self.command, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + encoding="utf-8", + errors="replace", + bufsize=1, + cwd=self.cwd, + env=full_env, + ) + except (OSError, ValueError) as exc: + raise MCPError(f"failed to start MCP server: {exc}") from exc + + with self._lock: + self._proc = proc + self._reader = threading.Thread( + target=self._reader_loop, + args=(proc,), + name="mcp-stdio-reader", + daemon=True, + ) + self._stderr_thread = threading.Thread( + target=self._stderr_loop, + args=(proc,), + name="mcp-stdio-stderr", + daemon=True, + ) + reader = self._reader + stderr_thread = self._stderr_thread + + reader.start() + stderr_thread.start() + + try: + init = self._request( + "initialize", + { + "protocolVersion": PROTOCOL_VERSION, + "capabilities": {}, + "clientInfo": {"name": CLIENT_NAME, "version": CLIENT_VERSION}, + }, + timeout=15.0, + ) + if not isinstance(init, dict): + raise MCPError("invalid initialize response: expected an object") + if not isinstance(init.get("protocolVersion"), str): + raise MCPError("invalid initialize response: missing protocolVersion") + self._init_result = init + self._send({"jsonrpc": "2.0", "method": "notifications/initialized"}) + return init + except BaseException: + self.stop() + raise + + def stop(self) -> None: + """Завершает процесс и джойнит фоновые потоки. Идемпотентно.""" + with self._lock: + proc = self._proc + if proc is None: + self._join_threads() + return + + self._fail_pending(-32000, "client stopped") + + try: + if proc.stdin is not None and not proc.stdin.closed: + proc.stdin.close() + except (OSError, ValueError): + pass + + if proc.poll() is None: + try: + proc.terminate() + proc.wait(timeout=5.0) + except subprocess.TimeoutExpired: + try: + proc.kill() + except OSError: + pass + try: + proc.wait(timeout=5.0) + except subprocess.TimeoutExpired: + pass + except OSError: + pass + + with self._lock: + if self._proc is proc: + self._proc = None + self._join_threads() + + def _join_threads(self) -> None: + current = threading.current_thread() + with self._lock: + threads = [self._reader, self._stderr_thread] + for thread in threads: + if thread is None or thread is current: + continue + if thread.is_alive(): + thread.join(timeout=5.0) + + def __enter__(self) -> "MCPStdioClient": + self.start() + return self + + def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None: + self.stop() + + # ---- Публичные запросы ------------------------------------------------ + + def list_tools(self) -> list[dict[str, Any]]: + """Возвращает все инструменты, при необходимости обходя nextCursor.""" + tools: list[dict[str, Any]] = [] + cursor: str | None = None + for _ in range(50): + params = {"cursor": cursor} if cursor else {} + result = self._request("tools/list", params, timeout=30.0) + if not isinstance(result, dict): + raise MCPError("invalid tools/list response") + page = result.get("tools") or [] + if not isinstance(page, list): + raise MCPError("invalid tools/list response: tools is not a list") + tools.extend(item for item in page if isinstance(item, dict)) + cursor = result.get("nextCursor") + if not cursor: + break + return tools + + def call_tool( + self, + name: str, + arguments: dict[str, Any] | None = None, + timeout: float = 30.0, + ) -> dict[str, Any]: + """Вызывает инструмент и возвращает сырой MCP-результат.""" + if not isinstance(name, str) or not name: + raise ValueError("tool name must be a non-empty string") + if arguments is None: + arguments = {} + if not isinstance(arguments, dict): + raise TypeError("arguments must be a dictionary") + + result = self._request( + "tools/call", + {"name": name, "arguments": arguments}, + timeout=timeout, + ) + if not isinstance(result, dict): + raise MCPError("invalid tools/call response: expected an object") + return result + + def ping(self, timeout: float = 10.0) -> dict[str, Any]: + result = self._request("ping", {}, timeout=timeout) + return result if isinstance(result, dict) else {} + + # ---- Транспорт -------------------------------------------------------- + + def _request(self, method: str, params: dict[str, Any] | None = None, + timeout: float = 30.0) -> Any: + if timeout <= 0: + raise ValueError("timeout must be greater than zero") + + with self._lock: + if self._proc is None: + raise MCPError("client is not started") + self._next_id += 1 + request_id = self._next_id + pending = _Pending(method=method) + self._pending[request_id] = pending + + message: dict[str, Any] = { + "jsonrpc": "2.0", + "id": request_id, + "method": method, + } + if params is not None: + message["params"] = params + + try: + self._send(message) + except BaseException: + with self._lock: + self._pending.pop(request_id, None) + raise + + if not pending.event.wait(timeout): + with self._lock: + self._pending.pop(request_id, None) + raise MCPTimeoutError( + f"timeout after {timeout:g}s while waiting for {method}" + ) + + if pending.error is not None: + error = pending.error + code = error.get("code") + message_text = error.get("message", "unknown MCP error") + raise MCPError( + f"{method}: {message_text} (code {code})", + code=code if isinstance(code, int) else None, + data=error.get("data"), + ) + + return pending.result + + def _send(self, message: dict[str, Any]) -> None: + with self._lock: + proc = self._proc + if proc is None or proc.stdin is None: + raise MCPError("client is not started") + + payload = json.dumps(message, ensure_ascii=False, separators=(",", ":")) + "\n" + with self._write_lock: + try: + proc.stdin.write(payload) + proc.stdin.flush() + except (BrokenPipeError, OSError, ValueError) as exc: + exit_code = proc.poll() + tail = self.stderr_text().strip().splitlines()[-5:] + detail = (" | ".join(tail)) if tail else "no stderr output" + raise MCPError( + f"failed to send {message.get('method')}: " + f"process exited (code {exit_code}); {detail}" + ) from exc + + # ---- Фоновые потоки --------------------------------------------------- + + def _reader_loop(self, proc: subprocess.Popen[str]) -> None: + stream = proc.stdout + try: + if stream is None: + return + while True: + line = stream.readline() + if line == "": + break + line = line.strip() + if not line: + continue + try: + message = json.loads(line) + except json.JSONDecodeError: + self._record_stderr(f"invalid JSON from server: {line[:500]}") + continue + if not isinstance(message, dict): + self._record_stderr("server sent a non-object JSON message") + continue + + if "id" in message and ("result" in message or "error" in message): + request_id = message.get("id") + if not isinstance(request_id, int): + # Наш клиент всегда использует целые id. + self._record_stderr(f"response with unsupported id: {request_id!r}") + continue + with self._lock: + pending = self._pending.pop(request_id, None) + if pending is None: + self._record_stderr(f"response for unknown request id={request_id}") + continue + pending.result = message.get("result") + error = message.get("error") + pending.error = error if isinstance(error, dict) else None + pending.event.set() + continue + + method = message.get("method") + if isinstance(method, str): + with self._lock: + self._notifications.append(message) + callback = self.on_notification + if callback is not None: + try: + callback(message) + except Exception as exc: # noqa: BLE001 + self._record_stderr( + f"notification callback error for {method}: {exc}" + ) + continue + + self._record_stderr(f"unknown server message: {line[:500]}") + finally: + exit_code = proc.poll() + self._fail_pending( + -32000, + f"MCP server closed the connection (exit code {exit_code})", + ) + + def _stderr_loop(self, proc: subprocess.Popen[str]) -> None: + stream = proc.stderr + if stream is None: + return + try: + for line in stream: + self._record_stderr(line.rstrip("\n")) + except (OSError, ValueError): + pass + + def _record_stderr(self, line: str) -> None: + with self._lock: + self._stderr_lines.append(line + "\n") + callback = self.on_stderr + if callback is not None: + try: + callback(line) + except Exception: + pass + + def _fail_pending(self, code: int, message: str) -> None: + with self._lock: + pending_items = list(self._pending.values()) + self._pending.clear() + for pending in pending_items: + pending.error = {"code": code, "message": message} + pending.event.set() + + +# --------------------------------------------------------------------------- +# Помощник для встроенного fs-сервера +# --------------------------------------------------------------------------- + + +def _project_root() -> str: + """XUI/core/mcp/client.py -> корень проекта (без импорта остального XUI).""" + here = os.path.abspath(__file__) + return os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(here)))) + + +def start_fs_server(roots: list[str]) -> MCPStdioClient: + """Создаёт (но не запускает) клиента для XUI.core.mcp.fs_server.""" + if not roots: + raise ValueError("at least one root directory is required") + + command = [sys.executable, "-m", "XUI.core.mcp.fs_server"] + for root in roots: + command.extend(["--root", os.path.abspath(os.fspath(root))]) + + env = os.environ.copy() + project_root = _project_root() + old_pythonpath = env.get("PYTHONPATH") + if old_pythonpath: + env["PYTHONPATH"] = project_root + os.pathsep + old_pythonpath + else: + env["PYTHONPATH"] = project_root + + return MCPStdioClient(command, env=env) diff --git a/XUI/core/mcp/fs_server.py b/XUI/core/mcp/fs_server.py new file mode 100644 index 0000000..6207178 --- /dev/null +++ b/XUI/core/mcp/fs_server.py @@ -0,0 +1,950 @@ +"""Встроенный MCP-сервер файловой системы. + +Сервер работает поверх stdio и общается с клиентом построчным JSON-RPC 2.0. +stdout занят только протоколом, все логи уходят в stderr. + +Запуск: + python3 -m XUI.core.mcp.fs_server --root /abs/path [--root /another] + +Реализованы инструменты list_dir, stat, read_file, write_file, create_dir, +move, copy, delete и search. Все пути обязаны оставаться внутри разрешённых +корневых каталогов; символические ссылки, ведущие наружу, не раскрываются. +""" + +from __future__ import annotations + +import argparse +import fnmatch +import json +import os +import shutil +import stat +import sys +import tempfile +import time +import traceback +from pathlib import PurePosixPath +from typing import Any, Callable, Iterable + +PROTOCOL_VERSION = "2025-06-18" +SERVER_NAME = "xenith-fs" +SERVER_VERSION = "1.0" + +MAX_FILE_BYTES = 2 * 1024 * 1024 # жёсткий предел чтения/записи — 2 МиБ +DEFAULT_READ_BYTES = 200_000 +DEFAULT_SEARCH_RESULTS = 100 +MAX_SEARCH_RESULTS = 200 + +TRASH_DIR_NAME = ".xenith-trash" + +_MISSING = object() + + +class ToolError(Exception): + """Ожидаемая ошибка выполнения инструмента (отдаётся как isError).""" + + +def log(message: str) -> None: + """Пишем только в stderr: stdout принадлежит JSON-RPC.""" + print(f"[xenith-fs] {message}", file=sys.stderr, flush=True) + + +def _is_within(path: str, root: str) -> bool: + """Проверяет, что path находится внутри root (или совпадает с ним).""" + try: + return os.path.commonpath([path, root]) == root + except ValueError: + # Разные диски / некорректные пути. + return False + + +def _rel(path: str, root: str) -> str: + rel = os.path.relpath(path, root) + return "." if rel == "." else rel + + +class PathGuard: + """Разрешение и проверка путей относительно списка корней.""" + + def __init__(self, roots: Iterable[str]): + resolved: list[str] = [] + for raw in roots: + if not isinstance(raw, str) or not raw.strip(): + raise ValueError("--root требует непустой путь") + root = os.path.realpath(os.path.abspath(os.path.expanduser(raw))) + if not os.path.isdir(root): + raise ValueError(f"корень не является каталогом: {raw}") + if root not in resolved: + resolved.append(root) + if not resolved: + raise ValueError("нужен хотя бы один --root") + self.roots = resolved + + def root_for(self, path: str) -> str | None: + """Находит самый конкретный корень, содержащий path.""" + best: str | None = None + for root in self.roots: + if _is_within(path, root): + if best is None or len(root) > len(best): + best = root + return best + + def _existing_ancestor(self, path: str) -> tuple[str, str, str]: + """Возвращает (существующий предок, его realpath, корень).""" + probe = path + while not os.path.lexists(probe): + parent = os.path.dirname(probe) + if parent == probe: + raise ToolError("cannot resolve path: no existing ancestor") + probe = parent + real = os.path.realpath(probe) + root = self.root_for(real) + if root is None: + raise ToolError("path escapes the allowed roots (outside root; traversal or symlink escape blocked)") + return probe, real, root + + def resolve( + self, + raw: Any, + *, + must_exist: bool = False, + follow_final: bool = True, + ) -> tuple[str, str]: + """Возвращает (безопасный абсолютный путь, содержащий его корень). + + follow_final=False позволяет работать с самой символической ссылкой + (например, удалить её), не раскрывая её цель. + """ + if not isinstance(raw, str): + raise ToolError("path must be a string") + if "\x00" in raw: + raise ToolError("path contains a NUL byte") + + if raw == "": + candidate = self.roots[0] + elif os.path.isabs(raw): + candidate = os.path.abspath(raw) + else: + candidate = os.path.abspath(os.path.join(self.roots[0], raw)) + + if follow_final: + probe, real, _root = self._existing_ancestor(candidate) + if probe == candidate: + resolved = real + else: + rel = os.path.relpath(candidate, probe) + resolved = os.path.normpath(os.path.join(real, rel)) + root = self.root_for(resolved) + if root is None: + raise ToolError("path escapes the allowed roots (outside root; traversal or symlink escape blocked)") + if must_exist and not os.path.lexists(resolved): + raise ToolError(f"path not found: {raw}") + return resolved, root + + # Сам корень не имеет родителя внутри разрешённой области. + if candidate in self.roots: + return candidate, candidate + + # Последний компонент не раскрываем: так безопасно удалять/перемещать + # саму ссылку, не трогая объект, на который она указывает. + parent = os.path.dirname(candidate) + if parent == candidate: + raise ToolError("invalid path") + parent_real, root = self.resolve(parent, must_exist=False, follow_final=True) + resolved = os.path.normpath(os.path.join(parent_real, os.path.basename(candidate))) + root = self.root_for(resolved) + if root is None: + raise ToolError("path escapes the allowed roots (outside root; traversal or symlink escape blocked)") + if must_exist and not os.path.lexists(resolved): + raise ToolError(f"path not found: {raw}") + return resolved, root + + +# --------------------------------------------------------------------------- +# Валидация аргументов tools/call +# --------------------------------------------------------------------------- + + +def _arg_str( + args: dict[str, Any], + name: str, + *, + required: bool = True, + default: str | None = None, +) -> str: + if name not in args: + if required: + raise ToolError(f"missing required argument: {name}") + return default # type: ignore[return-value] + value = args[name] + if not isinstance(value, str): + raise ToolError(f"argument '{name}' must be a string") + return value + + +def _arg_bool(args: dict[str, Any], name: str, default: bool = False) -> bool: + value = args.get(name, default) + if not isinstance(value, bool): + raise ToolError(f"argument '{name}' must be a boolean") + return value + + +def _arg_int( + args: dict[str, Any], + name: str, + default: int, + *, + minimum: int | None = None, + maximum: int | None = None, +) -> int: + value = args.get(name, default) + if isinstance(value, bool) or not isinstance(value, int): + raise ToolError(f"argument '{name}' must be an integer") + if minimum is not None and value < minimum: + raise ToolError(f"argument '{name}' must be >= {minimum}") + if maximum is not None and value > maximum: + raise ToolError(f"argument '{name}' must be <= {maximum}") + return value + + +# --------------------------------------------------------------------------- +# JSON Schema для tools/list +# --------------------------------------------------------------------------- + +_TOOLS: list[dict[str, Any]] = [ + { + "name": "list_dir", + "description": "Показать содержимое каталога внутри разрешённых корней.", + "inputSchema": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "Путь относительно первого корня или абсолютный путь внутри корня.", + }, + "recursive": {"type": "boolean", "default": False}, + }, + "required": ["path"], + "additionalProperties": False, + }, + }, + { + "name": "stat", + "description": "Метаданные файла, каталога или символической ссылки.", + "inputSchema": { + "type": "object", + "properties": {"path": {"type": "string"}}, + "required": ["path"], + "additionalProperties": False, + }, + }, + { + "name": "read_file", + "description": "Прочитать текстовый файл (по умолчанию первые 200000 байт).", + "inputSchema": { + "type": "object", + "properties": { + "path": {"type": "string"}, + "max_bytes": { + "type": "integer", + "minimum": 1, + "maximum": MAX_FILE_BYTES, + "default": DEFAULT_READ_BYTES, + }, + }, + "required": ["path"], + "additionalProperties": False, + }, + }, + { + "name": "write_file", + "description": "Атомарно записать текстовый файл (не более 2 МиБ).", + "inputSchema": { + "type": "object", + "properties": { + "path": {"type": "string"}, + "content": {"type": "string"}, + "overwrite": {"type": "boolean", "default": False}, + }, + "required": ["path", "content"], + "additionalProperties": False, + }, + }, + { + "name": "create_dir", + "description": "Создать каталог (включая отсутствующих родителей).", + "inputSchema": { + "type": "object", + "properties": {"path": {"type": "string"}}, + "required": ["path"], + "additionalProperties": False, + }, + }, + { + "name": "move", + "description": "Переместить файл или каталог внутри разрешённых корней.", + "inputSchema": { + "type": "object", + "properties": { + "src": {"type": "string"}, + "dst": {"type": "string"}, + "overwrite": {"type": "boolean", "default": False}, + }, + "required": ["src", "dst"], + "additionalProperties": False, + }, + }, + { + "name": "copy", + "description": "Скопировать файл или каталог внутри разрешённых корней.", + "inputSchema": { + "type": "object", + "properties": { + "src": {"type": "string"}, + "dst": {"type": "string"}, + "overwrite": {"type": "boolean", "default": False}, + }, + "required": ["src", "dst"], + "additionalProperties": False, + }, + }, + { + "name": "delete", + "description": "Удалить объект; по умолчанию он попадает в .xenith-trash внутри корня.", + "inputSchema": { + "type": "object", + "properties": { + "path": {"type": "string"}, + "trash": {"type": "boolean", "default": True}, + }, + "required": ["path"], + "additionalProperties": False, + }, + }, + { + "name": "search", + "description": "Поиск по именам и текстовому содержимому файлов.", + "inputSchema": { + "type": "object", + "properties": { + "query": {"type": "string"}, + "path": {"type": "string", "default": "."}, + "glob": {"type": "string"}, + "max_results": { + "type": "integer", + "minimum": 1, + "maximum": MAX_SEARCH_RESULTS, + "default": DEFAULT_SEARCH_RESULTS, + }, + }, + "required": ["query"], + "additionalProperties": False, + }, + }, +] + + +def _glob_matches(rel_path: str, name: str, pattern: str) -> bool: + if fnmatch.fnmatchcase(name, pattern) or fnmatch.fnmatchcase(rel_path, pattern): + return True + try: + return PurePosixPath(rel_path).match(pattern) + except (TypeError, ValueError): + return False + + +def _tool_error(message: str) -> dict[str, Any]: + return { + "content": [{"type": "text", "text": message}], + "isError": True, + } + + +# --------------------------------------------------------------------------- +# Сервер +# --------------------------------------------------------------------------- + + +class FsServer: + def __init__(self, roots: Iterable[str]): + self.guard = PathGuard(roots) + self._handlers: dict[str, Callable[[dict[str, Any]], Any]] = { + "list_dir": self._list_dir, + "stat": self._stat, + "read_file": self._read_file, + "write_file": self._write_file, + "create_dir": self._create_dir, + "move": self._move, + "copy": self._copy, + "delete": self._delete, + "search": self._search, + } + + # ---- JSON-RPC --------------------------------------------------------- + + def handle_message(self, msg: dict[str, Any]) -> dict[str, Any] | None: + msg_id = msg.get("id", _MISSING) + is_notification = msg_id is _MISSING + + def ok(result: Any) -> dict[str, Any] | None: + if is_notification: + return None + return { + "jsonrpc": "2.0", + "id": None if is_notification else msg_id, + "result": result, + } + + def err(code: int, message: str) -> dict[str, Any] | None: + if is_notification: + return None + return { + "jsonrpc": "2.0", + "id": None if is_notification else msg_id, + "error": {"code": code, "message": message}, + } + + jsonrpc = msg.get("jsonrpc", "2.0") + if jsonrpc != "2.0": + return err(-32600, "unsupported jsonrpc version") + + method = msg.get("method") + if not isinstance(method, str): + return err(-32600, "request is missing a method") + + params = msg.get("params", {}) + if params is None: + params = {} + if not isinstance(params, dict): + return err(-32602, "params must be an object") + + if method == "initialize": + return ok( + { + "protocolVersion": PROTOCOL_VERSION, + "capabilities": {"tools": {}}, + "serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION}, + } + ) + + if method == "notifications/initialized": + log("клиент инициализирован") + return None + + if method == "ping": + return ok({}) + + if method == "tools/list": + return ok({"tools": _TOOLS}) + + if method == "tools/call": + name = params.get("name") + if not isinstance(name, str) or not name: + return err(-32602, "tools/call requires a string tool name") + arguments = params.get("arguments", {}) + if arguments is None: + arguments = {} + if not isinstance(arguments, dict): + return err(-32602, "arguments must be an object") + result = self._call_tool(name, arguments) + if is_notification: + return None + return {"jsonrpc": "2.0", "id": msg_id, "result": result} + + return err(-32601, f"method not found: {method}") + + # ---- Выполнение инструментов ----------------------------------------- + + def _call_tool(self, name: str, args: dict[str, Any]) -> dict[str, Any]: + handler = self._handlers.get(name) + if handler is None: + return _tool_error(f"unknown tool: {name}") + + try: + value = handler(args) + except ToolError as exc: + return _tool_error(str(exc)) + except OSError as exc: + detail = exc.strerror or str(exc) + filename = getattr(exc, "filename", None) + if filename: + detail = f"{detail}: {filename}" + return _tool_error(f"filesystem error: {detail}") + except Exception as exc: # noqa: BLE001 - сервер не должен падать + log(f"внутренняя ошибка {name}:\n{traceback.format_exc()}") + return _tool_error(f"internal error in tool {name}: {exc}") + + if isinstance(value, str): + text = value + else: + text = json.dumps(value, ensure_ascii=False, indent=2) + return { + "content": [{"type": "text", "text": text}], + "isError": False, + } + + # ---- Инструменты ------------------------------------------------------ + + def _list_dir(self, args: dict[str, Any]) -> dict[str, Any]: + raw = _arg_str(args, "path") + recursive = _arg_bool(args, "recursive", False) + base, root = self.guard.resolve(raw, must_exist=True) + if not os.path.isdir(base): + raise ToolError(f"not a directory: {raw}") + + entries: list[dict[str, Any]] = [] + stack = [base] + while stack: + current = stack.pop() + try: + with os.scandir(current) as it: + items = sorted(it, key=lambda e: e.name.casefold()) + except OSError as exc: + raise ToolError(f"cannot read directory {current}: {exc}") from exc + + for entry in items: + try: + is_dir = entry.is_dir(follow_symlinks=False) + except OSError: + is_dir = False + if is_dir and entry.name == TRASH_DIR_NAME: + continue + try: + info = self._entry_info(entry.path, root) + except OSError: + continue + entries.append(info) + if recursive and is_dir: + stack.append(entry.path) + + entries.sort(key=lambda item: item["path"]) + return { + "path": _rel(base, root), + "root": root, + "count": len(entries), + "entries": entries, + } + + def _entry_info(self, path: str, root: str) -> dict[str, Any]: + st = os.lstat(path) + if stat.S_ISLNK(st.st_mode): + kind = "symlink" + elif stat.S_ISDIR(st.st_mode): + kind = "dir" + elif stat.S_ISREG(st.st_mode): + kind = "file" + else: + kind = "other" + return { + "name": os.path.basename(path), + "path": _rel(path, root), + "type": kind, + "size": st.st_size, + "mtime": st.st_mtime, + } + + def _stat(self, args: dict[str, Any]) -> dict[str, Any]: + raw = _arg_str(args, "path") + path, root = self.guard.resolve(raw, must_exist=True, follow_final=False) + st = os.lstat(path) + info = self._entry_info(path, root) + info["mode"] = oct(stat.S_IMODE(st.st_mode)) + if stat.S_ISLNK(st.st_mode): + target = os.path.realpath(path) + if self.guard.root_for(target) is None: + raise ToolError( + "path escapes the allowed roots " + "(outside root; traversal or symlink escape blocked)" + ) + info["target"] = _rel(target, root) + return info + + def _read_file(self, args: dict[str, Any]) -> str: + raw = _arg_str(args, "path") + max_bytes = _arg_int(args, "max_bytes", DEFAULT_READ_BYTES, minimum=1) + limit = min(max_bytes, MAX_FILE_BYTES) + + path, _root = self.guard.resolve(raw, must_exist=True) + st = os.stat(path) + if not stat.S_ISREG(st.st_mode): + raise ToolError(f"not a regular file: {raw}") + + with open(path, "rb") as fh: + chunk = fh.read(limit + 1) + + clipped = len(chunk) > limit + if clipped: + chunk = chunk[:limit] + text = chunk.decode("utf-8", errors="replace") + if clipped: + text += f"\n\n[... truncated: showing the first {limit} bytes of {raw}]" + return text + + def _write_file(self, args: dict[str, Any]) -> dict[str, Any]: + raw = _arg_str(args, "path") + content = _arg_str(args, "content") + overwrite = _arg_bool(args, "overwrite", False) + + data = content.encode("utf-8") + if len(data) > MAX_FILE_BYTES: + raise ToolError( + f"content exceeds {MAX_FILE_BYTES} bytes (got {len(data)})" + ) + + path, root = self.guard.resolve(raw, follow_final=True) + if path == root: + raise ToolError("refusing to overwrite the root directory") + + existed = os.path.lexists(path) + if existed: + if not overwrite: + raise ToolError(f"file already exists: {raw}") + if os.path.isdir(path) and not os.path.islink(path): + raise ToolError(f"path is a directory: {raw}") + + parent = os.path.dirname(path) + os.makedirs(parent, exist_ok=True) + # После создания родителей ещё раз убеждаемся, что путь внутри корня. + path, root = self.guard.resolve(path, follow_final=True) + parent = os.path.dirname(path) + + mode = 0o644 + if existed: + try: + mode = stat.S_IMODE(os.stat(path).st_mode) + except OSError: + pass + + fd, tmp_path = tempfile.mkstemp(prefix=".xenith-write-", dir=parent) + try: + with os.fdopen(fd, "wb") as fh: + fh.write(data) + fh.flush() + os.fsync(fh.fileno()) + try: + os.chmod(tmp_path, mode) + except OSError: + pass + os.replace(tmp_path, path) + except BaseException: + try: + os.unlink(tmp_path) + except OSError: + pass + raise + + return { + "ok": True, + "path": _rel(path, root), + "root": root, + "bytes": len(data), + "overwritten": existed, + } + + def _create_dir(self, args: dict[str, Any]) -> dict[str, Any]: + raw = _arg_str(args, "path") + path, root = self.guard.resolve(raw, follow_final=True) + + if os.path.lexists(path): + if not os.path.isdir(path): + raise ToolError(f"path exists and is not a directory: {raw}") + return {"ok": True, "path": _rel(path, root), "created": False} + + os.makedirs(path, exist_ok=True) + path, root = self.guard.resolve(path, follow_final=True) + return {"ok": True, "path": _rel(path, root), "created": True} + + @staticmethod + def _remove_path(path: str) -> None: + """Удаляет объект, не переходя по символическим ссылкам.""" + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode) and not stat.S_ISLNK(st.st_mode): + shutil.rmtree(path) + else: + os.unlink(path) + + def _move(self, args: dict[str, Any]) -> dict[str, Any]: + src_raw = _arg_str(args, "src") + dst_raw = _arg_str(args, "dst") + overwrite = _arg_bool(args, "overwrite", False) + + src, src_root = self.guard.resolve(src_raw, must_exist=True, follow_final=False) + dst, dst_root = self.guard.resolve(dst_raw, follow_final=False) + + if src == src_root: + raise ToolError("refusing to move the root directory") + if dst == dst_root: + raise ToolError("refusing to replace the root directory") + if src == dst: + raise ToolError("source and destination are the same") + + src_is_dir = os.path.isdir(src) and not os.path.islink(src) + if src_is_dir and _is_within(dst, src): + raise ToolError("cannot move a directory into itself") + + parent = os.path.dirname(dst) + os.makedirs(parent, exist_ok=True) + dst, dst_root = self.guard.resolve(dst_raw, follow_final=False) + + if os.path.lexists(dst): + if not overwrite: + raise ToolError(f"destination already exists: {dst_raw}") + self._remove_path(dst) + + shutil.move(src, dst) + return { + "ok": True, + "src": _rel(src, src_root), + "dst": _rel(dst, dst_root), + "src_root": src_root, + "dst_root": dst_root, + } + + def _copy(self, args: dict[str, Any]) -> dict[str, Any]: + src_raw = _arg_str(args, "src") + dst_raw = _arg_str(args, "dst") + overwrite = _arg_bool(args, "overwrite", False) + + src, src_root = self.guard.resolve(src_raw, must_exist=True, follow_final=True) + dst, dst_root = self.guard.resolve(dst_raw, follow_final=False) + + if src == src_root: + raise ToolError("refusing to copy the root directory") + if dst == dst_root: + raise ToolError("refusing to replace the root directory") + if src == dst: + raise ToolError("source and destination are the same") + + src_is_dir = os.path.isdir(src) + if src_is_dir and _is_within(dst, src): + raise ToolError("cannot copy a directory into itself") + if not src_is_dir and not stat.S_ISREG(os.stat(src).st_mode): + raise ToolError(f"not a regular file: {src_raw}") + + parent = os.path.dirname(dst) + os.makedirs(parent, exist_ok=True) + dst, dst_root = self.guard.resolve(dst_raw, follow_final=False) + + if os.path.lexists(dst): + if not overwrite: + raise ToolError(f"destination already exists: {dst_raw}") + self._remove_path(dst) + + if src_is_dir: + # symlinks=True: копируем ссылки как ссылки, не раскрывая их. + shutil.copytree(src, dst, symlinks=True) + else: + shutil.copy2(src, dst) + + return { + "ok": True, + "src": _rel(src, src_root), + "dst": _rel(dst, dst_root), + "src_root": src_root, + "dst_root": dst_root, + } + + def _delete(self, args: dict[str, Any]) -> dict[str, Any]: + raw = _arg_str(args, "path") + use_trash = _arg_bool(args, "trash", True) + + path, root = self.guard.resolve(raw, must_exist=True, follow_final=False) + if path == root: + raise ToolError("refusing to delete the root directory") + rel = _rel(path, root) + + if use_trash: + if rel == TRASH_DIR_NAME or rel.startswith(TRASH_DIR_NAME + os.sep): + raise ToolError("refusing to move the trash into itself; use trash=false") + stamp = f"{time.strftime('%Y%m%d-%H%M%S')}-{time.time_ns() % 1_000_000_000:09d}" + dest = os.path.join(root, TRASH_DIR_NAME, stamp, rel) + # Проверяем путь корзины: .xenith-trash может оказаться ссылкой наружу. + dest, _trash_root = self.guard.resolve(dest, follow_final=False) + base_dest = dest + counter = 1 + while os.path.lexists(dest): + dest = f"{base_dest}-{counter}" + counter += 1 + os.makedirs(os.path.dirname(dest), exist_ok=True) + shutil.move(path, dest) + return { + "ok": True, + "path": rel, + "trashed": True, + "trash_path": _rel(dest, root), + "root": root, + } + + self._remove_path(path) + return {"ok": True, "path": rel, "trashed": False, "root": root} + + def _search(self, args: dict[str, Any]) -> dict[str, Any]: + query = _arg_str(args, "query") + raw_path = _arg_str(args, "path", required=False, default=".") + pattern = _arg_str(args, "glob", required=False, default=None) + limit = _arg_int(args, "max_results", DEFAULT_SEARCH_RESULTS, minimum=1) + limit = min(limit, MAX_SEARCH_RESULTS) + + base, root = self.guard.resolve(raw_path or ".", must_exist=True) + needle = query.casefold() + results: list[dict[str, Any]] = [] + truncated = False + + def inspect(full_path: str) -> bool: + """Возвращает False, когда пора прекратить обход.""" + nonlocal truncated + rel = _rel(full_path, root) + name = os.path.basename(full_path) + if pattern and not _glob_matches(rel, name, pattern): + return True + + try: + st = os.lstat(full_path) + except OSError: + return True + if stat.S_ISLNK(st.st_mode): + return True + + match: dict[str, Any] | None = None + if needle == "" or needle in name.casefold(): + match = {"path": rel, "type": "file", "match": "name"} + elif stat.S_ISREG(st.st_mode) and st.st_size <= MAX_FILE_BYTES: + try: + with open(full_path, "rb") as fh: + raw = fh.read(MAX_FILE_BYTES + 1) + except OSError: + return True + if len(raw) <= MAX_FILE_BYTES and b"\x00" not in raw[:8192]: + text = raw.decode("utf-8", errors="ignore") + for lineno, line in enumerate(text.splitlines(), 1): + if needle in line.casefold(): + snippet = line.strip() + if len(snippet) > 300: + snippet = snippet[:300] + "..." + match = { + "path": rel, + "type": "file", + "match": "content", + "line": lineno, + "text": snippet, + } + break + + if match is not None: + if len(results) >= limit: + truncated = True + return False + results.append(match) + return True + + if os.path.isdir(base): + stop = False + for dirpath, dirnames, filenames in os.walk(base, followlinks=False): + dirnames[:] = sorted( + name + for name in dirnames + if name != TRASH_DIR_NAME + and not os.path.islink(os.path.join(dirpath, name)) + ) + for filename in sorted(filenames): + if not inspect(os.path.join(dirpath, filename)): + stop = True + break + if stop: + break + else: + inspect(base) + + return { + "query": query, + "path": _rel(base, root), + "count": len(results), + "truncated": truncated, + "max_results": limit, + "results": results, + } + + +# --------------------------------------------------------------------------- +# stdio / JSON-RPC транспорт +# --------------------------------------------------------------------------- + + +def _emit(message: dict[str, Any]) -> None: + sys.stdout.write(json.dumps(message, ensure_ascii=False, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +def _error_response(request_id: Any, code: int, message: str) -> dict[str, Any]: + return { + "jsonrpc": "2.0", + "id": request_id, + "error": {"code": code, "message": message}, + } + + +def serve(server: FsServer) -> int: + for line in sys.stdin: + line = line.strip() + if not line: + continue + + try: + msg = json.loads(line) + except json.JSONDecodeError as exc: + _emit(_error_response(None, -32700, f"JSON parse error: {exc.msg}")) + continue + + if not isinstance(msg, dict): + _emit(_error_response(None, -32600, "request must be a JSON object")) + continue + + try: + response = server.handle_message(msg) + except Exception: # noqa: BLE001 - не роняем транспорт из-за одного запроса + log(f"необработанная ошибка запроса:\n{traceback.format_exc()}") + request_id = msg.get("id") + response = _error_response(request_id, -32603, "internal server error") + + if response is not None: + _emit(response) + + return 0 + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + prog="xenith-fs", + description="Встроенный MCP-сервер файловой системы (stdio JSON-RPC 2.0)", + ) + parser.add_argument( + "--root", + action="append", + required=True, + metavar="PATH", + help="разрешённый корневой каталог (можно указывать несколько раз)", + ) + args = parser.parse_args(argv) + + try: + server = FsServer(args.root) + except (ValueError, OSError) as exc: + log(f"не удалось запустить сервер: {exc}") + return 2 + + # stdout — только протокол; принудительно UTF-8, чтобы JSON не ломался. + try: + sys.stdin.reconfigure(encoding="utf-8", errors="replace") + sys.stdout.reconfigure(encoding="utf-8", newline="\n") + except (AttributeError, ValueError): + pass + + log("запущен; корни: " + ", ".join(server.guard.roots)) + try: + return serve(server) + except (BrokenPipeError, KeyboardInterrupt): + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/XUI/core/mcp/manager.py b/XUI/core/mcp/manager.py new file mode 100644 index 0000000..f3b0a55 --- /dev/null +++ b/XUI/core/mcp/manager.py @@ -0,0 +1,146 @@ +"""Менеджер встроенного MCP-сервера и политики разрешений.""" + +import json +import os +from typing import Callable, Optional + +from ..mcp.client import start_fs_server + + +READ_ONLY_TOOLS = {"list_dir", "stat", "read_file", "search"} + + +class MCPManager: + def __init__(self, app): + self.app = app + self._client = None + self._tools = [] + self._roots = [] + self._last_error = "" + + # ---------- конфиг ---------- + def _conf(self): + try: + return self.app.engine.config.setdefault("mcp", {}) + except Exception: + return {} + + def roots(self): + conf = self._conf() + out = [] + for p in conf.get("roots") or []: + try: + ap = os.path.abspath(os.path.expanduser(str(p))) + except Exception: + continue + if os.path.isdir(ap): + out.append(ap) + return out + + def mode(self): + mode = self._conf().get("mode", "smart") + return mode if mode in ("smart", "full", "restricted") else "smart" + + def enabled(self) -> bool: + return bool(self.roots()) + + # ---------- lifecycle ---------- + def _ensure(self): + roots = self.roots() + if not roots: + raise RuntimeError("Укажите разрешённые папки в настройках MCP") + if self._client is not None and roots == self._roots: + return self._client + self.close() + client = start_fs_server(roots) + client.start() + self._client = client + self._roots = roots + self._tools = client.list_tools() + return client + + def close(self): + if self._client is not None: + try: + self._client.stop() + except Exception: + pass + self._client = None + self._tools = [] + self._roots = [] + + def list_tools(self): + client = self._ensure() + if not self._tools: + self._tools = client.list_tools() + return self._tools + + def tool_prompt(self) -> str: + try: + tools = self.list_tools() + except Exception as e: + return "" + lines = [] + for tool in tools: + name = tool.get("name", "") + desc = tool.get("description", "") + schema = tool.get("inputSchema") or {} + props = list((schema.get("properties") or {}).keys()) + lines.append(f"- {name}: {desc} Аргументы: {', '.join(props)}") + roots = "\n".join(f"- {r}" for r in self.roots()) + return ( + "Доступные файловые инструменты:\n" + "\n".join(lines) + + "\n\nРазрешённые папки:\n" + roots + + "\n\nЧтобы вызвать инструмент, ответь только одним блоком:\n" + "```tool\n{\"tool\": \"имя\", \"arguments\": {...}}\n```\n" + "После результата инструмента продолжи ответ пользователю. " + "Не выходи за пределы разрешённых папок." + ) + + # ---------- вызов ---------- + def call_tool(self, name: str, arguments: dict, + ask: Optional[Callable[[str, dict], bool]] = None): + client = self._ensure() + mode = self.mode() + readonly = name in READ_ONLY_TOOLS + need_ask = mode == "restricted" or (mode == "smart" and not readonly) + if need_ask and ask is not None: + if not ask(name, dict(arguments or {})): + msg = "Пользователь отклонил вызов инструмента" + self._audit(name, arguments, False, msg) + return False, msg + try: + raw = client.call_tool(name, dict(arguments or {})) + ok = True + text = self._extract_text(raw) + if isinstance(raw, dict) and raw.get("isError"): + ok = False + self._audit(name, arguments, ok, text) + return ok, text + except Exception as e: + self._audit(name, arguments, False, str(e)) + return False, str(e) + + def _extract_text(self, raw) -> str: + if isinstance(raw, dict): + content = raw.get("content") + if isinstance(content, list): + parts = [] + for item in content: + if isinstance(item, dict) and item.get("type") == "text": + parts.append(str(item.get("text", ""))) + if parts: + return "\n".join(parts) + return json.dumps(raw, ensure_ascii=False) + return str(raw) + + def _audit(self, name, arguments, ok, text): + try: + self.app.app_state.add_interaction( + "mcp", input_text=json.dumps({"tool": name, "arguments": arguments}, + ensure_ascii=False)[:4000], + output_text=str(text)[:4000], ok=ok, error="" if ok else str(text)[:1000], + meta={"tool": name, "mode": self.mode()}, + ) + except Exception: + pass diff --git a/XUI/core/state.py b/XUI/core/state.py index 0d9f5de..3716077 100644 --- a/XUI/core/state.py +++ b/XUI/core/state.py @@ -7,6 +7,8 @@ from typing import Optional, List, Dict, Any class AppState: current_model_path: Optional[str] = None current_model_name: Optional[str] = None + current_engine_id: Optional[str] = None + current_engine_name: Optional[str] = None model_loaded: bool = False mode: str = "chat" @@ -20,6 +22,7 @@ class AppState: # История графика обучения (переживает пересборку UI/смену темы). training_loss: List[Any] = field(default_factory=list) training_graph_x: int = 0 + training_stage: str = "data" chat_history: List[Dict[str, str]] = field(default_factory=list) diff --git a/XUI/theme.py b/XUI/theme.py index ed3fe9c..781f577 100644 --- a/XUI/theme.py +++ b/XUI/theme.py @@ -220,6 +220,17 @@ def _widget_theme(spec: ThemeSpec) -> dict: "button_color": g("scrollbar"), "button_hover_color": g("scrollbar_hover"), }, + "CTkSwitch": { + "corner_radius": 1000, + "border_width": 3, + "button_length": 0, + "fg_color": g("border"), + "progress_color": g("accent"), + "button_color": g("slider_button"), + "button_hover_color": g("slider_button_hover"), + "text_color": g("text"), + "text_color_disabled": g("text_faint"), + }, "CTkSlider": { "corner_radius": 1000, "button_corner_radius": 1000, diff --git a/XUI/views/chat.py b/XUI/views/chat.py index bac7b92..3b78f15 100644 --- a/XUI/views/chat.py +++ b/XUI/views/chat.py @@ -1,13 +1,15 @@ import json import re +import threading import time import customtkinter as ctk -from tkinter import filedialog +from tkinter import filedialog, messagebox from .base import ViewBase from ..theme import c, mono_font, ui_font from ..components.controls import IconButton +from ..core.mcp.manager import MCPManager class ChatView(ViewBase): @@ -17,6 +19,13 @@ class ChatView(ViewBase): self.configure(fg_color="transparent") self._busy = False self._labels = [] # [(CTkLabel, is_user), ...] — для пересчёта переноса строк + self._stream_label = None + self._stream_text = "" + self._agent_mode = False + try: + self.mcp = MCPManager(self.app) + except Exception: + self.mcp = None self._column_pad = 24 # центральная колонка чата (не даём растягиваться на весь экран) @@ -36,6 +45,13 @@ class ChatView(ViewBase): self._ghost(meta_row, "Экспорт", self.export_chat, width=66).pack(side="left") self._ghost(meta_row, "Очистить", self.clear_chat, width=72).pack(side="left", padx=(4, 0)) + self.agent_switch = ctk.CTkSwitch( + meta_row, text="Файлы", width=64, switch_width=28, switch_height=14, + font=ui_font(11), text_color=c("text_dim"), + command=self._toggle_agent, + ) + self.agent_switch.pack(side="left", padx=(10, 0)) + self.status_label = ctk.CTkLabel(meta_row, text="", font=ui_font(11), text_color=c("text_faint"), anchor="w") self.status_label.pack(side="left", padx=(10, 0)) @@ -197,50 +213,14 @@ class ChatView(ViewBase): def _get_context_info(self): """Возвращает (used, limit, estimated). used/limit могут быть None.""" - if not self.engine or getattr(self.engine, "model", None) is None or not (self.app_state and self.app_state.model_loaded): + if not self.engine or not (self.app_state and self.app_state.model_loaded): return None, None, False - - model = self.engine.model - used = None - limit = None - + used = limit = None + estimated = True try: - if hasattr(model, "chat_history"): - h = model.chat_history() - if isinstance(h, dict): - for k in ("context_used", "used", "tokens_used", "n_ctx_used"): - if k in h and h[k] is not None: - used = int(h[k]) - break - for k in ("context_max", "context_size", "ctx", "n_ctx", "max_ctx"): - if k in h and h[k] is not None: - limit = int(h[k]) - break + used, limit, estimated = self.engine.context_info() except Exception: pass - - if limit is None: - for attr in ("n_ctx", "ctx", "context_size", "block_size"): - try: - v = getattr(model, attr, None) - if v is not None: - limit = int(v) - break - except Exception: - pass - if limit is None: - try: - if hasattr(model, "info"): - info = model.info() - if isinstance(info, dict): - for k in ("ctx", "n_ctx", "context_size", "block_size", "block"): - if k in info and info[k] is not None: - limit = int(info[k]) - break - except Exception: - pass - - estimated = False if used is None: used = self._estimate_context_used() estimated = True @@ -250,7 +230,7 @@ class ChatView(ViewBase): if not hasattr(self, "context_label"): return - if not self.engine or getattr(self.engine, "model", None) is None or not (self.app_state and self.app_state.model_loaded): + if not self.engine or not (self.app_state and self.app_state.model_loaded): self.context_label.configure(text="Контекст —", text_color=c("text_faint")) return @@ -285,6 +265,13 @@ class ChatView(ViewBase): for w in self.messages.winfo_children(): w.destroy() self._labels = [] + self._stream_label = None + self._stream_text = "" + self._agent_mode = False + try: + self.mcp = MCPManager(self.app) + except Exception: + self.mcp = None def _add_empty_state(self): loaded = bool(self.app_state and self.app_state.model_loaded) @@ -531,27 +518,221 @@ class ChatView(ViewBase): self._update_placeholder() self.set_busy(True) self.update_context_indicator() + self._append_assistant_shell() params = dict(self.app_state.gen_params) if self.app_state.gen_params else {} messages = list(self.app_state.chat_history) + if self._agent_mode: + self._start_agent(messages, params) + return + def on_result(result_text: str): self.ui(lambda t=result_text: self._on_result(t)) + def on_token(piece: str): + self.ui(lambda p=piece: self._on_token(p)) + if self.engine is None: self._on_result("[ОШИБКА] Движок недоступен.") return try: - self.engine.chat(messages, params=params, on_result=on_result) + self.engine.chat(messages, params=params, on_result=on_result, on_token=on_token) except Exception as e: self.set_busy(False) self.status_label.configure(text=f"[ОШИБКА] {e}") + def _append_assistant_shell(self): + row = ctk.CTkFrame(self.messages, fg_color="transparent") + row.pack(fill="x", pady=(0, 16)) + bubble = ctk.CTkFrame(row, fg_color="transparent") + bubble.pack(side="left", fill="x", expand=True, anchor="w") + ctk.CTkLabel(bubble, text="Xenith", font=ui_font(11), + text_color=c("text_dim")).pack(anchor="w", padx=2, pady=(0, 4)) + label = ctk.CTkLabel( + bubble, text="", justify="left", anchor="w", font=ui_font(13), + text_color=c("text"), wraplength=self._max_text_width(), + ) + label.pack(anchor="w", padx=2) + self._labels.append((label, False)) + self._stream_label = label + self._stream_text = "" + self._scroll_bottom() + + def _on_token(self, piece: str): + if not piece or self._stream_label is None: + return + self._stream_text += str(piece) + try: + if self._stream_label.winfo_exists(): + self._stream_label.configure(text=self._stream_text) + except Exception: + pass + self._scroll_bottom() + + # ---------- агентный режим / MCP ---------- + def _toggle_agent(self): + try: + on = bool(self.agent_switch.get()) + except Exception: + on = False + if on and (self.mcp is None or not self.mcp.enabled()): + try: + self.agent_switch.deselect() + except Exception: + pass + self._agent_mode = False + self.status_label.configure(text="Укажите папки в настройках MCP") + try: + if self.app: + self.app.open_settings("mcp") + except Exception: + pass + return + self._agent_mode = on + self.status_label.configure(text="Файлы включены" if on else "") + + def _parse_tool_call(self, text: str): + m = re.search(r"```tool\s*(\{.*?\})\s*```", text or "", re.S) + raw = m.group(1) if m else None + if raw is None: + m2 = re.search(r'(\{\s*"tool"\s*:.*?\})', text or "", re.S) + raw = m2.group(1) if m2 else None + if not raw: + return None + try: + data = json.loads(raw) + except Exception: + return None + if not isinstance(data, dict): + return None + name = data.get("tool") or data.get("name") + args = data.get("arguments") or data.get("args") or {} + if not name or not isinstance(args, dict): + return None + return str(name), args + + def _append_tool_note(self, title: str, body: str = "", ok: bool = True): + row = ctk.CTkFrame(self.messages, fg_color="transparent") + row.pack(fill="x", pady=(0, 8)) + box = ctk.CTkFrame(row, fg_color=c("code_bg"), corner_radius=8, + border_width=1, border_color=c("border")) + box.pack(anchor="w", fill="x", padx=2) + ctk.CTkLabel(box, text=title, font=mono_font(10), + text_color=(c("text_dim") if ok else c("danger"))).pack( + anchor="w", padx=10, pady=(8, 2)) + if body: + label = ctk.CTkLabel( + box, text=body, font=mono_font(10), justify="left", anchor="w", + text_color=(c("text_faint") if ok else c("danger")), + wraplength=max(240, self._max_text_width() - 36), + ) + label.pack(anchor="w", padx=10, pady=(0, 8)) + self._labels.append((label, False)) + self._scroll_bottom() + + def _ask_tool(self, name: str, args: dict) -> bool: + event = threading.Event() + box = {"ok": False} + + def ask_ui(): + try: + preview = json.dumps(args, ensure_ascii=False, indent=2)[:900] + box["ok"] = messagebox.askyesno( + "MCP: подтверждение", + f"Разрешить инструмент «{name}»?\n\n{preview}", + parent=self, + ) + finally: + event.set() + + try: + self.ui(ask_ui) + except Exception: + return False + event.wait(timeout=180) + return bool(box.get("ok")) + + def _flatten_history(self, messages, limit=10): + lines = [] + for m in messages[-limit:]: + role = m.get("role", "user") + content = str(m.get("content", "")) + who = "Пользователь" if role == "user" else ("Ассистент" if role == "assistant" else role) + lines.append(f"{who}: {content}") + return "\n".join(lines) + + def _start_agent(self, messages, params): + if self.mcp is None or not self.mcp.enabled(): + self._on_result("[ОШИБКА] MCP не настроен: укажите папки в настройках") + return + try: + tools_prompt = self.mcp.tool_prompt() + except Exception as e: + self._on_result(f"[ОШИБКА] MCP: {e}") + return + system = (getattr(self.app_state, "system_prompt", "") or "").strip() + base = ( + (system + "\n\n" if system else "") + + "Ты — Xenith, локальный ассистент с доступом к файловым инструментам.\n" + + tools_prompt + "\n\n" + ) + transcript = self._flatten_history(messages, limit=10) + + def worker(): + final = "" + prompt = base + "Диалог:\n" + transcript + "\nАссистент:" + try: + for step in range(4): + out = self.engine.generate_sync(prompt, params) + call = self._parse_tool_call(out) + if not call: + final = (out or "").strip() + break + name, args = call + self.ui(lambda n=name, a=args: self._append_tool_note( + f"tool: {n}", json.dumps(a, ensure_ascii=False)[:700], True)) + ok, result = self.mcp.call_tool(name, args, ask=self._ask_tool) + preview = str(result) + if len(preview) > 1400: + preview = preview[:1400] + "…" + self.ui(lambda n=name, r=preview, o=ok: self._append_tool_note( + f"{'ok' if o else 'ошибка'}: {n}", r, o)) + prompt += ( + f"\n{out}\nРезультат инструмента {name}:\n{result[:4000]}\n" + "Продолжи ответ пользователю. Если инструмент больше не нужен — ответь обычным текстом." + ) + final = (out or "").strip() + except Exception as e: + final = f"[ОШИБКА] {e}" + self.ui(lambda t=final: self._on_result(t)) + + threading.Thread(target=worker, daemon=True).start() + + def destroy(self): + try: + if getattr(self, "mcp", None) is not None: + self.mcp.close() + except Exception: + pass + super().destroy() + def _on_result(self, result_text: str): if self.app_state is not None: self.app_state.chat_history.append({"role": "assistant", "content": result_text}) - self._append_message("assistant", result_text) + if self._stream_label is not None: + label = self._stream_label + self._stream_label = None + final = result_text or self._stream_text + try: + if label.winfo_exists(): + label.configure(text=final) + except Exception: + pass + self._stream_text = "" + else: + self._append_message("assistant", result_text) self.set_busy(False) self.update_context_indicator() try: diff --git a/XUI/views/dev.py b/XUI/views/dev.py index f7fd474..0545af3 100644 --- a/XUI/views/dev.py +++ b/XUI/views/dev.py @@ -43,9 +43,9 @@ class DevView(ViewBase): path = st.current_model_path or "—" info = { "engine_ready": engine_ok, + "engine_id": getattr(st, "current_engine_id", None), + "engine_name": getattr(st, "current_engine_name", None), "engine_version": (self.engine.version() if self.engine else ""), - "backend": getattr(self.engine, "backend", "?"), - "backend_info": getattr(self.engine, "backend_info", ""), "mode": st.mode, "model_loaded": st.model_loaded, "current_model": model, @@ -57,12 +57,16 @@ class DevView(ViewBase): "system_prompt_set": bool(getattr(st, "system_prompt", "")), "gen_params": st.gen_params, } - # Доп. инфо из модели, если доступно + # Доп. инфо из менеджера движков (и модели, если доступна) + try: + if self.engine and hasattr(self.engine, "info"): + info.update(self.engine.info()) + except Exception: + pass try: if self.engine and self.engine.model and hasattr(self.engine.model, "info"): mi = self.engine.model.info() if isinstance(mi, dict): - # короткая выжимка for k in ("n_layer", "n_embd", "n_head", "n_ctx", "ctx", "vocab_size"): if k in mi: info[f"model.{k}"] = mi[k] diff --git a/XUI/views/models.py b/XUI/views/models.py index 7d0617c..47ae364 100644 --- a/XUI/views/models.py +++ b/XUI/views/models.py @@ -1,4 +1,5 @@ import os +import threading import customtkinter as ctk from tkinter import filedialog @@ -7,23 +8,37 @@ from .base import ViewBase from ..theme import c, mono_font, ui_font +def _fmt_size(size: int) -> str: + try: + size = int(size) + except Exception: + size = 0 + if size >= 1024 ** 3: + return f"{size / (1024 ** 3):.2f} ГБ" + if size >= 1024 ** 2: + return f"{size / (1024 ** 2):.1f} МБ" + if size >= 1024: + return f"{size / 1024:.0f} КБ" + return f"{size} Б" + + class ModelsView(ViewBase): def __init__(self, master, **kwargs): super().__init__(master, **kwargs) self.title_text = "Модели" self.configure(fg_color="transparent") - # Пути, добавленные пользователем вручную (файлы/папки). - # Храним в AppState, чтобы они не терялись при смене темы/пересборке UI. + # Пути, добавленные вручную (переживают смену темы). if self.app_state is not None: self.extra_model_paths = self.app_state.extra_model_paths else: self.extra_model_paths = [] self._loading = False + self._scanned = False self._load_buttons = [] self.current_label = ctk.CTkLabel( - self, text="Текущая модель —", anchor="w", + self, text="Модель —", anchor="w", font=ctk.CTkFont(size=11), text_color=c("text_dim"), ) self.current_label.pack(anchor="w", padx=24, pady=(18, 8)) @@ -45,112 +60,213 @@ class ModelsView(ViewBase): self.list_frame = ctk.CTkScrollableFrame(self) self.list_frame.pack(fill="both", expand=True, padx=24, pady=(10, 20)) - self._render_paths([]) self._update_current_label() + self._render_placeholder("Нажмите «Сканировать», чтобы увидеть модели движков") + # ---------- заголовок ---------- def _update_current_label(self): if not self.app_state: - self.current_label.configure(text="Текущая модель —") + self.current_label.configure(text="Модель —") return if self.app_state.model_loaded: name = self.app_state.current_model_name or "загружена" + engine = getattr(self.app_state, "current_engine_name", "") or "" path = self.app_state.current_model_path + text = f"Модель — {name}" + if engine: + text += f" · {engine}" if path: - self.current_label.configure(text=f"Текущая модель — {name} ({path})") - else: - self.current_label.configure(text=f"Текущая модель — {name} (в памяти)") + text += f" ({path})" + self.current_label.configure(text=text) else: - self.current_label.configure(text="Текущая модель: не загружена") + self.current_label.configure(text="Модель не загружена") - def _render_paths(self, paths): + # ---------- сканирование ---------- + def on_show(self): + self._update_current_label() + if not self._scanned and not self._loading: + self.scan() + + def scan(self): + if self._loading or not self.engine: + return + self._set_loading(True, "Сканирование движков…") + + def task(): + groups = {} + errors = {} + try: + engines = self.engine.engines() + except Exception as e: + engines = [] + errors[""] = str(e) + for item in engines: + eid = item.get("id") + if not item.get("enabled", True): + continue + try: + groups[eid] = self.engine.list_models(eid) + except Exception as e: + groups[eid] = [] + errors[eid] = str(e) + self.ui(lambda: self._render_groups(groups, errors)) + + threading.Thread(target=task, daemon=True).start() + + def _clear_list(self): for w in self.list_frame.winfo_children(): w.destroy() self._load_buttons = [] - self._update_current_label() + def _render_placeholder(self, text): + self._clear_list() + ctk.CTkLabel( + self.list_frame, text=text, anchor="w", justify="left", + font=ui_font(12), text_color=c("text_dim"), + ).pack(anchor="w", pady=(4, 2)) - if not paths: - ctk.CTkLabel( - self.list_frame, - text="Модели не найдены. Нажмите «Сканировать» или добавьте файл или папку", - anchor="w", - justify="left", - font=ui_font(12), - text_color=c("text_dim"), - ).pack(anchor="w", pady=(4, 2)) - ctk.CTkLabel( - self.list_frame, - text=".xnh — родной формат Xenith; большие GGUF-модели загружаются дольше и требуют больше памяти", - anchor="w", - justify="left", - font=ui_font(11), - text_color=c("text_faint"), - wraplength=760, - ).pack(anchor="w", pady=(0, 4)) + def _render_groups(self, groups, errors): + self._clear_list() + self._scanned = True + self._set_loading(False) + + if not groups: + self._render_placeholder("Нет доступных движков. Добавьте движок в настройках") return - current_path = None - if self.app_state and self.app_state.current_model_path: - try: - current_path = os.path.abspath(self.app_state.current_model_path) - except Exception: - current_path = self.app_state.current_model_path + try: + engine_meta = {e["id"]: e for e in self.engine.engines()} + except Exception: + engine_meta = {} - for p in paths: - ap = os.path.abspath(p) - row = ctk.CTkFrame(self.list_frame, fg_color="transparent", corner_radius=0) - row.pack(fill="x", pady=0) - content = ctk.CTkFrame(row, fg_color="transparent", corner_radius=0) - content.pack(fill="x") + current_name = self.app_state.current_model_name if self.app_state else "" + current_path = self.app_state.current_model_path if self.app_state else "" + current_engine = getattr(self.app_state, "current_engine_id", None) if self.app_state else None + active_id = getattr(self.engine, "active_id", "") - is_current = current_path and ap == current_path - size_hint = "" - try: - sz = os.path.getsize(ap) - if sz >= 1024 * 1024 * 1024: - size_hint = f" · {sz / (1024**3):.2f} ГБ" - elif sz >= 1024 * 1024: - size_hint = f" · {sz / (1024**2):.1f} МБ" - except Exception: - pass - label_text = p + size_hint - ctk.CTkLabel(content, text=label_text, anchor="w", wraplength=760, justify="left", - font=ui_font(12), text_color=c("text_dim")).pack(side="left", padx=14, pady=12) + total = 0 + for eid, models in groups.items(): + meta = engine_meta.get(eid, {}) + title = meta.get("name") or eid + if eid == active_id: + title += " · активный" + header = ctk.CTkFrame(self.list_frame, fg_color="transparent") + header.pack(fill="x", pady=(10, 4)) + ctk.CTkLabel(header, text=title, font=ui_font(12), + text_color=c("text")).pack(side="left", padx=2) + if errors.get(eid): + ctk.CTkLabel(header, text="недоступен", font=ui_font(10), + text_color=c("danger")).pack(side="left", padx=8) - if is_current: - ctk.CTkLabel(content, text="текущая", font=ui_font(10), - text_color=c("text_faint")).pack(side="left", padx=(4, 8)) + if not models: + msg = errors.get(eid) or "нет моделей" + ctk.CTkLabel(self.list_frame, text=msg, font=ui_font(11), + text_color=c("text_faint"), anchor="w", + wraplength=760, justify="left").pack(anchor="w", padx=14, pady=(0, 6)) + continue - btn_text = "Открыть в чате" if is_current else "Загрузить" - btn = ctk.CTkButton( - content, - text=btn_text, - width=136, - height=32, - command=lambda path=p, cur=is_current: self._on_model_action(path, cur), - state=("disabled" if self._loading and not is_current else "normal"), - fg_color=(c("action_bg") if is_current else c("control")), - hover_color=(c("action_hover") if is_current else c("card_hover")), - text_color=(c("action_fg") if is_current else c("text")), - font=ui_font(12), - ) - btn.pack(side="right", padx=14, pady=8) - self._load_buttons.append(btn) + for model in models: + total += 1 + is_current = bool( + (model.id == current_name or (current_path and model.path == current_path)) + and (current_engine in (None, eid)) + ) + self._add_model_row(eid, model, is_current) - ctk.CTkFrame(row, fg_color=c("border"), height=1, corner_radius=0).pack(fill="x") + if total == 0: + ctk.CTkLabel( + self.list_frame, + text="Модели не найдены. Проверьте, запущен ли движок, или добавьте файл/папку", + font=ui_font(12), text_color=c("text_dim"), anchor="w", + wraplength=760, justify="left", + ).pack(anchor="w", padx=2, pady=(8, 2)) - def _on_model_action(self, path, is_current): + def _add_model_row(self, engine_id, model, is_current): + row = ctk.CTkFrame(self.list_frame, fg_color="transparent", corner_radius=0) + row.pack(fill="x", pady=0) + content = ctk.CTkFrame(row, fg_color="transparent", corner_radius=0) + content.pack(fill="x") + + label_text = model.name or model.id + meta = [] + if model.size: + meta.append(_fmt_size(model.size)) + if model.path: + meta.append(model.path) + if meta: + label_text += " " + " · ".join(meta) + + ctk.CTkLabel(content, text=label_text, anchor="w", wraplength=860, justify="left", + font=ui_font(12), text_color=c("text_dim")).pack(side="left", padx=14, pady=12) + + if is_current: + ctk.CTkLabel(content, text="текущая", font=ui_font(10), + text_color=c("text_faint")).pack(side="left", padx=(4, 8)) + + btn_text = "Открыть в чате" if is_current else "Загрузить" + btn = ctk.CTkButton( + content, + text=btn_text, + width=136, + height=32, + command=lambda e=engine_id, m=model, cur=is_current: self._on_model_action(e, m, cur), + state=("disabled" if self._loading and not is_current else "normal"), + fg_color=(c("action_bg") if is_current else c("control")), + hover_color=(c("action_hover") if is_current else c("card_hover")), + text_color=(c("action_fg") if is_current else c("text")), + font=ui_font(12), + ) + btn.pack(side="right", padx=14, pady=8) + self._load_buttons.append(btn) + + ctk.CTkFrame(row, fg_color=c("border"), height=1, corner_radius=0).pack(fill="x") + + def _on_model_action(self, engine_id, model, is_current): if is_current and self.app: self.app.switch_view("chat") return - self.load(path) + self.load(engine_id, model.id) - def scan(self): + def load(self, engine_id, model_id): if not self.engine: return - paths = self.engine.scan_models(self.extra_model_paths) - self._render_paths(paths) + try: + if self.app is not None and self.app.any_busy(exclude=self): + self.status_label.configure(text="Дождитесь завершения текущей операции") + return + except Exception: + pass + self._set_loading(True, f"Загрузка: {model_id}") + if self.app_state: + self.app_state.log(f"[UI] Загрузка модели: {model_id} ({engine_id})") + try: + self.engine.set_active_engine(engine_id) + except Exception as e: + self.status_label.configure(text=f"Ошибка выбора движка: {e}") + self._set_loading(False) + return + + self.engine.load_model(model_id, on_done=self._after_load_threadsafe, engine_id=engine_id) + + def _after_load_threadsafe(self): + self.ui(self.after_load) + + def after_load(self): + if self.app and self.app_state: + self.app.sidebar.update_status(self.app_state, self.engine.is_ready() if self.engine else False) + self._loading = False + self.status_label.configure(text="") + self._update_current_label() + self.scan() + try: + still_here = self.app is None or self.app.current_view is self + except Exception: + still_here = False + if self.app_state and self.app_state.model_loaded and self.app and still_here: + self.app.switch_view("chat") + + # ---------- добавление путей ---------- def add_file(self): f = filedialog.askopenfilename(title="Выбрать файл модели") if not f: @@ -171,7 +287,10 @@ class ModelsView(ViewBase): def _set_loading(self, loading: bool, msg: str = ""): self._loading = loading - self.status_label.configure(text=msg) + if msg: + self.status_label.configure(text=msg) + elif not loading: + self.status_label.configure(text="") state = "disabled" if loading else "normal" try: self.btn_scan.configure(state=state) @@ -179,63 +298,3 @@ class ModelsView(ViewBase): self.btn_add_folder.configure(state=state) except Exception: pass - # Перерисуем список, чтобы обновить состояние кнопок - try: - if hasattr(self, "list_frame"): - self.scan() - except Exception: - pass - - def load(self, path): - if not self.engine: - return - # Не подменяем модель, пока идёт генерация/обучение. - try: - if self.app is not None and self.app.any_busy(exclude=self): - self.status_label.configure(text="Дождитесь завершения текущей операции") - return - except Exception: - pass - ap = os.path.abspath(path) - if ap not in self.extra_model_paths: - self.extra_model_paths.append(ap) - - # Предупреждение для больших файлов / GGUF - warn = "" - try: - ext = os.path.splitext(ap)[1].lower() - sz = os.path.getsize(ap) - if ext == ".gguf" or sz >= 512 * 1024 * 1024: - warn = " Внимание: большой файл/GGUF — загрузка может занять долго и сильно нагрузить память." - except Exception: - pass - - self._set_loading(True, f"Загрузка: {os.path.basename(ap)}{warn}") - if self.app_state: - self.app_state.log(f"[UI] Запрошена загрузка модели: {ap}") - - self.engine.load_model(path, on_done=self._after_load_threadsafe) - - def _after_load_threadsafe(self): - # engine.load_model вызывает on_done из фонового потока - self.ui(self.after_load) - - def after_load(self): - """Обновление UI после загрузки модели. Выполняется в главном потоке.""" - self._loading = False - self.status_label.configure(text="") - self.scan() - # Если загрузка успешна — в чат. Но только если пользователь всё ещё на этой - # вкладке: иначе автопереход «крадёт» выбранную вкладку. - try: - still_here = self.app is None or self.app.current_view is self - except Exception: - still_here = False - if self.app_state and self.app_state.model_loaded and self.app and still_here: - self.app.switch_view("chat") - - def on_show(self): - # Обновляем подпись и список моделей при открытии вкладки: так новые - # модели (например, только что обученные) видны без ручного «Сканировать». - self._update_current_label() - self.scan() diff --git a/XUI/views/modes.py b/XUI/views/modes.py index be5c31a..d860e8f 100644 --- a/XUI/views/modes.py +++ b/XUI/views/modes.py @@ -233,22 +233,15 @@ class ModesView(ViewBase): def task(): try: results = [] - model = self.engine.model for i, p in enumerate(prompts, 1): self.ui(lambda idx=i, total=len(prompts), pr=p: self._set_status(self.eval_status, f"{idx}/{total}: {pr[:40]}")) try: - res = model.generate( + text = self.engine.generate_sync( p, - n=int(n), - temperature=params.get("temperature", 0.7), - top_p=params.get("top_p", 0.9), + {"n": n, + "temperature": params.get("temperature", 0.7), + "top_p": params.get("top_p", 0.9)}, ) - if isinstance(res, str): - text = res - elif res is not None: - text = getattr(res, "text", None) or getattr(res, "output", None) or str(res) - else: - text = "" except Exception as e: text = f"[ОШИБКА] {e}" results.append((p, text)) diff --git a/XUI/views/server.py b/XUI/views/server.py index 9a302e4..916b158 100644 --- a/XUI/views/server.py +++ b/XUI/views/server.py @@ -1,9 +1,12 @@ +import secrets +import socket import time import customtkinter as ctk from .base import ViewBase from ..theme import c, mono_font, ui_font +from ..core.api_server import ApiServer class ServerView(ViewBase): @@ -11,95 +14,254 @@ class ServerView(ViewBase): super().__init__(master, **kwargs) self.title_text = "Сервер" self.configure(fg_color="transparent") + self._server = None + self._client_label_last = "" panel = ctk.CTkFrame(self) panel.pack(fill="x", padx=24, pady=(16, 10)) - self.status_label = ctk.CTkLabel(panel, text="Статус: остановлен", font=ui_font(13), text_color=c("text")) - self.status_label.grid(row=0, column=0, columnspan=4, sticky="w", padx=16, pady=(16, 8)) + self.status_label = ctk.CTkLabel(panel, text="Статус: остановлен", + font=ui_font(13), text_color=c("text")) + self.status_label.grid(row=0, column=0, columnspan=5, sticky="w", padx=16, pady=(14, 8)) - ctk.CTkLabel(panel, text="Хост", font=ui_font(11), text_color=c("text_dim")).grid(row=1, column=0, sticky="w", padx=16, pady=6) - self.host_entry = ctk.CTkEntry(panel, width=180, font=ui_font(12)) + ctk.CTkLabel(panel, text="Хост", font=ui_font(11), + text_color=c("text_dim")).grid(row=1, column=0, sticky="w", padx=16, pady=6) + self.host_entry = ctk.CTkEntry(panel, width=160, font=ui_font(12)) self.host_entry.grid(row=1, column=1, sticky="w", padx=8, pady=6) - ctk.CTkLabel(panel, text="Порт", font=ui_font(11), text_color=c("text_dim")).grid(row=1, column=2, sticky="w", padx=16, pady=6) - self.port_entry = ctk.CTkEntry(panel, width=120, font=ui_font(12)) + ctk.CTkLabel(panel, text="Порт", font=ui_font(11), + text_color=c("text_dim")).grid(row=1, column=2, sticky="w", padx=16, pady=6) + self.port_entry = ctk.CTkEntry(panel, width=100, font=ui_font(12)) self.port_entry.grid(row=1, column=3, sticky="w", padx=8, pady=6) + ctk.CTkLabel(panel, text="Токен", font=ui_font(11), + text_color=c("text_dim")).grid(row=2, column=0, sticky="w", padx=16, pady=6) + self.token_entry = ctk.CTkEntry(panel, width=420, font=mono_font(10)) + self.token_entry.grid(row=2, column=1, columnspan=4, sticky="we", padx=8, pady=6) + btns = ctk.CTkFrame(panel, fg_color="transparent") - btns.grid(row=2, column=0, columnspan=4, sticky="w", padx=16, pady=(8, 16)) - ctk.CTkButton(btns, text="Старт", width=120, height=34, command=self.start, fg_color=c("action_bg"), hover_color=c("action_hover"), text_color=c("action_fg"), font=ui_font(12)).pack(side="left") - ctk.CTkButton(btns, text="Стоп", width=120, height=34, command=self.stop).pack(side="left", padx=8) - ctk.CTkButton(btns, text="Применить адрес", width=140, height=34, command=self.apply_address).pack(side="left", padx=8) - ctk.CTkButton(btns, text="Очистить лог", width=120, height=34, command=self.clear_log).pack(side="left", padx=8) + btns.grid(row=3, column=0, columnspan=5, sticky="w", padx=16, pady=(8, 8)) + self.btn_start = ctk.CTkButton(btns, text="Запустить", width=120, height=34, + command=self.start, fg_color=c("action_bg"), + hover_color=c("action_hover"), + text_color=c("action_fg"), font=ui_font(12)) + self.btn_start.pack(side="left") + self.btn_stop = ctk.CTkButton(btns, text="Остановить", width=120, height=34, + command=self.stop, state="disabled") + self.btn_stop.pack(side="left", padx=8) + ctk.CTkButton(btns, text="Применить адрес", width=140, height=34, + command=self.apply_address).pack(side="left", padx=8) + ctk.CTkButton(btns, text="Новый токен", width=120, height=34, + command=self.rotate_token).pack(side="left", padx=8) + ctk.CTkButton(btns, text="Очистить лог", width=120, height=34, + command=self.clear_log).pack(side="left", padx=8) - self.uptime_label = ctk.CTkLabel(panel, text="Время работы —", font=ui_font(11), text_color=c("text_faint")) - self.uptime_label.grid(row=3, column=0, columnspan=4, sticky="w", padx=16, pady=(0, 16)) + self.endpoint_label = ctk.CTkLabel( + panel, text="", font=mono_font(10), text_color=c("text_faint"), + anchor="w", justify="left", + ) + self.endpoint_label.grid(row=4, column=0, columnspan=5, sticky="w", padx=16, pady=(0, 4)) + self.uptime_label = ctk.CTkLabel(panel, text="Время работы —", + font=ui_font(11), text_color=c("text_faint")) + self.uptime_label.grid(row=5, column=0, columnspan=5, sticky="w", padx=16, pady=(0, 14)) - ctk.CTkLabel(self, text="Лог сервера — панель управления без реального HTTP", anchor="w", font=ui_font(11), text_color=c("text_faint")).pack(anchor="w", padx=24, pady=(8, 4)) - self.logbox = ctk.CTkTextbox(self, wrap="word") + ctk.CTkLabel( + self, + text="OpenAI- и Ollama-совместимый API для будущего телефонного приложения и внешних клиентов", + anchor="w", font=ui_font(11), text_color=c("text_faint"), + ).pack(anchor="w", padx=24, pady=(8, 0)) + ctk.CTkLabel( + self, + text="Автономно: python xenith_server.py --model <файл> --host 0.0.0.0", + anchor="w", font=mono_font(10), text_color=c("text_faint"), + ).pack(anchor="w", padx=24, pady=(2, 6)) + + self.logbox = ctk.CTkTextbox(self, wrap="word", font=mono_font(10)) self.logbox.pack(fill="both", expand=True, padx=24, pady=(0, 20)) - self._sync_from_state() + self._sync_from_config() self._refresh_log() self.after(1000, self._tick) - def _sync_from_state(self): - host = self.app_state.server_host if self.app_state else "127.0.0.1" - port = self.app_state.server_port if self.app_state else 1234 + # ---------- конфиг/состояние ---------- + def _server_conf(self): + try: + return self.engine.config.setdefault("server", {}) + except Exception: + return {} + + def _sync_from_config(self): + conf = self._server_conf() + host = conf.get("host") or (self.app_state.server_host if self.app_state else "127.0.0.1") + port = conf.get("port") or (self.app_state.server_port if self.app_state else 1234) + token = conf.get("token") or "" + if not token: + token = secrets.token_urlsafe(18) + conf["token"] = token self.host_entry.delete(0, "end") self.host_entry.insert(0, str(host)) self.port_entry.delete(0, "end") self.port_entry.insert(0, str(port)) + self.token_entry.delete(0, "end") + self.token_entry.insert(0, token) + if self.app_state: + self.app_state.server_host = str(host) + self.app_state.server_port = int(port) self._update_status() + self._update_endpoint() - def _update_status(self): - running = bool(self.app_state and self.app_state.server_running) - self.status_label.configure(text=f"Статус: {'работает' if running else 'остановлен'}") + def _apply_to_config(self): + conf = self._server_conf() + conf["host"] = self.host_entry.get().strip() or "127.0.0.1" + try: + conf["port"] = int(self.port_entry.get().strip()) + except Exception: + conf["port"] = 1234 + conf["token"] = self.token_entry.get().strip() + try: + self.engine.save_config() + except Exception: + pass + if self.app_state: + self.app_state.server_host = conf["host"] + self.app_state.server_port = conf["port"] + self._update_endpoint() def apply_address(self): - if not self.app_state: - return - host = self.host_entry.get().strip() or "127.0.0.1" - try: - port = int(self.port_entry.get().strip()) - except Exception: - port = self.app_state.server_port - self.app_state.server_host = host - self.app_state.server_port = port - self.app_state.server_log(f"Адрес обновлён: {host}:{port}") + self._apply_to_config() + if self.app_state: + self.app_state.server_log( + f"Адрес обновлён: {self.app_state.server_host}:{self.app_state.server_port}" + ) self._refresh_log() + self._update_status() + if self._server is not None: + self.status_label.configure(text="Статус: перезапустите сервер, чтобы применить адрес") + + def rotate_token(self): + token = secrets.token_urlsafe(18) + self.token_entry.delete(0, "end") + self.token_entry.insert(0, token) + self._apply_to_config() + if self.app_state: + self.app_state.server_log("Токен обновлён") + self._refresh_log() + + # ---------- запуск/остановка ---------- + def _models_for_api(self): + try: + models = self.engine.list_models() + out = [{"id": m.id, "name": m.name or m.id} for m in models] + if out: + return out + except Exception: + pass + name = (self.app_state.current_model_name if self.app_state else "") or "xenith" + return [{"id": name, "name": name}] + + def _chat_for_api(self, messages, params, on_token): + return self.engine.chat_sync(messages, params, on_token=on_token) def start(self): if not self.app_state: return - self.apply_address() - if not self.app_state.server_running: - self.app_state.server_running = True - self.app_state.server_started_at = time.time() - self.app_state.server_log(f"Сервер запущен на {self.app_state.server_host}:{self.app_state.server_port}") - else: - self.app_state.server_log("Старт: сервер уже работает") + if self._server is not None and self._server.is_running: + return + self._apply_to_config() + conf = self._server_conf() + try: + server = ApiServer( + self._chat_for_api, + self._models_for_api, + host=conf.get("host", "127.0.0.1"), + port=int(conf.get("port", 1234)), + token=conf.get("token", ""), + ) + except Exception as e: + self.status_label.configure(text=f"Статус: ошибка — {e}") + return + server.log_callback = self._on_server_log + try: + server.start() + except Exception as e: + self.status_label.configure(text=f"Статус: ошибка — {e}") + if self.app_state: + self.app_state.server_log(f"Ошибка запуска: {e}") + self._refresh_log() + return + self._server = server + self.app_state.server_running = True + self.app_state.server_started_at = time.time() + self.app_state.server_log( + f"Сервер запущен: http://{conf.get('host')}:{conf.get('port')}" + ) self._update_status() self._refresh_log() def stop(self): - if not self.app_state: - return - if self.app_state.server_running: + if self._server is not None: + try: + self._server.stop() + except Exception: + pass + self._server = None + if self.app_state: self.app_state.server_running = False - self.app_state.server_log("Сервер остановлен") self.app_state.server_started_at = None - else: - self.app_state.server_log("Стоп: сервер уже остановлен") + self.app_state.server_log("Сервер остановлен") self._update_status() self._refresh_log() + def _on_server_log(self, line: str): + try: + self.app.post_ui(lambda: self._append_server_log(line)) + except Exception: + pass + + def _append_server_log(self, line: str): + if self.app_state: + self.app_state.server_log(str(line)[:400]) + self._refresh_log() + def clear_log(self): if self.app_state: self.app_state.server_logs.clear() self._refresh_log() + # ---------- UI ---------- + def _update_status(self): + running = bool(self._server is not None and self._server.is_running) + if self.app_state: + self.app_state.server_running = running + self.status_label.configure( + text=f"Статус: {'работает' if running else 'остановлен'}", + text_color=(c("success") if running else c("text_dim")), + ) + self.btn_start.configure(state=("disabled" if running else "normal")) + self.btn_stop.configure(state=("normal" if running else "disabled")) + + def _local_ip(self): + try: + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + s.connect(("8.8.8.8", 80)) + ip = s.getsockname()[0] + s.close() + return ip + except Exception: + return "127.0.0.1" + + def _update_endpoint(self): + host = self.host_entry.get().strip() or "127.0.0.1" + try: + port = int(self.port_entry.get().strip()) + except Exception: + port = 1234 + shown = "127.0.0.1" if host in ("0.0.0.0", "::") else host + lan = self._local_ip() + self.endpoint_label.configure( + text=f"OpenAI: http://{shown}:{port}/v1 · Ollama: http://{shown}:{port} · LAN: http://{lan}:{port}" + ) + def _refresh_log(self): self.logbox.delete("1.0", "end") if self.app_state: @@ -111,7 +273,8 @@ class ServerView(ViewBase): if not getattr(self, "_alive", True): return self._update_status() - if self.app_state and self.app_state.server_running and self.app_state.server_started_at: + if (self.app_state and self.app_state.server_running + and self.app_state.server_started_at): delta = int(time.time() - self.app_state.server_started_at) m, s = divmod(delta, 60) h, m = divmod(m, 60) @@ -122,3 +285,11 @@ class ServerView(ViewBase): self.after(1000, self._tick) except Exception: pass + + def shutdown(self): + if self._server is not None: + try: + self._server.stop() + except Exception: + pass + self._server = None diff --git a/XUI/views/training.py b/XUI/views/training.py index f4f85be..731d208 100644 --- a/XUI/views/training.py +++ b/XUI/views/training.py @@ -22,6 +22,7 @@ class TrainingView(ViewBase): self._poll_job = None self._busy = False self._stage = "" + self._run_stage = "" if self.app_state is not None: self._loss_history = list(getattr(self.app_state, "training_loss", []) or []) self._graph_x = int(getattr(self.app_state, "training_graph_x", 0) or 0) @@ -38,6 +39,10 @@ class TrainingView(ViewBase): self._last_polled_step = None self._redraw_job = None self._graph_retry = False + try: + self._train_allowed = bool(self.engine and self.engine.can_train()) + except Exception: + self._train_allowed = False top = ctk.CTkFrame(self, fg_color="transparent") top.pack(fill="both", expand=True, padx=24, pady=(16, 10)) @@ -45,13 +50,51 @@ class TrainingView(ViewBase): top.grid_columnconfigure(1, weight=3) top.grid_rowconfigure(0, weight=1) - # ---------- Левая панель (управление) ---------- - left = ctk.CTkScrollableFrame(top) + # ---------- Левая панель: шаги обучения ---------- + left = ctk.CTkFrame(top, fg_color="transparent") left.grid(row=0, column=0, sticky="nsew", padx=(0, 8)) + self._left = left + + self._stage_order = ["data", "pre", "ft", "export"] + self._stage_labels = { + "data": "Данные", + "pre": "Предобучение", + "ft": "Дообучение", + "export": "Экспорт", + } + self._stage_by_label = {v: k for k, v in self._stage_labels.items()} + self._stage_frames = {} + try: + start_stage = getattr(self.app_state, "training_stage", "data") if self.app_state else "data" + except Exception: + start_stage = "data" + self._stage = start_stage if start_stage in self._stage_order else "data" + + self.stepbar = ctk.CTkSegmentedButton( + left, values=list(self._stage_labels.values()), + command=self.show_stage, height=32, font=ui_font(11), + fg_color=c("card"), selected_color=c("accent_soft"), + selected_hover_color=c("control_hover"), + unselected_color=c("card"), unselected_hover_color=c("card_hover"), + text_color=c("text"), + ) + self.stepbar.pack(fill="x", padx=8, pady=(0, 8)) + + self.engine_notice = ctk.CTkLabel( + left, text="", font=ui_font(11), text_color=c("warn"), + anchor="w", justify="left", wraplength=520, + ) + + self._footer = ctk.CTkFrame(left, fg_color="transparent") + self._footer.pack(side="bottom", fill="x", padx=8, pady=(4, 6)) + + self._stage_area = ctk.CTkScrollableFrame(left, fg_color="transparent", corner_radius=0) + self._stage_area.pack(fill="both", expand=True, padx=0, pady=0) # Архитектура / создание - arch = ctk.CTkFrame(left) - arch.pack(fill="x", padx=8, pady=8) + arch = ctk.CTkFrame(self._stage_area) + self._stage_frames["data"] = arch + self._arch_frame = arch ctk.CTkLabel(arch, text="1. Модель и корпус", font=ui_font(13), text_color=c("text")).pack(anchor="w", padx=14, pady=(12, 8)) corpus_row = ctk.CTkFrame(arch, fg_color="transparent") @@ -88,8 +131,8 @@ class TrainingView(ViewBase): ctk.CTkLabel(arch_actions, text="Создаёт модель в памяти, прогресс сбрасывается", font=ui_font(10), text_color=c("text_faint"), wraplength=220, justify="left", anchor="w").pack(side="left", padx=10) # Предобучение - pre = ctk.CTkFrame(left) - pre.pack(fill="x", padx=8, pady=8) + pre = ctk.CTkFrame(self._stage_area) + self._stage_frames["pre"] = pre ctk.CTkLabel(pre, text="2. Предобучение", font=ui_font(13), text_color=c("text")).pack(anchor="w", padx=14, pady=(12, 8)) pre_grid = ctk.CTkFrame(pre, fg_color="transparent") @@ -106,8 +149,8 @@ class TrainingView(ViewBase): ctk.CTkLabel(pre_actions, text="Обучение на корпусе после создания модели", font=ui_font(10), text_color=c("text_faint"), wraplength=220, justify="left", anchor="w").pack(side="left", padx=10) # Дообучение - ft = ctk.CTkFrame(left) - ft.pack(fill="x", padx=8, pady=8) + ft = ctk.CTkFrame(self._stage_area) + self._stage_frames["ft"] = ft ctk.CTkLabel(ft, text="3. Дообучение на диалогах", font=ui_font(13), text_color=c("text")).pack(anchor="w", padx=14, pady=(12, 8)) ds_row = ctk.CTkFrame(ft, fg_color="transparent") @@ -136,8 +179,8 @@ class TrainingView(ViewBase): ctk.CTkLabel(ft_actions, text="Нужна модель и датасет диалогов", font=ui_font(10), text_color=c("text_faint"), wraplength=220, justify="left", anchor="w").pack(side="left", padx=10) # Сохранение / управление - savef = ctk.CTkFrame(left) - savef.pack(fill="x", padx=8, pady=8) + savef = ctk.CTkFrame(self._stage_area) + self._stage_frames["export"] = savef ctk.CTkLabel(savef, text="4. Сохранение и управление", font=ui_font(13), text_color=c("text")).pack(anchor="w", padx=14, pady=(12, 8)) path_row = ctk.CTkFrame(savef, fg_color="transparent") @@ -156,10 +199,10 @@ class TrainingView(ViewBase): self.btn_clear_graph = ctk.CTkButton(ctl, text="Очистить график", width=148, height=34, command=self.clear_graph) self.btn_clear_graph.pack(side="left", padx=8) - self.status_label = ctk.CTkLabel(left, text="Статус: готово", anchor="w", justify="left", font=ui_font(11), text_color=c("text_dim")) - self.status_label.pack(fill="x", padx=12, pady=(4, 2)) - self.progress_label = ctk.CTkLabel(left, text="", anchor="w", justify="left", font=mono_font(10), text_color=c("text_faint")) - self.progress_label.pack(fill="x", padx=12, pady=(0, 12)) + self.status_label = ctk.CTkLabel(self._footer, text="Статус: готово", anchor="w", justify="left", font=ui_font(11), text_color=c("text_dim")) + self.status_label.pack(fill="x", padx=4, pady=(2, 2)) + self.progress_label = ctk.CTkLabel(self._footer, text="", anchor="w", justify="left", font=mono_font(10), text_color=c("text_faint")) + self.progress_label.pack(fill="x", padx=4, pady=(0, 2)) # ---------- Правая панель (график) ---------- right = ctk.CTkFrame(top) @@ -171,8 +214,34 @@ class TrainingView(ViewBase): self.canvas = tk.Canvas(right, bg=c("card"), highlightthickness=0) self.canvas.grid(row=1, column=0, sticky="nsew", padx=12, pady=(0, 12)) self.canvas.bind("", lambda e: self.draw_loss_graph()) + self.show_stage(self._stage_labels[self._stage]) self.after(150, self._update_corpus_info) self.draw_loss_graph() + self._apply_engine_gate() + + # ---------- шаги ---------- + def show_stage(self, label_or_key): + key = self._stage_by_label.get(label_or_key, label_or_key) + if key not in self._stage_frames: + key = "data" + self._stage = key + for k, frame in self._stage_frames.items(): + try: + if k == key: + frame.pack(fill="x", padx=8, pady=8) + else: + frame.pack_forget() + except Exception: + pass + try: + self.stepbar.set(self._stage_labels[key]) + except Exception: + pass + try: + if self.app_state is not None: + self.app_state.training_stage = key + except Exception: + pass # ---------- helpers ---------- def _mk_entry(self, parent, label, default, row, col, width=90): @@ -254,19 +323,58 @@ class TrainingView(ViewBase): def set_busy(self, busy: bool): self._busy = busy - st = "disabled" if busy else "normal" - for b in (self.btn_create, self.btn_pretrain, self.btn_finetune, self.btn_save, self.btn_clear_graph): + allowed = bool(getattr(self, "_train_allowed", False)) + st = "disabled" if busy or not allowed else "normal" + for b in (self.btn_create, self.btn_pretrain, self.btn_finetune, self.btn_save): try: b.configure(state=st) except Exception: pass + try: + self.btn_clear_graph.configure(state="normal") + except Exception: + pass self.btn_stop.configure(state=("normal" if busy else "disabled")) + def _apply_engine_gate(self): + try: + self._train_allowed = bool(self.engine and self.engine.can_train()) + except Exception: + self._train_allowed = False + if self._train_allowed: + try: + self.engine_notice.pack_forget() + except Exception: + pass + self.set_busy(self._busy) + else: + try: + name = self.engine.active_name() if self.engine else "—" + except Exception: + name = "—" + try: + self.engine_notice.configure( + text=f"Обучение доступно только в движке Xenith. Сейчас активен: {name}" + ) + if not self.engine_notice.winfo_ismapped(): + self.engine_notice.pack(fill="x", padx=14, pady=(0, 8), + before=self.stepbar) + except Exception: + pass + for b in (self.btn_create, self.btn_pretrain, self.btn_finetune, self.btn_save): + try: + b.configure(state="disabled") + except Exception: + pass + + def on_show(self): + self._apply_engine_gate() + def _get_model(self): # приоритет: модель, с которой сейчас работаем, иначе загруженная в движок if self._active_model is not None: return self._active_model - if self.engine and self.engine.model is not None: + if self.engine and self.engine.can_train() and self.engine.model is not None: return self.engine.model return None @@ -490,6 +598,9 @@ class TrainingView(ViewBase): def create_only(self): if self._busy: return + if not getattr(self, "_train_allowed", False): + self.set_status("обучение доступно только в движке Xenith") + return if self._blocked_by_other(): self.set_status("дождитесь завершения генерации/загрузки модели") return @@ -528,7 +639,7 @@ class TrainingView(ViewBase): def _on_model_ready(self, model, info: str, reset_graph: bool = False): self._active_model = model if self.engine: - self.engine.model = model + self.engine.set_native_model(model) if self.app_state: self.app_state.model_loaded = True if not self.app_state.current_model_name: @@ -543,6 +654,9 @@ class TrainingView(ViewBase): def start_pretrain(self): if self._busy: return + if not getattr(self, "_train_allowed", False): + self.set_status("обучение доступно только в движке Xenith") + return if self._blocked_by_other(): self.set_status("дождитесь завершения генерации/загрузки модели") return @@ -592,7 +706,7 @@ class TrainingView(ViewBase): model = xe.Model(vocab=vocab, embd=embd, layers=layers, heads=heads, ctx=ctx, seed=seed, corpus_text=corpus) self._active_model = model if self.engine: - self.engine.model = model + self.engine.set_native_model(model) if self.app_state: self.app_state.log(f"[TRAIN/UI] {self._model_summary(model, 'Модель создана')}") self.ui(lambda: continuation(model)) @@ -603,7 +717,9 @@ class TrainingView(ViewBase): def _run_train(self, model, corpus, steps, lr, batch, block): self._active_model = model - self._stage = "pretrain" + self._run_stage = "pretrain" + if self.engine: + self.engine.set_training(True) self._last_polled_step = None self.set_busy(True) self.set_status("предобучение") @@ -644,6 +760,9 @@ class TrainingView(ViewBase): def start_finetune(self): if self._busy: return + if not getattr(self, "_train_allowed", False): + self.set_status("обучение доступно только в движке Xenith") + return if self._blocked_by_other(): self.set_status("дождитесь завершения генерации/загрузки модели") return @@ -662,7 +781,9 @@ class TrainingView(ViewBase): return self._active_model = model - self._stage = "finetune" + self._run_stage = "finetune" + if self.engine: + self.engine.set_training(True) self._last_polled_step = None self.set_busy(True) self.set_status("дообучение") @@ -721,14 +842,22 @@ class TrainingView(ViewBase): if step != self._last_polled_step: self._last_polled_step = step if loss and loss > 0: - self.add_loss_point(loss, self._stage or "other") + self.add_loss_point(loss, self._run_stage or "other") pct = "" try: - pct = f"{float(progress) * 100:.1f}%" + pct = f" · {float(progress) * 100:.0f}%" except Exception: pass - self.progress_label.configure(text=f"{self._stage} | phase={phase} step={step} loss={loss} {pct}") + stage_ru = {"pretrain": "Предобучение", "finetune": "Дообучение"}.get( + self._run_stage, self._run_stage) + try: + loss_txt = f"{float(loss):.4f}" + except Exception: + loss_txt = str(loss) + self.progress_label.configure( + text=f"{stage_ru} · шаг {step} · loss {loss_txt}{pct}" + ) if is_running: self._schedule_poll(100) @@ -737,7 +866,9 @@ class TrainingView(ViewBase): if err: self._fail(err) return - self._finalize_stage(f"{self._stage}: phase={phase} step={step} loss={loss}") + stage_ru = {"pretrain": "Предобучение", "finetune": "Дообучение"}.get( + self._run_stage, self._run_stage) + self._finalize_stage(f"{stage_ru} · шаг {step} · loss {float(loss):.4f}") except Exception as e: self._fail(str(e)) @@ -756,13 +887,15 @@ class TrainingView(ViewBase): self._cancel_poll() model = self._active_model or self._get_model() if model is not None and self.engine: - self.engine.model = model + self.engine.set_native_model(model) if self.app_state and model is not None: self.app_state.model_loaded = True if not self.app_state.current_model_name: self.app_state.current_model_name = "in-memory (ui)" self.app_state.log(f"[TRAIN/UI] Этап завершён: {info}") self._train_state = None + if self.engine: + self.engine.set_training(False) self.set_busy(False) self.set_status("готово") self.progress_label.configure(text=info) @@ -770,6 +903,8 @@ class TrainingView(ViewBase): def _fail(self, msg: str): self._cancel_poll() self._train_state = None + if self.engine: + self.engine.set_training(False) self.set_busy(False) self.set_status("ошибка") self.progress_label.configure(text=msg) @@ -777,6 +912,9 @@ class TrainingView(ViewBase): self.app_state.log(f"[TRAIN/UI] Ошибка: {msg}") def save_current_model(self): + if not getattr(self, "_train_allowed", False): + self.set_status("сохранение доступно только для Xenith") + return if self._blocked_by_other(): self.set_status("дождитесь завершения генерации/загрузки модели") return diff --git a/XUI/views/user.py b/XUI/views/user.py index 41dd4d5..d042493 100644 --- a/XUI/views/user.py +++ b/XUI/views/user.py @@ -62,7 +62,7 @@ class UserView(ViewBase): def _open_ui_settings(self): try: if self.app: - self.app.open_settings_popup() + self.app.open_settings("appearance") except Exception as e: if self.app_state: self.app_state.log(f"Ошибка открытия настроек: {e}") diff --git a/xenith_server.py b/xenith_server.py new file mode 100644 index 0000000..97fe095 --- /dev/null +++ b/xenith_server.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Автономный HTTP-сервер Xenith для телефонного приложения и внешних клиентов. + +Запуск: + python3 xenith_server.py --model models/ui_chat_model.xnh --host 0.0.0.0 --port 1234 + python3 xenith_server.py --list + +Сервер отдаёт OpenAI-совместимый (/v1) и Ollama-совместимый (/api) API. +Токен можно задать через --token; иначе он будет сгенерирован и напечатан. +""" + +import argparse +import os +import secrets +import sys + +import xenith_engine as xe + +from XUI.core.api_server import ApiServer + + +def find_models(): + dirs = [os.path.join(os.getcwd(), "models"), os.path.join(os.getcwd(), "xenith", "models")] + out = [] + seen = set() + for d in dirs: + try: + for name in sorted(os.listdir(d)): + full = os.path.abspath(os.path.join(d, name)) + if os.path.isfile(full) and full not in seen: + seen.add(full) + out.append(full) + except Exception: + pass + return out + + +def transcript(messages): + parts = [] + for m in messages or []: + if not isinstance(m, dict): + continue + role = str(m.get("role", "user")) + content = str(m.get("content", "")) + if role == "system": + parts.append(f"System: {content}") + elif role == "assistant": + parts.append(f"Assistant: {content}") + else: + parts.append(f"User: {content}") + parts.append("Assistant:") + return "\n".join(parts) + + +def main(argv=None): + p = argparse.ArgumentParser(description="Xenith HTTP API server") + p.add_argument("--model", default="", help="путь к .xnh модели") + p.add_argument("--host", default="127.0.0.1") + p.add_argument("--port", type=int, default=1234) + p.add_argument("--token", default="", help="Bearer-токен (по умолчанию сгенерируется)") + p.add_argument("--list", action="store_true", help="показать доступные модели") + args = p.parse_args(argv) + + models = find_models() + if args.list: + for m in models: + print(m) + return 0 + if not args.model: + if not models: + print("Модели .xnh не найдены. Укажите --model", file=sys.stderr) + return 1 + args.model = models[0] + if not os.path.isfile(args.model): + print(f"Файл модели не найден: {args.model}", file=sys.stderr) + return 1 + + print(f"Загрузка {args.model} …", flush=True) + model = xe.Model(args.model) + token = args.token or secrets.token_urlsafe(18) + + def chat_callable(messages, params, on_token): + prompt = transcript(messages) + + def cb(_tid, piece): + if on_token and piece: + on_token(str(piece)) + + res = model.generate( + prompt, + n=int(params.get("n", params.get("max_tokens", 256))), + temperature=float(params.get("temperature", 0.7)), + top_p=float(params.get("top_p", 0.9)), + on_token=cb, + ) + text = getattr(res, "text", res) + return "" if text is None else str(text) + + def models_callable(): + return [{"id": os.path.basename(m), "name": os.path.basename(m)} for m in models] + + server = ApiServer(chat_callable, models_callable, + host=args.host, port=args.port, token=token) + server.log_callback = lambda line: print(f"[api] {line}", flush=True) + try: + server.start() + except Exception as e: + print(f"Не удалось запустить сервер: {e}", file=sys.stderr) + return 1 + + shown = "127.0.0.1" if args.host in ("0.0.0.0", "::") else args.host + print(f"OpenAI API: http://{shown}:{args.port}/v1") + print(f"Ollama API: http://{shown}:{args.port}") + print(f"Токен: {token}") + print("Ctrl+C — остановить.") + try: + while True: + import time + time.sleep(3600) + except KeyboardInterrupt: + pass + finally: + server.stop() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())