Files
AiRouter/airouter/cli.py
T
2026-11-19 20:48:42 +07:00

687 lines
25 KiB
Python

"""Command-line entry point."""
from __future__ import annotations
import argparse
import asyncio
import platform
import shutil
import sys
import time
import traceback
from pathlib import Path
from typing import Any
from rich.console import Console
from rich.table import Table
from . import APP_NAME, __version__
from .auth import describe_auth, resolve_tokens, token_hint
from .config import (
CONFIG_FILENAME,
Config,
ConfigError,
load_config,
write_sample_config,
)
from .models import ModelInfo, fetch_models
from .provider import OpenAIClient, ProviderError
from .session import Session, SessionError
from .storage import SessionStore, StorageError
from .ui import UI
from .workspace import ReadOnlyFS
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(
"--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)
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")
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="показать версию")
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)
return config
def _make_provider(config: Config) -> tuple[OpenAIClient, list[Any]]:
tokens = resolve_tokens(config)
if not tokens and "opencode.ai" in config.provider.base_url:
raise ConfigError(token_hint(config))
return OpenAIClient(config, tokens), tokens
def _catalog(config: Config, tokens: list[Any], *, refresh: bool = False) -> list[ModelInfo]:
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,
) -> 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,
)
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,
)
resumed = True
else:
session = Session.create(
sessions_root=sessions_root,
config=config,
provider=provider,
cwd=cwd,
)
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
) -> 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
)
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)
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)
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()
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,
) -> 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)
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 == "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
new_path = Path(arg).expanduser()
if not new_path.is_absolute():
new_path = (session.cwd / new_path).resolve()
if new_path.exists() and not new_path.is_dir():
ui.error(f"Это не директория: {new_path}")
return None
new_path.mkdir(parents=True, exist_ok=True)
session.cwd = new_path
session.read_fs = ReadOnlyFS(new_path, session.config.limits)
session.refresh_system_prompt()
session.main_messages.append(
{
"role": "user",
"content": (
f"[system] Рабочая папка сессии изменена на {new_path}. "
"Новые воркеры без явного workspace будут работать там."
),
}
)
session.save_all()
ui.console.print(f"Workspace: [cyan]{new_path}[/cyan]")
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,
)
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,
)
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
) -> 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
)
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()
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
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 == "models":
ui = UI(config, no_color=_opt(args, "no_color", False))
tokens = resolve_tokens(config)
models = await asyncio.to_thread(
_catalog, config, tokens, refresh=bool(_opt(args, "refresh", False))
)
ui.set_models(models)
ui.print_models(models, config.orchestrator_model, config.worker_model)
console = ui.console
console.print(
f"[dim]base_url: {config.provider.base_url} · auth: {describe_auth(tokens)}[/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, _ = _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)
if command not in {"interactive", "tui", "chat"}:
print(f"Неизвестная команда: {command}. Доступно: run, tui, models, sessions, init, doctor.", file=sys.stderr)
return 2
if not sys.stdin.isatty():
print(
"Интерактивный режим требует терминал. Используйте: airouter run \"цель\"",
file=sys.stderr,
)
return 2
try:
provider, _ = _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)
finally:
try:
await provider.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()))
table.add_row("base_url", config.provider.base_url)
table.add_row("main model", 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 поиск)")
tokens = resolve_tokens(config)
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 "opencode.ai" in config.provider.base_url else ""))
console.print(table)
if not tokens and "opencode.ai" in config.provider.base_url:
console.print(f"[yellow]{token_hint(config)}[/yellow]")
return 2
try:
models = await asyncio.to_thread(_catalog, config, tokens)
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 = OpenAIClient(config, tokens)
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 provider.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
try:
provider, _ = _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,
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"),
)
finally:
try:
asyncio.run(provider.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"}
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()