"""Terminal UI: streaming output, worker dashboard, prompt and commands.""" from __future__ import annotations import asyncio import shutil import sys import time from pathlib import Path from typing import Any from collections.abc import Iterable from prompt_toolkit import PromptSession from prompt_toolkit.completion import Completer, Completion from prompt_toolkit.history import FileHistory from prompt_toolkit.styles import Style from rich.box import ROUNDED, SIMPLE from rich.console import Console, Group from rich.live import Live from rich.markdown import Markdown from rich.panel import Panel from rich.table import Table from rich.text import Text from .config import Config from .events import Event from .models import ModelInfo from .session import Session from .utils import format_cost, format_duration, format_tokens, truncate from .worker import Worker class SlashCompleter(Completer): COMMANDS = [ "help", "models", "providers", "model", "worker-model", "retry", "fork", "delete", "workers", "plan", "stats", "context", "compact", "cancel", "workspace", "new", "sessions", "resume", "config", "quit", ] def __init__(self, get_models) -> None: self.get_models = get_models def get_completions(self, document, complete_event): text = document.text_before_cursor if not text.startswith("/"): return body = text[1:] if " " not in body: for command in self.COMMANDS: if command.startswith(body): yield Completion(f"/{command}", start_position=-len(text)) return command, _, arg = body.partition(" ") if command in {"model", "worker-model", "resume"}: source = self.get_models() if command != "resume" else [] for item in source: value = item.id if command != "resume" else str(item) if value.startswith(arg.strip()): yield Completion(value, start_position=-len(arg)) class UI: def __init__(self, config: Config, *, no_color: bool = False) -> None: self.config = config self.is_tty = sys.stdout.isatty() self.console = Console( no_color=no_color or not self.is_tty, highlight=False, soft_wrap=True, width=shutil.get_terminal_size((120, 30)).columns if self.is_tty else None, ) self.session: Session | None = None self.spinner: Any = None self.live: Live | None = None self._dashboard_task: asyncio.Task[Any] | None = None self._main_live: Live | None = None self._last_main_render = 0.0 self.deferred: list[Event] = [] self.saw_main_text = False self.main_text = "" self.text_open = False self.prompt: PromptSession[str] | None = None self._models: list[ModelInfo] = [] self._models_loaded = False self._sleep_started: float | None = None self._sleep_targets: list[str] = [] # ------------------------------------------------------------------ setup def attach(self, session: Session) -> None: self.session = session def set_models(self, models: list[ModelInfo]) -> None: self._models = models self._models_loaded = True def get_models(self) -> list[ModelInfo]: return self._models @property def models_loaded(self) -> bool: return self._models_loaded def print_banner(self, session: Session, auth_label: str) -> None: c = self.console c.print() logo = Text() logo.append(" AiRouter", style="bold #22d3ee") logo.append(" главный агент следит за воркерами", style="dim") c.print(logo) grid = Table.grid(padding=(0, 2)) grid.add_column(style="dim", justify="right") grid.add_column(style="white") grid.add_row("main", session.config.orchestrator_model) grid.add_row("worker", session.config.worker_model) grid.add_row( "roles", ", ".join(session.config.roles.keys()), ) grid.add_row("dir", str(session.cwd)) grid.add_row("auth", auth_label) grid.add_row("session", session.id) c.print( Panel( grid, border_style="grey30", box=ROUNDED, padding=(0, 1), title="[dim]сессия[/dim]", title_align="left", ) ) c.print( "[dim]Опишите цель. Главная модель разобьёт работу на задачи и запустит " "воркеров. /help — команды.[/dim]" ) c.print() def print_resumed(self, session: Session) -> None: self.console.print( f"[dim]Продолжена сессия [white]{session.id}[/white] · " f"{len(session.main_messages)} сообщений в контексте · " f"воркеров: {len(session.workers)}[/dim]" ) def print_help(self) -> None: table = Table( title="Команды", box=SIMPLE, border_style="grey30", title_style="bold", title_justify="left", show_header=False, padding=(0, 2), ) table.add_column(style="cyan", no_wrap=True) table.add_column(style="white") rows = [ ("/help", "эта справка"), ("/models", "список моделей всех провайдеров"), ("/providers", "провайдеры, локальные серверы и их модели"), ("/model ", "сменить главную модель"), ("/worker-model ", "сменить модель воркеров по умолчанию"), ("/workers [id]", "статусы воркеров; с id — полный отчёт"), ("/plan", "план задач и подзадач"), ("/stats", "расход токенов и стоимость"), ("/context", "размер контекста главной модели"), ("/compact", "сжать контекст (полный транскрипт сохраняется)"), ("/cancel", "остановить всех воркеров"), ("/workspace ", "сменить папку проекта"), ("/retry", "повторить последний запрос после ошибки"), ("/fork [N]", "создать ветку чата"), ("/delete ", "удалить сообщение по номеру"), ("/new", "новая сессия"), ("/sessions", "сессии в этой папке"), ("/resume ", "переключиться на сессию"), ("/config", "конфигурация и пути"), ("/quit", "выход"), ] for command, description in rows: table.add_row(command, description) self.console.print(table) if self.session: self.console.print( "[dim]Роли:[/dim] " + session_role_menu(self.session.config) ) # ------------------------------------------------------------------ prompt def _history_path(self) -> Path: path = Path.home() / ".local" / "state" / "airouter" / "history" path.parent.mkdir(parents=True, exist_ok=True) return path def _style(self) -> Style: return Style.from_dict( { "prompt": "bold #22d3ee", "bottom-toolbar": "bg:#111827 #9ca3af", } ) def _toolbar(self) -> str: if not self.session: return "" running = len(self.session.running_workers()) pieces = [ f" {self.session.config.orchestrator_model}", f"workers {running}", f"{self.session.id}", f"{self.session.cwd}", ] return " · ".join(pieces) + " " async def prompt_text(self) -> str: if self.prompt is None: self.prompt = PromptSession( history=FileHistory(str(self._history_path())), completer=SlashCompleter(self.get_models), style=self._style(), complete_while_typing=False, ) return await self.prompt.prompt_async( [("class:prompt", "❯ ")], bottom_toolbar=self._toolbar, ) # ------------------------------------------------------------------ events def on_event(self, event: Event) -> None: if not self.is_tty: self._on_event_plain(event) return try: self._on_event(event) except Exception: # Never break the agent because of rendering. pass def _on_event_plain(self, event: Event) -> None: t = event.type data = event.data if t == "main_tool_call": self.console.print(f"[main] {data.get('name')}({data.get('args', '')})", markup=False) elif t == "worker_spawned": self.console.print( f"[{event.worker_id}] spawned {data.get('name')} · {data.get('workspace')}", markup=False, ) elif t == "worker_done": self.console.print( f"[{event.worker_id}] done in {format_duration(data.get('duration'))}", markup=False, ) elif t == "worker_failed": self.console.print( f"[{event.worker_id}] FAILED: {data.get('error')}", markup=False ) elif t == "worker_cancelled": self.console.print( f"[{event.worker_id}] cancelled: {data.get('error', '')}", markup=False ) elif t == "worker_continued": self.console.print(f"[{event.worker_id}] continuing", markup=False) elif t == "worker_tool_call": self.console.print( f"[{event.worker_id}] {data.get('name')}: {data.get('args', '')}", markup=False, ) elif t == "main_sleep": targets = ", ".join(str(item.get("id")) for item in (data.get("waiting_for") or [])) self.console.print( f"[main] sleeping until workers finish: {targets}", markup=False ) elif t == "main_wake": completed = ", ".join(data.get("completed") or []) still = ", ".join(data.get("still_running") or []) if completed: self.console.print(f"[main] woke up: {completed}", markup=False) elif still: self.console.print( f"[main] woke up (timeout), still running: {still}", markup=False ) elif t == "main_text_delta": if not self.saw_main_text: self.console.print(Text("main › ", style="bold #22d3ee"), end="") self.saw_main_text = True self.console.print(data.get("delta", ""), end="", markup=False, highlight=False) elif t == "main_turn_done": self.console.print() elif t == "notice": self.console.print(f"[notice] {data.get('text')}", markup=False) def _on_event(self, event: Event) -> None: t = event.type d = event.data if t == "main_turn_started": self._stop_main_live() self.saw_main_text = False self.main_text = "" self.text_open = False elif t == "main_step": self._start_spinner("main думает…") elif t == "main_text_delta": self._stop_spinner() delta = d.get("delta", "") if not delta: return if not self.text_open: self.text_open = True self.main_text = "" if not self.is_tty: self.console.print(Text("main › ", style="bold #22d3ee"), end="") self.main_text += delta self.saw_main_text = True if self.is_tty: self._render_main_live() else: self.console.print(Text(delta), end="") elif t == "main_tool_call": self._stop_spinner() self._close_text() self._flush_deferred() args = d.get("args", "") self.console.print( Text(" ▸ ", style="cyan") + Text(str(d.get("name")), style="bold cyan") + (Text(f"({args})", style="dim") if args else Text("", style="dim")) ) elif t == "main_tool_result": if d.get("ok", True) and d.get("name") in { "spawn_worker", "wait_for_workers", "message_worker", }: return ok = bool(d.get("ok", True)) summary = str(d.get("summary", "")) if summary: marker = Text(" ✓ ", style="green") if ok else Text(" ✗ ", style="red") self.console.print(marker + Text(truncate(summary, 180), style="dim")) elif t == "main_sleep": self._stop_spinner() self._close_text() self._flush_deferred() targets = d.get("waiting_for") or [] self._sleep_targets = [str(item.get("id")) for item in targets] self._sleep_started = time.monotonic() names = ", ".join(str(item.get("id")) for item in targets) self.console.print( Text(" ⏸ ", style="yellow") + Text(f"main спит — ждёт: {names}", style="yellow") ) self._start_dashboard() elif t == "main_wake": self._stop_dashboard() completed = d.get("completed") or [] still = d.get("still_running") or [] self._flush_deferred() if completed: self.console.print( Text(" ▶ ", style="bold cyan") + Text(f"main проснулся — готовы: {', '.join(completed)}", style="bold cyan") ) elif still: self.console.print( Text(" ▶ ", style="yellow") + Text(f"main проснулся — ещё работают: {', '.join(still)}", style="yellow") ) elif t == "worker_spawned": if not self.live and not self._main_live: self.console.print( Text(" + ", style="magenta") + Text(str(event.worker_id), style="bold magenta") + Text( f" {d.get('name')} · {d.get('role')} · {d.get('model')} · {d.get('workspace')}", style="dim", ) ) elif t == "worker_started": pass elif t == "worker_tool_call": if not self.live and not self._main_live: args = str(d.get("args", "")) self.console.print( Text(f" {event.worker_id} ", style="magenta") + Text("⚙ ", style="dim") + Text(str(d.get("name")), style="magenta") + (Text(f": {truncate(args, self.config.ui.max_worker_line)}", style="dim") if args else Text("")) ) elif t == "worker_tool_result": if not self.live and not self._main_live and not d.get("ok", True): self.console.print( Text(f" {event.worker_id} ", style="magenta") + Text("✗ ", style="red") + Text(truncate(str(d.get("summary", "")), 160), style="red") ) elif t in {"worker_done", "worker_failed", "worker_cancelled"}: if self.live or self._main_live: self.deferred.append(event) else: self._print_worker_finished(event) elif t == "worker_continued": if not self.live and not self._main_live: self.console.print( Text(f" ↻ {event.worker_id} ", style="magenta") + Text("продолжает работу", style="dim") ) elif t == "notice": if not self._main_live and not self.live: self.console.print(Text(f" · {d.get('text')}", style="dim")) elif t == "error": self.console.print(Panel(str(d.get("text")), border_style="red")) elif t == "compacted": self._stop_spinner() self.console.print( Text(" ◇ контекст сжат. ", style="cyan") + Text(f"Бэкап: {d.get('backup')}", style="dim") ) elif t == "main_turn_done": self._stop_spinner() self._stop_dashboard() self._close_text() self._flush_deferred() final_text = str(d.get("text") or "") if not self.saw_main_text and final_text: self.console.print(Markdown(final_text)) elif self.saw_main_text and final_text: streamed = self.main_text.strip() final_clean = final_text.strip() if final_clean != streamed: extra = ( final_clean[len(streamed):].strip() if final_clean.startswith(streamed) else final_clean ) if extra: self.console.print(Text(extra, style="yellow")) self.console.print() # ------------------------------------------------------------------ rendering helpers def _start_spinner(self, message: str) -> None: if self.live: return self._stop_spinner() self.spinner = self.console.status( Text(f" {message}", style="cyan"), spinner="dots", spinner_style="cyan" ) try: self.spinner.start() except Exception: self.spinner = None def _stop_spinner(self) -> None: if self.spinner: try: self.spinner.stop() except Exception: pass self.spinner = None def _close_text(self) -> None: if not self.text_open: return if self.is_tty: self._stop_main_live() if self.main_text.strip(): self.console.print( Group( Text("main › ", style="bold #22d3ee"), Markdown(self.main_text), ) ) else: self.console.print() self.text_open = False if self.deferred: self._flush_deferred() def _render_main_live(self) -> None: if not self.is_tty: return group = Group( Text("main › ", style="bold #22d3ee"), Markdown(self.main_text), ) now = time.monotonic() if self._main_live is None: self._main_live = Live( group, console=self.console, refresh_per_second=8, transient=True, vertical_overflow="visible", ) try: self._main_live.start(refresh=True) self._last_main_render = now except Exception: self._main_live = None elif now - self._last_main_render >= 0.12: try: self._main_live.update(group, refresh=True) self._last_main_render = now except Exception: self._stop_main_live() def _stop_main_live(self) -> None: if self._main_live: try: self._main_live.stop() except Exception: pass self._main_live = None def _start_dashboard(self) -> None: if self.live or not self.is_tty or not self.session: return try: self.live = Live( self._dashboard_renderable(), console=self.console, refresh_per_second=6, transient=True, vertical_overflow="visible", ) self.live.start(refresh=True) except Exception: self.live = None return self._dashboard_task = asyncio.create_task(self._dashboard_loop()) async def _dashboard_loop(self) -> None: try: while self.live is not None: self.live.update(self._dashboard_renderable(), refresh=True) await asyncio.sleep(0.25) except asyncio.CancelledError: pass except Exception: pass def _stop_dashboard(self) -> None: task = getattr(self, "_dashboard_task", None) if task is not None: task.cancel() self._dashboard_task = None if self.live: try: self.live.stop() except Exception: pass self.live = None def _dashboard_renderable(self) -> Group: if not self.session: return Group() table = Table.grid(padding=(0, 2)) table.add_column(no_wrap=True) table.add_column(no_wrap=True) table.add_column(no_wrap=True) table.add_column(no_wrap=True) table.add_column(overflow="ellipsis", no_wrap=True) frames = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏" frame = frames[int(time.monotonic() * 10) % len(frames)] running = [w for w in self.session.workers.values() if not w.is_terminal] for worker in running: table.add_row( Text(f"{frame} {worker.id}", style="magenta"), Text(worker.name, style="white"), Text(worker.status, style="yellow"), Text(format_duration(worker.duration), style="dim"), Text(worker.last_action, style="dim"), ) elapsed = time.monotonic() - (self._sleep_started or time.monotonic()) caption = Text( f"main спит · ждёт {len(running)} · {format_duration(elapsed)} · " "проснётся, как только воркер закончит", style="dim", ) if not running: caption = Text("main спит · завершение воркеров…", style="dim") return Group(table, caption) def _flush_deferred(self) -> None: for event in self.deferred: self._print_worker_finished(event) self.deferred.clear() def _print_worker_finished(self, event: Event) -> None: d = event.data wid = event.worker_id or "?" name = d.get("name", wid) duration = format_duration(d.get("duration")) files = d.get("files_changed") or [] if event.type == "worker_done": marker = Text(" ✓ ", style="green") label = Text(f"{wid} {name}", style="bold green") extra = f" · {duration}" if files: extra += f" · файлов: {len(files)}" self.console.print(marker + label + Text(extra, style="dim")) report = str(d.get("result") or "").strip().splitlines() if report: self.console.print(Text(f" {truncate(report[0], 160)}", style="dim")) elif event.type == "worker_failed": self.console.print( Text(" ✗ ", style="red") + Text(f"{wid} {name}", style="bold red") + Text(f" · {duration} · {truncate(str(d.get('error', '')), 200)}", style="red") ) else: self.console.print( Text(" ⊘ ", style="yellow") + Text(f"{wid} {name}", style="bold yellow") + Text(" · отменён", style="dim") ) # ------------------------------------------------------------------ tables def print_plan(self, session: Session) -> None: if not session.todos: self.console.print("[dim]Плана пока нет. Главная модель создаст его через update_plan.[/dim]") return table = Table(title="План", box=SIMPLE, border_style="grey30") table.add_column("", width=2) table.add_column("задача", overflow="fold") table.add_column("воркер", style="magenta") table.add_column("статус") icons = { "pending": "○", "in_progress": "◐", "done": "✓", "blocked": "!", "skipped": "–", } styles = { "pending": "dim", "in_progress": "yellow", "done": "green", "blocked": "red", "skipped": "dim", } for task in session.todos: status = str(task.get("status", "pending")) title = str(task.get("title", "")) subtasks = task.get("subtasks") or [] if subtasks: title += "\n" + "\n".join( f" {icons.get(str(sub.get('status', 'pending')), '○')} {sub.get('title', '')}" for sub in subtasks ) table.add_row( icons.get(status, "○"), title, str(task.get("worker_id") or ""), f"[{styles.get(status, 'white')}]{status}[/]", ) self.console.print(table) def print_workers(self, session: Session, worker_id: str | None = None) -> None: if worker_id: worker = session.workers.get(worker_id) if not worker: self.console.print(f"[red]Воркер {worker_id} не найден[/red]") return self.print_worker_report(worker) return if not session.workers: self.console.print("[dim]Воркеров ещё не было.[/dim]") return table = Table(title="Воркеры", box=SIMPLE, border_style="grey30") table.add_column("id", style="magenta", no_wrap=True) table.add_column("имя") table.add_column("роль") table.add_column("статус") table.add_column("время", justify="right") table.add_column("шаги", justify="right") table.add_column("файлы", justify="right") table.add_column("папка", overflow="fold") for w in session.workers.values(): status_style = { "done": "green", "failed": "red", "cancelled": "yellow", "interrupted": "yellow", "running": "cyan", "pending": "cyan", }.get(w.status, "white") table.add_row( w.id, w.name, w.role.name, f"[{status_style}]{w.status}[/{status_style}]", format_duration(w.duration), str(w.steps), str(len(w.files_changed)), str(w.workspace_path), ) self.console.print(table) def print_worker_report(self, worker: Worker) -> None: self.console.print( Panel( Text(worker.result or worker.error or "(отчёта нет)"), title=f"{worker.id} · {worker.name} · {worker.status}", subtitle=str(worker.report_path) if worker.report_path else None, border_style="green" if worker.status == "done" else "red", box=ROUNDED, padding=(0, 1), ) ) if worker.files_changed: self.console.print("[bold]Файлы:[/bold] " + ", ".join(worker.files_changed)) if worker.commands: self.console.print("[bold]Команды:[/bold]") for command in worker.commands[-8:]: self.console.print( Text( f" ${command.get('command')} → {command.get('exit_code')} " f"({command.get('duration')}s)", style="dim", ) ) def print_models( self, models: Iterable[ModelInfo], current_main: str, current_worker: str ) -> None: table = Table(title="Модели", box=SIMPLE, border_style="grey30") table.add_column("провайдер", style="magenta") table.add_column("id", style="cyan", no_wrap=True) table.add_column("контекст", justify="right") table.add_column("tools", justify="center") table.add_column("$ in/out", justify="right") table.add_column("", style="green") for model in models: marks = [] if model.id == current_main: marks.append("main") if model.id == current_worker: marks.append("worker") table.add_row( model.provider or "—", model.id, format_tokens(model.context or 0) if model.context else "—", "yes" if model.tools else "no", ( f"{model.input_price:g}/{model.output_price:g}" if model.input_price is not None else "—" ), ", ".join(marks), ) self.console.print(table) def print_sessions(self, sessions: list[dict[str, Any]], current: str | None) -> None: if not sessions: self.console.print("[dim]Сессий пока нет.[/dim]") return table = Table(title="Сессии", box=SIMPLE, border_style="grey30") table.add_column("id", style="cyan", no_wrap=True) table.add_column("обновлена") table.add_column("сообщений", justify="right") table.add_column("модель") table.add_column("цель", overflow="fold") for item in sessions: marker = " ←" if item.get("id") == current else "" updated = time.strftime("%Y-%m-%d %H:%M", time.localtime(item.get("updated_at", 0))) table.add_row( f"{item.get('id')}{marker}", updated, str(item.get("messages", 0)), str(item.get("model", "")), truncate(str(item.get("goal", "")).replace("\n", " "), 80), ) self.console.print(table) def print_stats(self, session: Session) -> None: stats = session.stats() main = stats["main_usage"] workers = stats["worker_usage"] table = Table.grid(padding=(0, 2)) table.add_column(style="dim", justify="right") table.add_column() table.add_row("сессия", session.id) table.add_row("ходов", str(stats["turns"])) table.add_row("контекст", f"≈{format_tokens(stats['context_tokens_estimate'])} токенов, {stats['messages']} сообщений") table.add_row( "main", f"{format_tokens(main['prompt_tokens'])} in / " f"{format_tokens(main['completion_tokens'])} out · " f"{format_cost(main['cost'])}" + ( f" · Go allowance {format_cost(main['allowance'])}" if main.get("allowance") else "" ), ) table.add_row( "workers", f"{format_tokens(workers['prompt_tokens'])} in / " f"{format_tokens(workers['completion_tokens'])} out · " f"{format_cost(workers['cost'])}", ) table.add_row("воркеры", f"{stats['workers']} всего, {stats['running']} работают") self.console.print(Panel(table, title="Статистика", box=ROUNDED, border_style="grey30")) def print_context(self, session: Session) -> None: self.console.print( f"[bold]Контекст главной модели[/bold]: {len(session.main_messages)} сообщений, " f"≈{format_tokens(session.context_tokens())} токенов.\n" "[dim]Лимит модели — в /models. /compact сжимает контекст, полный транскрипт " "сохраняется в папке сессии.[/dim]" ) def print_config(self, session: Session) -> None: config = session.config table = Table.grid(padding=(0, 2)) table.add_column(style="dim", justify="right") table.add_column() active = config.orchestrator_provider or config.active_provider profile = config.providers[active] table.add_row("provider", active) table.add_row("base_url", profile.base_url) table.add_row("main", f"{active}/{config.orchestrator_model}") table.add_row("worker", config.worker_model) table.add_row("roles", ", ".join(config.roles)) table.add_row("project config", str(config.project_config_path or "—")) table.add_row("global config", str(config.global_config_path or "—")) table.add_row("sessions", str(session.store.sessions_root)) self.console.print(Panel(table, title="Конфигурация", box=ROUNDED, border_style="grey30")) def error(self, message: str, *, title: str = "Ошибка") -> None: self._stop_spinner() self._stop_dashboard() self._close_text() self.console.print( Panel(Text(message), title=title, border_style="red", box=ROUNDED, padding=(0, 1)) ) def session_role_menu(config: Config) -> str: return "; ".join(f"{name}" for name in config.roles)