Репозитории /
AiRouter /
airouter/ui.py
ui.py
| 1 | """Terminal UI: streaming output, worker dashboard, prompt and commands.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import asyncio |
| 6 | import shutil |
| 7 | import sys |
| 8 | import time |
| 9 | from pathlib import Path |
| 10 | from typing import Any |
| 11 | from collections.abc import Iterable |
| 12 | |
| 13 | from prompt_toolkit import PromptSession |
| 14 | from prompt_toolkit.completion import Completer, Completion |
| 15 | from prompt_toolkit.history import FileHistory |
| 16 | from prompt_toolkit.styles import Style |
| 17 | from rich.box import ROUNDED, SIMPLE |
| 18 | from rich.console import Console, Group |
| 19 | from rich.live import Live |
| 20 | from rich.markdown import Markdown |
| 21 | from rich.panel import Panel |
| 22 | from rich.table import Table |
| 23 | from rich.text import Text |
| 24 | |
| 25 | from .config import Config |
| 26 | from .events import Event |
| 27 | from .models import ModelInfo |
| 28 | from .session import Session |
| 29 | from .utils import format_cost, format_duration, format_tokens, truncate |
| 30 | from .worker import Worker |
| 31 | |
| 32 | |
| 33 | class SlashCompleter(Completer): |
| 34 | COMMANDS = [ |
| 35 | "help", |
| 36 | "models", |
| 37 | "model", |
| 38 | "worker-model", |
| 39 | "workers", |
| 40 | "plan", |
| 41 | "stats", |
| 42 | "context", |
| 43 | "compact", |
| 44 | "cancel", |
| 45 | "workspace", |
| 46 | "new", |
| 47 | "sessions", |
| 48 | "resume", |
| 49 | "config", |
| 50 | "quit", |
| 51 | ] |
| 52 | |
| 53 | def __init__(self, get_models) -> None: |
| 54 | self.get_models = get_models |
| 55 | |
| 56 | def get_completions(self, document, complete_event): |
| 57 | text = document.text_before_cursor |
| 58 | if not text.startswith("/"): |
| 59 | return |
| 60 | body = text[1:] |
| 61 | if " " not in body: |
| 62 | for command in self.COMMANDS: |
| 63 | if command.startswith(body): |
| 64 | yield Completion(f"/{command}", start_position=-len(text)) |
| 65 | return |
| 66 | command, _, arg = body.partition(" ") |
| 67 | if command in {"model", "worker-model", "resume"}: |
| 68 | source = self.get_models() if command != "resume" else [] |
| 69 | for item in source: |
| 70 | value = item.id if command != "resume" else str(item) |
| 71 | if value.startswith(arg.strip()): |
| 72 | yield Completion(value, start_position=-len(arg)) |
| 73 | |
| 74 | |
| 75 | class UI: |
| 76 | def __init__(self, config: Config, *, no_color: bool = False) -> None: |
| 77 | self.config = config |
| 78 | self.is_tty = sys.stdout.isatty() |
| 79 | self.console = Console( |
| 80 | no_color=no_color or not self.is_tty, |
| 81 | highlight=False, |
| 82 | soft_wrap=True, |
| 83 | width=shutil.get_terminal_size((120, 30)).columns if self.is_tty else None, |
| 84 | ) |
| 85 | self.session: Session | None = None |
| 86 | self.spinner: Any = None |
| 87 | self.live: Live | None = None |
| 88 | self._dashboard_task: asyncio.Task[Any] | None = None |
| 89 | self._main_live: Live | None = None |
| 90 | self._last_main_render = 0.0 |
| 91 | self.deferred: list[Event] = [] |
| 92 | self.saw_main_text = False |
| 93 | self.main_text = "" |
| 94 | self.text_open = False |
| 95 | self.prompt: PromptSession[str] | None = None |
| 96 | self._models: list[ModelInfo] = [] |
| 97 | self._models_loaded = False |
| 98 | self._sleep_started: float | None = None |
| 99 | self._sleep_targets: list[str] = [] |
| 100 | |
| 101 | # ------------------------------------------------------------------ setup |
| 102 | |
| 103 | def attach(self, session: Session) -> None: |
| 104 | self.session = session |
| 105 | |
| 106 | def set_models(self, models: list[ModelInfo]) -> None: |
| 107 | self._models = models |
| 108 | self._models_loaded = True |
| 109 | |
| 110 | def get_models(self) -> list[ModelInfo]: |
| 111 | return self._models |
| 112 | |
| 113 | @property |
| 114 | def models_loaded(self) -> bool: |
| 115 | return self._models_loaded |
| 116 | |
| 117 | def print_banner(self, session: Session, auth_label: str) -> None: |
| 118 | c = self.console |
| 119 | c.print() |
| 120 | logo = Text() |
| 121 | logo.append(" AiRouter", style="bold #22d3ee") |
| 122 | logo.append(" главный агент следит за воркерами", style="dim") |
| 123 | c.print(logo) |
| 124 | grid = Table.grid(padding=(0, 2)) |
| 125 | grid.add_column(style="dim", justify="right") |
| 126 | grid.add_column(style="white") |
| 127 | grid.add_row("main", session.config.orchestrator_model) |
| 128 | grid.add_row("worker", session.config.worker_model) |
| 129 | grid.add_row( |
| 130 | "roles", |
| 131 | ", ".join(session.config.roles.keys()), |
| 132 | ) |
| 133 | grid.add_row("dir", str(session.cwd)) |
| 134 | grid.add_row("auth", auth_label) |
| 135 | grid.add_row("session", session.id) |
| 136 | c.print( |
| 137 | Panel( |
| 138 | grid, |
| 139 | border_style="grey30", |
| 140 | box=ROUNDED, |
| 141 | padding=(0, 1), |
| 142 | title="[dim]сессия[/dim]", |
| 143 | title_align="left", |
| 144 | ) |
| 145 | ) |
| 146 | c.print( |
| 147 | "[dim]Опишите цель. Главная модель разобьёт работу на задачи и запустит " |
| 148 | "воркеров. /help — команды.[/dim]" |
| 149 | ) |
| 150 | c.print() |
| 151 | |
| 152 | def print_resumed(self, session: Session) -> None: |
| 153 | self.console.print( |
| 154 | f"[dim]Продолжена сессия [white]{session.id}[/white] · " |
| 155 | f"{len(session.main_messages)} сообщений в контексте · " |
| 156 | f"воркеров: {len(session.workers)}[/dim]" |
| 157 | ) |
| 158 | |
| 159 | def print_help(self) -> None: |
| 160 | table = Table( |
| 161 | title="Команды", |
| 162 | box=SIMPLE, |
| 163 | border_style="grey30", |
| 164 | title_style="bold", |
| 165 | title_justify="left", |
| 166 | show_header=False, |
| 167 | padding=(0, 2), |
| 168 | ) |
| 169 | table.add_column(style="cyan", no_wrap=True) |
| 170 | table.add_column(style="white") |
| 171 | rows = [ |
| 172 | ("/help", "эта справка"), |
| 173 | ("/models", "список моделей OpenCode Go"), |
| 174 | ("/model <id>", "сменить главную модель"), |
| 175 | ("/worker-model <id>", "сменить модель воркеров по умолчанию"), |
| 176 | ("/workers [id]", "статусы воркеров; с id — полный отчёт"), |
| 177 | ("/plan", "план задач и подзадач"), |
| 178 | ("/stats", "расход токенов и стоимость"), |
| 179 | ("/context", "размер контекста главной модели"), |
| 180 | ("/compact", "сжать контекст (полный транскрипт сохраняется)"), |
| 181 | ("/cancel", "остановить всех воркеров"), |
| 182 | ("/workspace <path>", "сменить папку проекта"), |
| 183 | ("/new", "новая сессия"), |
| 184 | ("/sessions", "сессии в этой папке"), |
| 185 | ("/resume <id>", "переключиться на сессию"), |
| 186 | ("/config", "конфигурация и пути"), |
| 187 | ("/quit", "выход"), |
| 188 | ] |
| 189 | for command, description in rows: |
| 190 | table.add_row(command, description) |
| 191 | self.console.print(table) |
| 192 | if self.session: |
| 193 | self.console.print( |
| 194 | "[dim]Роли:[/dim] " + session_role_menu(self.session.config) |
| 195 | ) |
| 196 | |
| 197 | # ------------------------------------------------------------------ prompt |
| 198 | |
| 199 | def _history_path(self) -> Path: |
| 200 | path = Path.home() / ".local" / "state" / "airouter" / "history" |
| 201 | path.parent.mkdir(parents=True, exist_ok=True) |
| 202 | return path |
| 203 | |
| 204 | def _style(self) -> Style: |
| 205 | return Style.from_dict( |
| 206 | { |
| 207 | "prompt": "bold #22d3ee", |
| 208 | "bottom-toolbar": "bg:#111827 #9ca3af", |
| 209 | } |
| 210 | ) |
| 211 | |
| 212 | def _toolbar(self) -> str: |
| 213 | if not self.session: |
| 214 | return "" |
| 215 | running = len(self.session.running_workers()) |
| 216 | pieces = [ |
| 217 | f" {self.session.config.orchestrator_model}", |
| 218 | f"workers {running}", |
| 219 | f"{self.session.id}", |
| 220 | f"{self.session.cwd}", |
| 221 | ] |
| 222 | return " · ".join(pieces) + " " |
| 223 | |
| 224 | async def prompt_text(self) -> str: |
| 225 | if self.prompt is None: |
| 226 | self.prompt = PromptSession( |
| 227 | history=FileHistory(str(self._history_path())), |
| 228 | completer=SlashCompleter(self.get_models), |
| 229 | style=self._style(), |
| 230 | complete_while_typing=False, |
| 231 | ) |
| 232 | return await self.prompt.prompt_async( |
| 233 | [("class:prompt", "❯ ")], |
| 234 | bottom_toolbar=self._toolbar, |
| 235 | ) |
| 236 | |
| 237 | # ------------------------------------------------------------------ events |
| 238 | |
| 239 | def on_event(self, event: Event) -> None: |
| 240 | if not self.is_tty: |
| 241 | self._on_event_plain(event) |
| 242 | return |
| 243 | try: |
| 244 | self._on_event(event) |
| 245 | except Exception: |
| 246 | # Never break the agent because of rendering. |
| 247 | pass |
| 248 | |
| 249 | def _on_event_plain(self, event: Event) -> None: |
| 250 | t = event.type |
| 251 | data = event.data |
| 252 | if t == "main_tool_call": |
| 253 | self.console.print(f"[main] {data.get('name')}({data.get('args', '')})", markup=False) |
| 254 | elif t == "worker_spawned": |
| 255 | self.console.print( |
| 256 | f"[{event.worker_id}] spawned {data.get('name')} · {data.get('workspace')}", |
| 257 | markup=False, |
| 258 | ) |
| 259 | elif t == "worker_done": |
| 260 | self.console.print( |
| 261 | f"[{event.worker_id}] done in {format_duration(data.get('duration'))}", |
| 262 | markup=False, |
| 263 | ) |
| 264 | elif t == "worker_failed": |
| 265 | self.console.print( |
| 266 | f"[{event.worker_id}] FAILED: {data.get('error')}", markup=False |
| 267 | ) |
| 268 | elif t == "worker_cancelled": |
| 269 | self.console.print( |
| 270 | f"[{event.worker_id}] cancelled: {data.get('error', '')}", markup=False |
| 271 | ) |
| 272 | elif t == "worker_continued": |
| 273 | self.console.print(f"[{event.worker_id}] continuing", markup=False) |
| 274 | elif t == "worker_tool_call": |
| 275 | self.console.print( |
| 276 | f"[{event.worker_id}] {data.get('name')}: {data.get('args', '')}", |
| 277 | markup=False, |
| 278 | ) |
| 279 | elif t == "main_sleep": |
| 280 | targets = ", ".join(str(item.get("id")) for item in (data.get("waiting_for") or [])) |
| 281 | self.console.print( |
| 282 | f"[main] sleeping until workers finish: {targets}", markup=False |
| 283 | ) |
| 284 | elif t == "main_wake": |
| 285 | completed = ", ".join(data.get("completed") or []) |
| 286 | still = ", ".join(data.get("still_running") or []) |
| 287 | if completed: |
| 288 | self.console.print(f"[main] woke up: {completed}", markup=False) |
| 289 | elif still: |
| 290 | self.console.print( |
| 291 | f"[main] woke up (timeout), still running: {still}", markup=False |
| 292 | ) |
| 293 | elif t == "main_text_delta": |
| 294 | if not self.saw_main_text: |
| 295 | self.console.print(Text("main › ", style="bold #22d3ee"), end="") |
| 296 | self.saw_main_text = True |
| 297 | self.console.print(data.get("delta", ""), end="", markup=False, highlight=False) |
| 298 | elif t == "main_turn_done": |
| 299 | self.console.print() |
| 300 | elif t == "notice": |
| 301 | self.console.print(f"[notice] {data.get('text')}", markup=False) |
| 302 | |
| 303 | def _on_event(self, event: Event) -> None: |
| 304 | t = event.type |
| 305 | d = event.data |
| 306 | if t == "main_turn_started": |
| 307 | self._stop_main_live() |
| 308 | self.saw_main_text = False |
| 309 | self.main_text = "" |
| 310 | self.text_open = False |
| 311 | elif t == "main_step": |
| 312 | self._start_spinner("main думает…") |
| 313 | elif t == "main_text_delta": |
| 314 | self._stop_spinner() |
| 315 | delta = d.get("delta", "") |
| 316 | if not delta: |
| 317 | return |
| 318 | if not self.text_open: |
| 319 | self.text_open = True |
| 320 | self.main_text = "" |
| 321 | if not self.is_tty: |
| 322 | self.console.print(Text("main › ", style="bold #22d3ee"), end="") |
| 323 | self.main_text += delta |
| 324 | self.saw_main_text = True |
| 325 | if self.is_tty: |
| 326 | self._render_main_live() |
| 327 | else: |
| 328 | self.console.print(Text(delta), end="") |
| 329 | elif t == "main_tool_call": |
| 330 | self._stop_spinner() |
| 331 | self._close_text() |
| 332 | self._flush_deferred() |
| 333 | args = d.get("args", "") |
| 334 | self.console.print( |
| 335 | Text(" ▸ ", style="cyan") |
| 336 | + Text(str(d.get("name")), style="bold cyan") |
| 337 | + (Text(f"({args})", style="dim") if args else Text("", style="dim")) |
| 338 | ) |
| 339 | elif t == "main_tool_result": |
| 340 | if d.get("ok", True) and d.get("name") in { |
| 341 | "spawn_worker", |
| 342 | "wait_for_workers", |
| 343 | "message_worker", |
| 344 | }: |
| 345 | return |
| 346 | ok = bool(d.get("ok", True)) |
| 347 | summary = str(d.get("summary", "")) |
| 348 | if summary: |
| 349 | marker = Text(" ✓ ", style="green") if ok else Text(" ✗ ", style="red") |
| 350 | self.console.print(marker + Text(truncate(summary, 180), style="dim")) |
| 351 | elif t == "main_sleep": |
| 352 | self._stop_spinner() |
| 353 | self._close_text() |
| 354 | self._flush_deferred() |
| 355 | targets = d.get("waiting_for") or [] |
| 356 | self._sleep_targets = [str(item.get("id")) for item in targets] |
| 357 | self._sleep_started = time.monotonic() |
| 358 | names = ", ".join(str(item.get("id")) for item in targets) |
| 359 | self.console.print( |
| 360 | Text(" ⏸ ", style="yellow") |
| 361 | + Text(f"main спит — ждёт: {names}", style="yellow") |
| 362 | ) |
| 363 | self._start_dashboard() |
| 364 | elif t == "main_wake": |
| 365 | self._stop_dashboard() |
| 366 | completed = d.get("completed") or [] |
| 367 | still = d.get("still_running") or [] |
| 368 | self._flush_deferred() |
| 369 | if completed: |
| 370 | self.console.print( |
| 371 | Text(" ▶ ", style="bold cyan") |
| 372 | + Text(f"main проснулся — готовы: {', '.join(completed)}", style="bold cyan") |
| 373 | ) |
| 374 | elif still: |
| 375 | self.console.print( |
| 376 | Text(" ▶ ", style="yellow") |
| 377 | + Text(f"main проснулся — ещё работают: {', '.join(still)}", style="yellow") |
| 378 | ) |
| 379 | elif t == "worker_spawned": |
| 380 | if not self.live and not self._main_live: |
| 381 | self.console.print( |
| 382 | Text(" + ", style="magenta") |
| 383 | + Text(str(event.worker_id), style="bold magenta") |
| 384 | + Text( |
| 385 | f" {d.get('name')} · {d.get('role')} · {d.get('model')} · {d.get('workspace')}", |
| 386 | style="dim", |
| 387 | ) |
| 388 | ) |
| 389 | elif t == "worker_started": |
| 390 | pass |
| 391 | elif t == "worker_tool_call": |
| 392 | if not self.live and not self._main_live: |
| 393 | args = str(d.get("args", "")) |
| 394 | self.console.print( |
| 395 | Text(f" {event.worker_id} ", style="magenta") |
| 396 | + Text("⚙ ", style="dim") |
| 397 | + Text(str(d.get("name")), style="magenta") |
| 398 | + (Text(f": {truncate(args, self.config.ui.max_worker_line)}", style="dim") if args else Text("")) |
| 399 | ) |
| 400 | elif t == "worker_tool_result": |
| 401 | if not self.live and not self._main_live and not d.get("ok", True): |
| 402 | self.console.print( |
| 403 | Text(f" {event.worker_id} ", style="magenta") |
| 404 | + Text("✗ ", style="red") |
| 405 | + Text(truncate(str(d.get("summary", "")), 160), style="red") |
| 406 | ) |
| 407 | elif t in {"worker_done", "worker_failed", "worker_cancelled"}: |
| 408 | if self.live or self._main_live: |
| 409 | self.deferred.append(event) |
| 410 | else: |
| 411 | self._print_worker_finished(event) |
| 412 | elif t == "worker_continued": |
| 413 | if not self.live and not self._main_live: |
| 414 | self.console.print( |
| 415 | Text(f" ↻ {event.worker_id} ", style="magenta") |
| 416 | + Text("продолжает работу", style="dim") |
| 417 | ) |
| 418 | elif t == "notice": |
| 419 | if not self._main_live and not self.live: |
| 420 | self.console.print(Text(f" · {d.get('text')}", style="dim")) |
| 421 | elif t == "error": |
| 422 | self.console.print(Panel(str(d.get("text")), border_style="red")) |
| 423 | elif t == "compacted": |
| 424 | self._stop_spinner() |
| 425 | self.console.print( |
| 426 | Text(" ◇ контекст сжат. ", style="cyan") |
| 427 | + Text(f"Бэкап: {d.get('backup')}", style="dim") |
| 428 | ) |
| 429 | elif t == "main_turn_done": |
| 430 | self._stop_spinner() |
| 431 | self._stop_dashboard() |
| 432 | self._close_text() |
| 433 | self._flush_deferred() |
| 434 | final_text = str(d.get("text") or "") |
| 435 | if not self.saw_main_text and final_text: |
| 436 | self.console.print(Markdown(final_text)) |
| 437 | elif self.saw_main_text and final_text: |
| 438 | streamed = self.main_text.strip() |
| 439 | final_clean = final_text.strip() |
| 440 | if final_clean != streamed: |
| 441 | extra = ( |
| 442 | final_clean[len(streamed):].strip() |
| 443 | if final_clean.startswith(streamed) |
| 444 | else final_clean |
| 445 | ) |
| 446 | if extra: |
| 447 | self.console.print(Text(extra, style="yellow")) |
| 448 | self.console.print() |
| 449 | |
| 450 | # ------------------------------------------------------------------ rendering helpers |
| 451 | |
| 452 | def _start_spinner(self, message: str) -> None: |
| 453 | if self.live: |
| 454 | return |
| 455 | self._stop_spinner() |
| 456 | self.spinner = self.console.status( |
| 457 | Text(f" {message}", style="cyan"), spinner="dots", spinner_style="cyan" |
| 458 | ) |
| 459 | try: |
| 460 | self.spinner.start() |
| 461 | except Exception: |
| 462 | self.spinner = None |
| 463 | |
| 464 | def _stop_spinner(self) -> None: |
| 465 | if self.spinner: |
| 466 | try: |
| 467 | self.spinner.stop() |
| 468 | except Exception: |
| 469 | pass |
| 470 | self.spinner = None |
| 471 | |
| 472 | def _close_text(self) -> None: |
| 473 | if not self.text_open: |
| 474 | return |
| 475 | if self.is_tty: |
| 476 | self._stop_main_live() |
| 477 | if self.main_text.strip(): |
| 478 | self.console.print( |
| 479 | Group( |
| 480 | Text("main › ", style="bold #22d3ee"), |
| 481 | Markdown(self.main_text), |
| 482 | ) |
| 483 | ) |
| 484 | else: |
| 485 | self.console.print() |
| 486 | self.text_open = False |
| 487 | if self.deferred: |
| 488 | self._flush_deferred() |
| 489 | |
| 490 | def _render_main_live(self) -> None: |
| 491 | if not self.is_tty: |
| 492 | return |
| 493 | group = Group( |
| 494 | Text("main › ", style="bold #22d3ee"), |
| 495 | Markdown(self.main_text), |
| 496 | ) |
| 497 | now = time.monotonic() |
| 498 | if self._main_live is None: |
| 499 | self._main_live = Live( |
| 500 | group, |
| 501 | console=self.console, |
| 502 | refresh_per_second=8, |
| 503 | transient=True, |
| 504 | vertical_overflow="visible", |
| 505 | ) |
| 506 | try: |
| 507 | self._main_live.start(refresh=True) |
| 508 | self._last_main_render = now |
| 509 | except Exception: |
| 510 | self._main_live = None |
| 511 | elif now - self._last_main_render >= 0.12: |
| 512 | try: |
| 513 | self._main_live.update(group, refresh=True) |
| 514 | self._last_main_render = now |
| 515 | except Exception: |
| 516 | self._stop_main_live() |
| 517 | |
| 518 | def _stop_main_live(self) -> None: |
| 519 | if self._main_live: |
| 520 | try: |
| 521 | self._main_live.stop() |
| 522 | except Exception: |
| 523 | pass |
| 524 | self._main_live = None |
| 525 | |
| 526 | def _start_dashboard(self) -> None: |
| 527 | if self.live or not self.is_tty or not self.session: |
| 528 | return |
| 529 | try: |
| 530 | self.live = Live( |
| 531 | self._dashboard_renderable(), |
| 532 | console=self.console, |
| 533 | refresh_per_second=6, |
| 534 | transient=True, |
| 535 | vertical_overflow="visible", |
| 536 | ) |
| 537 | self.live.start(refresh=True) |
| 538 | except Exception: |
| 539 | self.live = None |
| 540 | return |
| 541 | self._dashboard_task = asyncio.create_task(self._dashboard_loop()) |
| 542 | |
| 543 | async def _dashboard_loop(self) -> None: |
| 544 | try: |
| 545 | while self.live is not None: |
| 546 | self.live.update(self._dashboard_renderable(), refresh=True) |
| 547 | await asyncio.sleep(0.25) |
| 548 | except asyncio.CancelledError: |
| 549 | pass |
| 550 | except Exception: |
| 551 | pass |
| 552 | |
| 553 | def _stop_dashboard(self) -> None: |
| 554 | task = getattr(self, "_dashboard_task", None) |
| 555 | if task is not None: |
| 556 | task.cancel() |
| 557 | self._dashboard_task = None |
| 558 | if self.live: |
| 559 | try: |
| 560 | self.live.stop() |
| 561 | except Exception: |
| 562 | pass |
| 563 | self.live = None |
| 564 | |
| 565 | def _dashboard_renderable(self) -> Group: |
| 566 | if not self.session: |
| 567 | return Group() |
| 568 | table = Table.grid(padding=(0, 2)) |
| 569 | table.add_column(no_wrap=True) |
| 570 | table.add_column(no_wrap=True) |
| 571 | table.add_column(no_wrap=True) |
| 572 | table.add_column(no_wrap=True) |
| 573 | table.add_column(overflow="ellipsis", no_wrap=True) |
| 574 | frames = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏" |
| 575 | frame = frames[int(time.monotonic() * 10) % len(frames)] |
| 576 | running = [w for w in self.session.workers.values() if not w.is_terminal] |
| 577 | for worker in running: |
| 578 | table.add_row( |
| 579 | Text(f"{frame} {worker.id}", style="magenta"), |
| 580 | Text(worker.name, style="white"), |
| 581 | Text(worker.status, style="yellow"), |
| 582 | Text(format_duration(worker.duration), style="dim"), |
| 583 | Text(worker.last_action, style="dim"), |
| 584 | ) |
| 585 | elapsed = time.monotonic() - (self._sleep_started or time.monotonic()) |
| 586 | caption = Text( |
| 587 | f"main спит · ждёт {len(running)} · {format_duration(elapsed)} · " |
| 588 | "проснётся, как только воркер закончит", |
| 589 | style="dim", |
| 590 | ) |
| 591 | if not running: |
| 592 | caption = Text("main спит · завершение воркеров…", style="dim") |
| 593 | return Group(table, caption) |
| 594 | |
| 595 | def _flush_deferred(self) -> None: |
| 596 | for event in self.deferred: |
| 597 | self._print_worker_finished(event) |
| 598 | self.deferred.clear() |
| 599 | |
| 600 | def _print_worker_finished(self, event: Event) -> None: |
| 601 | d = event.data |
| 602 | wid = event.worker_id or "?" |
| 603 | name = d.get("name", wid) |
| 604 | duration = format_duration(d.get("duration")) |
| 605 | files = d.get("files_changed") or [] |
| 606 | if event.type == "worker_done": |
| 607 | marker = Text(" ✓ ", style="green") |
| 608 | label = Text(f"{wid} {name}", style="bold green") |
| 609 | extra = f" · {duration}" |
| 610 | if files: |
| 611 | extra += f" · файлов: {len(files)}" |
| 612 | self.console.print(marker + label + Text(extra, style="dim")) |
| 613 | report = str(d.get("result") or "").strip().splitlines() |
| 614 | if report: |
| 615 | self.console.print(Text(f" {truncate(report[0], 160)}", style="dim")) |
| 616 | elif event.type == "worker_failed": |
| 617 | self.console.print( |
| 618 | Text(" ✗ ", style="red") |
| 619 | + Text(f"{wid} {name}", style="bold red") |
| 620 | + Text(f" · {duration} · {truncate(str(d.get('error', '')), 200)}", style="red") |
| 621 | ) |
| 622 | else: |
| 623 | self.console.print( |
| 624 | Text(" ⊘ ", style="yellow") |
| 625 | + Text(f"{wid} {name}", style="bold yellow") |
| 626 | + Text(" · отменён", style="dim") |
| 627 | ) |
| 628 | |
| 629 | # ------------------------------------------------------------------ tables |
| 630 | |
| 631 | def print_plan(self, session: Session) -> None: |
| 632 | if not session.todos: |
| 633 | self.console.print("[dim]Плана пока нет. Главная модель создаст его через update_plan.[/dim]") |
| 634 | return |
| 635 | table = Table(title="План", box=SIMPLE, border_style="grey30") |
| 636 | table.add_column("", width=2) |
| 637 | table.add_column("задача", overflow="fold") |
| 638 | table.add_column("воркер", style="magenta") |
| 639 | table.add_column("статус") |
| 640 | icons = { |
| 641 | "pending": "○", |
| 642 | "in_progress": "◐", |
| 643 | "done": "✓", |
| 644 | "blocked": "!", |
| 645 | "skipped": "–", |
| 646 | } |
| 647 | styles = { |
| 648 | "pending": "dim", |
| 649 | "in_progress": "yellow", |
| 650 | "done": "green", |
| 651 | "blocked": "red", |
| 652 | "skipped": "dim", |
| 653 | } |
| 654 | for task in session.todos: |
| 655 | status = str(task.get("status", "pending")) |
| 656 | title = str(task.get("title", "")) |
| 657 | subtasks = task.get("subtasks") or [] |
| 658 | if subtasks: |
| 659 | title += "\n" + "\n".join( |
| 660 | f" {icons.get(str(sub.get('status', 'pending')), '○')} {sub.get('title', '')}" |
| 661 | for sub in subtasks |
| 662 | ) |
| 663 | table.add_row( |
| 664 | icons.get(status, "○"), |
| 665 | title, |
| 666 | str(task.get("worker_id") or ""), |
| 667 | f"[{styles.get(status, 'white')}]{status}[/]", |
| 668 | ) |
| 669 | self.console.print(table) |
| 670 | |
| 671 | def print_workers(self, session: Session, worker_id: str | None = None) -> None: |
| 672 | if worker_id: |
| 673 | worker = session.workers.get(worker_id) |
| 674 | if not worker: |
| 675 | self.console.print(f"[red]Воркер {worker_id} не найден[/red]") |
| 676 | return |
| 677 | self.print_worker_report(worker) |
| 678 | return |
| 679 | if not session.workers: |
| 680 | self.console.print("[dim]Воркеров ещё не было.[/dim]") |
| 681 | return |
| 682 | table = Table(title="Воркеры", box=SIMPLE, border_style="grey30") |
| 683 | table.add_column("id", style="magenta", no_wrap=True) |
| 684 | table.add_column("имя") |
| 685 | table.add_column("роль") |
| 686 | table.add_column("статус") |
| 687 | table.add_column("время", justify="right") |
| 688 | table.add_column("шаги", justify="right") |
| 689 | table.add_column("файлы", justify="right") |
| 690 | table.add_column("папка", overflow="fold") |
| 691 | for w in session.workers.values(): |
| 692 | status_style = { |
| 693 | "done": "green", |
| 694 | "failed": "red", |
| 695 | "cancelled": "yellow", |
| 696 | "interrupted": "yellow", |
| 697 | "running": "cyan", |
| 698 | "pending": "cyan", |
| 699 | }.get(w.status, "white") |
| 700 | table.add_row( |
| 701 | w.id, |
| 702 | w.name, |
| 703 | w.role.name, |
| 704 | f"[{status_style}]{w.status}[/{status_style}]", |
| 705 | format_duration(w.duration), |
| 706 | str(w.steps), |
| 707 | str(len(w.files_changed)), |
| 708 | str(w.workspace_path), |
| 709 | ) |
| 710 | self.console.print(table) |
| 711 | |
| 712 | def print_worker_report(self, worker: Worker) -> None: |
| 713 | self.console.print( |
| 714 | Panel( |
| 715 | Text(worker.result or worker.error or "(отчёта нет)"), |
| 716 | title=f"{worker.id} · {worker.name} · {worker.status}", |
| 717 | subtitle=str(worker.report_path) if worker.report_path else None, |
| 718 | border_style="green" if worker.status == "done" else "red", |
| 719 | box=ROUNDED, |
| 720 | padding=(0, 1), |
| 721 | ) |
| 722 | ) |
| 723 | if worker.files_changed: |
| 724 | self.console.print("[bold]Файлы:[/bold] " + ", ".join(worker.files_changed)) |
| 725 | if worker.commands: |
| 726 | self.console.print("[bold]Команды:[/bold]") |
| 727 | for command in worker.commands[-8:]: |
| 728 | self.console.print( |
| 729 | Text( |
| 730 | f" ${command.get('command')} → {command.get('exit_code')} " |
| 731 | f"({command.get('duration')}s)", |
| 732 | style="dim", |
| 733 | ) |
| 734 | ) |
| 735 | |
| 736 | def print_models( |
| 737 | self, models: Iterable[ModelInfo], current_main: str, current_worker: str |
| 738 | ) -> None: |
| 739 | table = Table(title="Модели", box=SIMPLE, border_style="grey30") |
| 740 | table.add_column("id", style="cyan", no_wrap=True) |
| 741 | table.add_column("контекст", justify="right") |
| 742 | table.add_column("tools", justify="center") |
| 743 | table.add_column("$ in/out", justify="right") |
| 744 | table.add_column("", style="green") |
| 745 | for model in models: |
| 746 | marks = [] |
| 747 | if model.id == current_main: |
| 748 | marks.append("main") |
| 749 | if model.id == current_worker: |
| 750 | marks.append("worker") |
| 751 | table.add_row( |
| 752 | model.id, |
| 753 | format_tokens(model.context or 0) if model.context else "—", |
| 754 | "yes" if model.tools else "no", |
| 755 | ( |
| 756 | f"{model.input_price:g}/{model.output_price:g}" |
| 757 | if model.input_price is not None |
| 758 | else "—" |
| 759 | ), |
| 760 | ", ".join(marks), |
| 761 | ) |
| 762 | self.console.print(table) |
| 763 | |
| 764 | def print_sessions(self, sessions: list[dict[str, Any]], current: str | None) -> None: |
| 765 | if not sessions: |
| 766 | self.console.print("[dim]Сессий пока нет.[/dim]") |
| 767 | return |
| 768 | table = Table(title="Сессии", box=SIMPLE, border_style="grey30") |
| 769 | table.add_column("id", style="cyan", no_wrap=True) |
| 770 | table.add_column("обновлена") |
| 771 | table.add_column("сообщений", justify="right") |
| 772 | table.add_column("модель") |
| 773 | table.add_column("цель", overflow="fold") |
| 774 | for item in sessions: |
| 775 | marker = " ←" if item.get("id") == current else "" |
| 776 | updated = time.strftime("%Y-%m-%d %H:%M", time.localtime(item.get("updated_at", 0))) |
| 777 | table.add_row( |
| 778 | f"{item.get('id')}{marker}", |
| 779 | updated, |
| 780 | str(item.get("messages", 0)), |
| 781 | str(item.get("model", "")), |
| 782 | truncate(str(item.get("goal", "")).replace("\n", " "), 80), |
| 783 | ) |
| 784 | self.console.print(table) |
| 785 | |
| 786 | def print_stats(self, session: Session) -> None: |
| 787 | stats = session.stats() |
| 788 | main = stats["main_usage"] |
| 789 | workers = stats["worker_usage"] |
| 790 | table = Table.grid(padding=(0, 2)) |
| 791 | table.add_column(style="dim", justify="right") |
| 792 | table.add_column() |
| 793 | table.add_row("сессия", session.id) |
| 794 | table.add_row("ходов", str(stats["turns"])) |
| 795 | table.add_row("контекст", f"≈{format_tokens(stats['context_tokens_estimate'])} токенов, {stats['messages']} сообщений") |
| 796 | table.add_row( |
| 797 | "main", |
| 798 | f"{format_tokens(main['prompt_tokens'])} in / " |
| 799 | f"{format_tokens(main['completion_tokens'])} out · " |
| 800 | f"{format_cost(main['cost'])}" |
| 801 | + ( |
| 802 | f" · Go allowance {format_cost(main['allowance'])}" |
| 803 | if main.get("allowance") |
| 804 | else "" |
| 805 | ), |
| 806 | ) |
| 807 | table.add_row( |
| 808 | "workers", |
| 809 | f"{format_tokens(workers['prompt_tokens'])} in / " |
| 810 | f"{format_tokens(workers['completion_tokens'])} out · " |
| 811 | f"{format_cost(workers['cost'])}", |
| 812 | ) |
| 813 | table.add_row("воркеры", f"{stats['workers']} всего, {stats['running']} работают") |
| 814 | self.console.print(Panel(table, title="Статистика", box=ROUNDED, border_style="grey30")) |
| 815 | |
| 816 | def print_context(self, session: Session) -> None: |
| 817 | self.console.print( |
| 818 | f"[bold]Контекст главной модели[/bold]: {len(session.main_messages)} сообщений, " |
| 819 | f"≈{format_tokens(session.context_tokens())} токенов.\n" |
| 820 | "[dim]Лимит модели — в /models. /compact сжимает контекст, полный транскрипт " |
| 821 | "сохраняется в папке сессии.[/dim]" |
| 822 | ) |
| 823 | |
| 824 | def print_config(self, session: Session) -> None: |
| 825 | config = session.config |
| 826 | table = Table.grid(padding=(0, 2)) |
| 827 | table.add_column(style="dim", justify="right") |
| 828 | table.add_column() |
| 829 | table.add_row("base_url", config.provider.base_url) |
| 830 | table.add_row("main", config.orchestrator_model) |
| 831 | table.add_row("worker", config.worker_model) |
| 832 | table.add_row("roles", ", ".join(config.roles)) |
| 833 | table.add_row("project config", str(config.project_config_path or "—")) |
| 834 | table.add_row("global config", str(config.global_config_path or "—")) |
| 835 | table.add_row("sessions", str(session.store.sessions_root)) |
| 836 | self.console.print(Panel(table, title="Конфигурация", box=ROUNDED, border_style="grey30")) |
| 837 | |
| 838 | def error(self, message: str, *, title: str = "Ошибка") -> None: |
| 839 | self._stop_spinner() |
| 840 | self._stop_dashboard() |
| 841 | self._close_text() |
| 842 | self.console.print( |
| 843 | Panel(Text(message), title=title, border_style="red", box=ROUNDED, padding=(0, 1)) |
| 844 | ) |
| 845 | |
| 846 | |
| 847 | def session_role_menu(config: Config) -> str: |
| 848 | return "; ".join(f"{name}" for name in config.roles) |