Files

960 lines
36 KiB
Python

"""Command-line entry point."""
from __future__ import annotations
import argparse
import asyncio
import os
import platform
import shutil
import sys
import time
import traceback
from dataclasses import replace
from pathlib import Path
from typing import Any
from rich.console import Console
from rich.prompt import Confirm
from rich.table import Table
from . import APP_NAME, __version__
from .auth import describe_auth, token_hint
from .chats import delete_visible_message, last_visible_index, visible_message_indices
from .config import (
CONFIG_FILENAME,
Config,
ConfigError,
load_config,
write_sample_config,
)
from .models import ModelInfo, fetch_models
from .provider import OpenAIClient, ProviderError
from .providers import ProviderRegistry
from .service import ServiceClient, load_service_runtime
from .service_commands import add_integration_parsers, handle_integration_command
from .session import Session, SessionError
from .storage import SessionStore, StorageError
from .ui import UI
from .update import check_for_updates, install_update
from .workspace import ToolError
def _common_options(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"-c",
"--continue",
dest="continue_session",
action="store_true",
default=argparse.SUPPRESS,
help="продолжить последнюю сессию",
)
parser.add_argument("-s", "--session", dest="session_id", default=argparse.SUPPRESS)
parser.add_argument("--config", type=Path, default=argparse.SUPPRESS)
parser.add_argument("-m", "--model", dest="model", default=argparse.SUPPRESS)
parser.add_argument("-w", "--worker-model", dest="worker_model", default=argparse.SUPPRESS)
parser.add_argument("--base-url", default=argparse.SUPPRESS)
parser.add_argument(
"--provider",
dest="provider_id",
default=argparse.SUPPRESS,
help="ID провайдера из config/providers.json",
)
parser.add_argument(
"--workspace", default=argparse.SUPPRESS, help="рабочая папка сессии"
)
parser.add_argument("--max-workers", type=int, default=argparse.SUPPRESS)
parser.add_argument("--no-color", action="store_true", default=argparse.SUPPRESS)
parser.add_argument("--debug", action="store_true", default=argparse.SUPPRESS)
parser.add_argument(
"--no-update-check",
action="store_true",
default=argparse.SUPPRESS,
help="не проверять обновления при запуске",
)
def _build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="airouter",
description="AiRouter — главная модель планирует работу и следит за изолированными воркерами.",
)
_common_options(parser)
parser.add_argument("-v", "--version", action="version", version=f"{APP_NAME} {__version__}")
parser.add_argument(
"--classic",
action="store_true",
help="классический prompt-интерфейс вместо TUI",
)
sub = parser.add_subparsers(dest="command")
run = sub.add_parser("run", help="выполнить цель без интерактивного режима")
_common_options(run)
run.add_argument("goal", nargs="+", help="цель для главной модели")
tui = sub.add_parser("tui", help="запустить интерактивный TUI")
_common_options(tui)
tui.add_argument(
"--classic", action="store_true", default=argparse.SUPPRESS, help=argparse.SUPPRESS
)
models = sub.add_parser("models", help="показать каталог моделей")
_common_options(models)
models.add_argument("--refresh", action="store_true")
providers = sub.add_parser("providers", help="показать провайдеров и их модели")
_common_options(providers)
providers.add_argument("--refresh", action="store_true")
sessions = sub.add_parser("sessions", help="показать сессии в текущей папке")
_common_options(sessions)
init = sub.add_parser("init", help="создать .airouter.toml")
init.add_argument("--force", action="store_true")
doctor = sub.add_parser("doctor", help="проверить окружение и доступ к API")
_common_options(doctor)
doctor.add_argument("--live", action="store_true", help="сделать тестовый запрос к модели")
sub.add_parser("version", help="показать версию")
add_integration_parsers(sub)
return parser
def _opt(args: argparse.Namespace, name: str, default: Any = None) -> Any:
return getattr(args, name, default)
def _sessions_root(cwd: Path) -> Path:
return cwd / ".airouter" / "sessions"
def _make_config(args: argparse.Namespace, cwd: Path) -> Config:
config = load_config(
cwd,
config_path=_opt(args, "config"),
base_url=_opt(args, "base_url"),
model=_opt(args, "model"),
worker_model=_opt(args, "worker_model"),
)
max_workers = _opt(args, "max_workers")
if max_workers:
config.limits.max_workers = max(1, max_workers)
provider_id = _opt(args, "provider_id")
if provider_id:
if provider_id not in config.providers:
raise ConfigError(
f"Неизвестный провайдер {provider_id!r}. "
f"Доступны: {', '.join(sorted(config.providers))}"
)
config.active_provider = provider_id
config.orchestrator_provider = provider_id
config.worker_provider = provider_id
base_override = _opt(args, "base_url") or os.environ.get("AIROUTER_BASE_URL")
if base_override:
active = config.orchestrator_provider or config.active_provider
profile = replace(
config.providers[active],
base_url=base_override.rstrip("/"),
kind="opencode" if "opencode.ai" in base_override else "openai",
)
config.providers[active] = profile
config.provider.base_url = profile.base_url
return config
def _make_provider(config: Config) -> tuple[OpenAIClient, list[Any], ProviderRegistry]:
registry = ProviderRegistry(config)
client = registry.default_client(role="orchestrator")
tokens = client.tokens
profile = config.providers.get(config.orchestrator_provider or config.active_provider)
if not tokens and profile and profile.auto_auth and "opencode.ai" in profile.base_url:
raise ConfigError(token_hint(config))
return client, tokens, registry
def _update_check_disabled(args: argparse.Namespace) -> bool:
return bool(
_opt(args, "no_update_check", False)
or os.environ.get("AIROUTER_NO_UPDATE_CHECK", "").lower()
in {"1", "true", "yes", "on"}
)
def _maybe_update_sync(args: argparse.Namespace) -> bool:
"""Offer a safe update before launching an interactive interface."""
if _update_check_disabled(args) or not sys.stdin.isatty():
return False
info = check_for_updates()
if not info.available:
return False
Console().print(
f"[yellow]Доступна AiRouter {info.latest}; установлена {info.current}.[/yellow]"
)
if not Confirm.ask("Обновить сейчас?", default=False):
return False
result = install_update()
Console().print(result.message)
return result.updated or result.message == "AiRouter is already up to date."
async def _maybe_update_async(args: argparse.Namespace) -> bool:
if _update_check_disabled(args) or not sys.stdin.isatty():
return False
info = await asyncio.to_thread(check_for_updates)
if not info.available:
return False
Console().print(
f"[yellow]Доступна AiRouter {info.latest}; установлена {info.current}.[/yellow]"
)
if not Confirm.ask("Обновить сейчас?", default=False):
return False
result = await asyncio.to_thread(install_update)
Console().print(result.message)
return result.updated or result.message == "AiRouter is already up to date."
def _catalog(
config: Config,
tokens: list[Any],
*,
refresh: bool = False,
registry: ProviderRegistry | None = None,
) -> list[ModelInfo]:
if registry is not None:
return registry.catalog(refresh=refresh, timeout=6)
token = tokens[0].value if tokens else None
return fetch_models(config.provider.base_url, token=token, refresh=refresh, timeout=6)
async def _open_session(
*,
args: argparse.Namespace,
config: Config,
provider: OpenAIClient,
cwd: Path,
ui: UI,
provider_registry: ProviderRegistry | None = None,
) -> tuple[Session, bool]:
sessions_root = _sessions_root(cwd)
resumed = False
if _opt(args, "session_id"):
session = await asyncio.to_thread(
Session.load,
sessions_root=sessions_root,
session_id=_opt(args, "session_id"),
config=config,
provider=provider,
provider_registry=provider_registry,
)
resumed = True
elif _opt(args, "continue_session", False):
latest = SessionStore.latest(sessions_root)
if latest is None:
raise StorageError("Нет сохранённых сессий в этой папке")
session = await asyncio.to_thread(
Session.load,
sessions_root=sessions_root,
session_id=latest.id,
config=config,
provider=provider,
provider_registry=provider_registry,
)
resumed = True
else:
session = Session.create(
sessions_root=sessions_root,
config=config,
provider=provider,
cwd=cwd,
provider_registry=provider_registry,
)
if resumed:
if _opt(args, "model"):
session.config.orchestrator_model = _opt(args, "model")
if _opt(args, "worker_model"):
session.config.worker_model = _opt(args, "worker_model")
if _opt(args, "max_workers"):
session.config.limits.max_workers = max(1, int(_opt(args, "max_workers")))
session.refresh_system_prompt()
session.listener = ui.on_event
ui.attach(session)
return session, resumed
def _safe_unknown_model(ui: UI, model: str) -> None:
if not ui.models_loaded:
return
if not any(item.id == model for item in ui.get_models()):
ui.console.print(
f"[yellow]Модель {model!r} отсутствует в каталоге. Запрос всё равно будет отправлен.[/yellow]"
)
async def _interactive(
args: argparse.Namespace,
config: Config,
provider: OpenAIClient,
ui: UI,
provider_registry: ProviderRegistry | None = None,
) -> int:
if await _maybe_update_async(args):
return 0
workspace = _opt(args, "workspace")
cwd = (Path(workspace).expanduser().resolve() if workspace else Path.cwd().resolve())
cwd.mkdir(parents=True, exist_ok=True)
try:
session, resumed = await _open_session(
args=args,
config=config,
provider=provider,
cwd=cwd,
ui=ui,
provider_registry=provider_registry,
)
except (StorageError, ConfigError, OSError) as exc:
ui.error(str(exc))
return 2
tokens = provider.tokens
ui.print_banner(session, describe_auth(tokens))
if resumed:
ui.print_resumed(session)
try:
models = await asyncio.to_thread(
_catalog, config, tokens, registry=provider_registry
)
ui.set_models(models)
except Exception:
ui.set_models([])
while True:
try:
line = await ui.prompt_text()
except KeyboardInterrupt:
ui.console.print("[dim]Ctrl+D — выход.[/dim]")
continue
except EOFError:
break
text = line.strip()
if not text:
continue
if text.startswith("/"):
try:
action = await _handle_command(
text,
session,
ui,
config,
provider,
args,
provider_registry=provider_registry,
)
except (ProviderError, SessionError, ConfigError, OSError) as exc:
ui.error(exc.display() if isinstance(exc, ProviderError) else str(exc))
continue
if action == "quit":
break
if isinstance(action, tuple) and action[0] == "session":
session = action[1]
ui.attach(session)
continue
try:
await session.run_turn(text)
except KeyboardInterrupt:
await session.cancel_all_workers()
ui.error("Выполнение прервано пользователем. Воркеры остановлены.", title="Остановлено")
except (ProviderError, SessionError, ConfigError) as exc:
ui.error(exc.display() if isinstance(exc, ProviderError) else str(exc))
except Exception as exc: # pragma: no cover - defensive
if _opt(args, "debug", False):
ui.console.print(traceback.format_exc())
else:
ui.error(f"{type(exc).__name__}: {exc}")
if session.running_workers():
ui.console.print(
f"[yellow]В фоне остаются воркеры: "
f"{', '.join(w.id for w in session.running_workers())}. /cancel — остановить.[/yellow]"
)
try:
await session.cancel_all_workers()
session.save_all()
if provider_registry is not None:
await provider_registry.aclose()
else:
await provider.aclose()
except Exception:
pass
return 0
async def _handle_command(
text: str,
session: Session,
ui: UI,
config: Config,
provider: OpenAIClient,
args: argparse.Namespace,
provider_registry: ProviderRegistry | None = None,
) -> Any:
parts = text.split(maxsplit=1)
command = parts[0][1:]
arg = parts[1].strip() if len(parts) > 1 else ""
if command in {"quit", "exit", "q"}:
return "quit"
if command in {"help", "h", "?"}:
ui.print_help()
return None
if command == "models":
try:
models = await asyncio.to_thread(
_catalog,
config,
provider.tokens,
refresh=True,
registry=provider_registry,
)
ui.set_models(models)
except Exception as exc:
ui.error(f"Не удалось получить каталог моделей: {exc}")
return None
ui.print_models(models, session.config.orchestrator_model, session.config.worker_model)
return None
if command == "providers":
if provider_registry is None:
ui.console.print("Реестр провайдеров недоступен.")
return None
table = Table(title="Провайдеры", box=None)
table.add_column("id", style="cyan")
table.add_column("название")
table.add_column("base_url")
table.add_column("моделей", justify="right")
table.add_column("статус")
try:
catalog = await asyncio.to_thread(provider_registry.catalog, True, 6)
ui.set_models(catalog)
except Exception as exc:
ui.error(f"Не удалось получить модели: {exc}")
return None
for provider_id, profile in config.providers.items():
count = sum(1 for model in catalog if model.provider == provider_id)
table.add_row(
provider_id,
profile.name,
profile.base_url,
str(count),
" · основной" if provider_id == config.active_provider else "",
)
ui.console.print(table)
return None
if command == "retry":
if session.running_workers():
ui.error("Дождитесь завершения воркеров.")
return None
try:
await session.continue_turn()
except (ProviderError, SessionError) as exc:
ui.error(exc.display() if isinstance(exc, ProviderError) else str(exc))
return None
if command == "fork":
if session.running_workers():
ui.error("Дождитесь завершения воркеров перед форком.")
return None
indexes = visible_message_indices(session.main_messages)
if arg:
try:
number = int(arg)
except ValueError:
ui.error("Использование: /fork [номер сообщения]")
return None
if not 1 <= number <= len(indexes):
ui.error("Нет сообщения с таким номером.")
return None
index = indexes[number - 1]
else:
index = last_visible_index(session.main_messages)
if index is None:
ui.error("Нет сообщений для форка.")
return None
forked = session.fork_session(session.main_messages[: index + 1])
forked.listener = ui.on_event
ui.attach(forked)
ui.print_resumed(forked)
return ("session", forked)
if command == "delete":
if not arg:
ui.error("Использование: /delete <номер сообщения>")
return None
try:
number = int(arg)
indexes = visible_message_indices(session.main_messages)
if not 1 <= number <= len(indexes):
raise ValueError("Нет сообщения с таким номером.")
session.main_messages[:] = delete_visible_message(
session.main_messages, indexes[number - 1]
)
session.save_main()
ui.console.print("[dim]Сообщение удалено.[/dim]")
except ValueError as exc:
ui.error(str(exc))
return None
if command == "model":
if not arg:
ui.console.print(f"main: [cyan]{session.config.orchestrator_model}[/cyan]")
return None
session.config.orchestrator_model = arg
session.refresh_system_prompt()
session.save_all()
_safe_unknown_model(ui, arg)
ui.console.print(f"Главная модель: [cyan]{arg}[/cyan]")
return None
if command in {"worker-model", "worker_model"}:
if not arg:
ui.console.print(f"worker: [cyan]{session.config.worker_model}[/cyan]")
return None
session.config.worker_model = arg
session.refresh_system_prompt()
session.save_all()
_safe_unknown_model(ui, arg)
ui.console.print(f"Модель воркеров по умолчанию: [cyan]{arg}[/cyan]")
return None
if command in {"workers", "tasks"}:
ui.print_workers(session, arg or None)
return None
if command == "plan":
ui.print_plan(session)
return None
if command == "stats":
ui.print_stats(session)
return None
if command == "context":
ui.print_context(session)
return None
if command == "config":
ui.print_config(session)
return None
if command == "compact":
try:
await session.compact()
except (ProviderError, SessionError) as exc:
ui.error(exc.display() if isinstance(exc, ProviderError) else str(exc))
return None
if command == "cancel":
if not session.running_workers():
ui.console.print("[dim]Нет работающих воркеров.[/dim]")
return None
await session.cancel_all_workers()
ui.console.print("[yellow]Все воркеры остановлены.[/yellow]")
return None
if command == "workspace":
if not arg:
ui.console.print(f"workspace: [cyan]{session.cwd}[/cyan]")
return None
try:
new_path = session.change_workspace(arg)
ui.console.print(f"Workspace: [cyan]{new_path}[/cyan]")
except (ToolError, OSError) as exc:
ui.error(str(exc))
return None
if command == "new":
if session.running_workers():
ui.error("Сначала дождитесь завершения воркеров или выполните /cancel.")
return None
session.save_all()
new = Session.create(
sessions_root=session.store.sessions_root,
config=session.config,
provider=provider,
cwd=session.cwd,
provider_registry=provider_registry,
)
new.listener = ui.on_event
ui.attach(new)
ui.print_banner(new, describe_auth(provider.tokens))
return ("session", new)
if command == "sessions":
ui.print_sessions(SessionStore.list(session.store.sessions_root), session.id)
return None
if command == "resume":
if not arg:
ui.print_sessions(SessionStore.list(session.store.sessions_root), session.id)
return None
if session.running_workers():
ui.error("Сначала дождитесь завершения воркеров или выполните /cancel.")
return None
try:
session.save_all()
new = await asyncio.to_thread(
Session.load,
sessions_root=session.store.sessions_root,
session_id=arg,
config=session.config,
provider=provider,
provider_registry=provider_registry,
)
except (StorageError, ConfigError, OSError) as exc:
ui.error(str(exc))
return None
new.listener = ui.on_event
ui.attach(new)
ui.print_resumed(new)
return ("session", new)
ui.error(f"Неизвестная команда: /{command}. /help — список команд.")
return None
async def _run_once(
args: argparse.Namespace,
config: Config,
provider: OpenAIClient,
ui: UI,
goal: str,
provider_registry: ProviderRegistry | None = None,
) -> int:
workspace = _opt(args, "workspace")
cwd = (Path(workspace).expanduser().resolve() if workspace else Path.cwd().resolve())
cwd.mkdir(parents=True, exist_ok=True)
try:
session, resumed = await _open_session(
args=args,
config=config,
provider=provider,
cwd=cwd,
ui=ui,
provider_registry=provider_registry,
)
except (StorageError, ConfigError, OSError) as exc:
ui.error(str(exc))
return 2
if ui.is_tty:
ui.console.print(
f"[bold #22d3ee]AiRouter[/] [dim]· {config.orchestrator_model} + "
f"{config.worker_model} · {cwd}[/dim]"
)
elif resumed:
print(f"resumed session {session.id}", file=sys.stderr)
try:
await session.run_turn(goal)
except KeyboardInterrupt:
await session.cancel_all_workers()
print("\ninterrupted", file=sys.stderr)
return 130
except (ProviderError, SessionError, ConfigError) as exc:
ui.error(exc.display() if isinstance(exc, ProviderError) else str(exc))
return 1
except Exception as exc: # pragma: no cover
if _opt(args, "debug", False):
traceback.print_exc()
else:
ui.error(f"{type(exc).__name__}: {exc}")
return 1
finally:
try:
session.save_all()
await session.cancel_all_workers()
if provider_registry is not None:
await provider_registry.aclose()
else:
await provider.aclose()
except Exception:
pass
return 0
async def async_main(args: argparse.Namespace) -> int:
cwd = Path.cwd().resolve()
command = _opt(args, "command", "interactive") or "interactive"
workspace = _opt(args, "workspace")
project_cwd = (Path(workspace).expanduser().resolve() if workspace else cwd)
if command in {"version", "--version"}:
print(f"{APP_NAME} {__version__}")
return 0
if command == "init":
force = bool(_opt(args, "force", False))
try:
path = write_sample_config(cwd / CONFIG_FILENAME, force=force)
print(f"Создан {path}")
print("Отредактируйте модели и запустите `airouter`.")
return 0
except ConfigError as exc:
print(str(exc), file=sys.stderr)
return 2
if command in {"service", "ctl", "skill", "update"}:
try:
result = await handle_integration_command(args, cwd)
if result is not None:
return result
except (ConfigError, OSError) as exc:
print(str(exc), file=sys.stderr)
return 2
try:
config = _make_config(args, project_cwd)
except ConfigError as exc:
print(f"Ошибка конфигурации: {exc}", file=sys.stderr)
return 2
if command == "sessions":
sessions = SessionStore.list(_sessions_root(project_cwd))
console = Console(no_color=_opt(args, "no_color", False))
if not sessions:
console.print("[dim]Сессий пока нет.[/dim]")
else:
table = Table(title="Сессии", box=None)
table.add_column("id", style="cyan")
table.add_column("обновлена")
table.add_column("сообщений", justify="right")
table.add_column("модель")
table.add_column("цель")
for item in sessions:
table.add_row(
str(item.get("id")),
time.strftime("%Y-%m-%d %H:%M", time.localtime(item.get("updated_at", 0))),
str(item.get("messages", 0)),
str(item.get("model", "")),
str(item.get("goal", ""))[:80],
)
console.print(table)
return 0
if command == "doctor":
return await _doctor(args, config)
if command in {"models", "providers"}:
ui = UI(config, no_color=_opt(args, "no_color", False))
registry = ProviderRegistry(config)
try:
models = await asyncio.to_thread(
registry.catalog,
refresh=bool(_opt(args, "refresh", False)),
timeout=6,
)
finally:
await registry.aclose()
ui.set_models(models)
if command == "providers":
table = Table(title="Провайдеры", box=None)
table.add_column("id", style="cyan")
table.add_column("название")
table.add_column("base_url")
table.add_column("моделей", justify="right")
table.add_column("статус")
for provider_id, profile in config.providers.items():
count = sum(1 for model in models if model.provider == provider_id)
table.add_row(
provider_id,
profile.name,
profile.base_url,
str(count),
"основной" if provider_id == config.active_provider else profile.kind,
)
ui.console.print(table)
else:
ui.print_models(models, config.orchestrator_model, config.worker_model)
active = config.orchestrator_provider or config.active_provider
profile = config.providers[active]
ui.console.print(
f"[dim]{active}: {profile.base_url} · провайдеров: {len(config.providers)}[/dim]"
)
return 0
if command == "run":
goal = " ".join(getattr(args, "goal", [])).strip()
if not goal:
print("Использование: airouter run \"цель\"", file=sys.stderr)
return 2
try:
provider, _, registry = _make_provider(config)
except ConfigError as exc:
UI(config, no_color=_opt(args, "no_color", False)).error(str(exc))
return 2
ui = UI(config, no_color=_opt(args, "no_color", False))
return await _run_once(
args, config, provider, ui, goal, provider_registry=registry
)
if command not in {"interactive", "tui", "chat", "attach"}:
print(f"Неизвестная команда: {command}. Доступно: run, tui, attach, service, ctl, skill, update, models, providers, sessions, init, doctor.", file=sys.stderr)
return 2
if not sys.stdin.isatty():
print(
"Интерактивный режим требует терминал. Используйте: airouter run \"цель\"",
file=sys.stderr,
)
return 2
try:
provider, _, registry = _make_provider(config)
except ConfigError as exc:
UI(config, no_color=_opt(args, "no_color", False)).error(str(exc))
return 2
ui = UI(config, no_color=_opt(args, "no_color", False))
try:
return await _interactive(
args, config, provider, ui, provider_registry=registry
)
finally:
try:
await registry.aclose()
except Exception:
pass
async def _doctor(args: argparse.Namespace, config: Config) -> int:
console = Console(no_color=_opt(args, "no_color", False))
table = Table(title="AiRouter doctor", box=None)
table.add_column("проверка", style="cyan")
table.add_column("значение")
table.add_row("версия", __version__)
table.add_row("python", platform.python_version())
table.add_row("cwd", str(Path.cwd()))
active_provider = config.orchestrator_provider or config.active_provider
active_profile = config.providers[active_provider]
table.add_row("provider", active_provider)
table.add_row("base_url", active_profile.base_url)
table.add_row("providers", str(len(config.providers)))
table.add_row("main model", f"{active_provider}/{config.orchestrator_model}")
table.add_row("worker model", config.worker_model)
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("opencode CLI", shutil.which("opencode") or "не найден")
try:
import textual
table.add_row("textual", textual.__version__)
except Exception:
table.add_row("textual", "не найден (TUI недоступен)")
table.add_row("git", shutil.which("git") or "не найден")
table.add_row("ripgrep", shutil.which("rg") or "не найден (fallback поиск)")
registry = ProviderRegistry(config)
tokens = registry.default_client(role="orchestrator").tokens
if tokens:
for index, token in enumerate(tokens[:4]):
state = "просрочен" if token.expired else "не проверен"
table.add_row(f"token {index + 1}", f"{token.source} · {token.kind} · {state}")
else:
table.add_row("token", "не найден" + (" (нужен для OpenCode)" if active_profile.auto_auth else ""))
console.print(table)
if not tokens and active_profile.auto_auth and "opencode.ai" in active_profile.base_url:
console.print(f"[yellow]{token_hint(config)}[/yellow]")
await registry.aclose()
return 2
try:
models = await asyncio.to_thread(registry.catalog, timeout=6)
console.print(f"[green]Каталог моделей доступен:[/green] {len(models)} моделей")
if not any(model.id == config.orchestrator_model for model in models):
console.print(
f"[yellow]Главная модель {config.orchestrator_model!r} не найдена в каталоге.[/yellow]"
)
except Exception as exc:
console.print(f"[yellow]Каталог моделей недоступен:[/yellow] {exc}")
if _opt(args, "live", False):
provider = registry.default_client(role="orchestrator")
try:
turn = await provider.stream_chat(
model=config.orchestrator_model,
messages=[{"role": "user", "content": "Reply with exactly: OK"}],
session_id="ses_airouter_doctor",
max_tokens=64,
)
text = (turn.content or turn.reasoning or "").strip().replace("\n", " ")[:120]
console.print(f"[green]Live-проверка:[/green] {text or '(пустой ответ)'}")
except ProviderError as exc:
console.print(f"[red]Live-проверка не прошла:[/red] {exc.display()}")
return 1
finally:
await registry.aclose()
else:
await registry.aclose()
return 0
def _run_tui_cli(args: argparse.Namespace) -> int:
workspace = _opt(args, "workspace")
project_cwd = (Path(workspace).expanduser().resolve() if workspace else Path.cwd().resolve())
try:
config = _make_config(args, project_cwd)
except ConfigError as exc:
print(f"Ошибка конфигурации: {exc}", file=sys.stderr)
return 2
if _maybe_update_sync(args):
return 0
service_client: ServiceClient | None = None
registry: ProviderRegistry | None = None
provider: OpenAIClient | None = None
if _opt(args, "command") == "attach":
runtime = load_service_runtime()
if not runtime:
print("Сервис не запущен. Выполните `airouter service start`.", file=sys.stderr)
return 2
service_client = ServiceClient(str(runtime["url"]), str(runtime["token"]))
else:
try:
provider, _, registry = _make_provider(config)
except ConfigError as exc:
UI(config, no_color=_opt(args, "no_color", False)).error(str(exc))
return 2
try:
from .tui.app import run_tui_app
return run_tui_app(
config=config,
provider=provider, # type: ignore[arg-type]
sessions_root=_sessions_root(project_cwd),
cwd=project_cwd,
resume=bool(_opt(args, "continue_session", False)),
session_id=_opt(args, "session_id"),
model_override=_opt(args, "model"),
worker_model_override=_opt(args, "worker_model"),
max_workers_override=_opt(args, "max_workers"),
provider_registry=registry,
service_client=service_client,
)
finally:
try:
if registry is not None:
asyncio.run(registry.aclose())
elif service_client is not None:
asyncio.run(service_client.aclose())
except Exception:
pass
def main() -> None:
parser = _build_parser()
args = parser.parse_args()
command = _opt(args, "command", None)
use_tui = (
command in {None, "tui", "attach"}
and not bool(_opt(args, "classic", False))
and sys.stdin.isatty()
and sys.stdout.isatty()
)
if use_tui:
try:
code = _run_tui_cli(args)
except KeyboardInterrupt:
code = 130
sys.exit(code)
try:
code = asyncio.run(async_main(args))
except KeyboardInterrupt:
code = 130
sys.exit(code)
if __name__ == "__main__":
main()