1"""Command-line entry point."""
2
3from __future__ import annotations
4
5import argparse
6import asyncio
7import platform
8import shutil
9import sys
10import time
11import traceback
12from pathlib import Path
13from typing import Any
14
15from rich.console import Console
16from rich.table import Table
17
18from . import APP_NAME, __version__
19from .auth import describe_auth, resolve_tokens, token_hint
20from .config import (
21 CONFIG_FILENAME,
22 Config,
23 ConfigError,
24 load_config,
25 write_sample_config,
26)
27from .models import ModelInfo, fetch_models
28from .provider import OpenAIClient, ProviderError
29from .session import Session, SessionError
30from .storage import SessionStore, StorageError
31from .ui import UI
32from .workspace import ReadOnlyFS
33
34
35def _common_options(parser: argparse.ArgumentParser) -> None:
36 parser.add_argument(
37 "-c",
38 "--continue",
39 dest="continue_session",
40 action="store_true",
41 default=argparse.SUPPRESS,
42 help="продолжить последнюю сессию",
43 )
44 parser.add_argument("-s", "--session", dest="session_id", default=argparse.SUPPRESS)
45 parser.add_argument("--config", type=Path, default=argparse.SUPPRESS)
46 parser.add_argument("-m", "--model", dest="model", default=argparse.SUPPRESS)
47 parser.add_argument("-w", "--worker-model", dest="worker_model", default=argparse.SUPPRESS)
48 parser.add_argument("--base-url", default=argparse.SUPPRESS)
49 parser.add_argument(
50 "--workspace", default=argparse.SUPPRESS, help="рабочая папка сессии"
51 )
52 parser.add_argument("--max-workers", type=int, default=argparse.SUPPRESS)
53 parser.add_argument("--no-color", action="store_true", default=argparse.SUPPRESS)
54 parser.add_argument("--debug", action="store_true", default=argparse.SUPPRESS)
55
56
57def _build_parser() -> argparse.ArgumentParser:
58 parser = argparse.ArgumentParser(
59 prog="airouter",
60 description="AiRouter — главная модель планирует работу и следит за изолированными воркерами.",
61 )
62 _common_options(parser)
63 parser.add_argument("-v", "--version", action="version", version=f"{APP_NAME} {__version__}")
64 parser.add_argument(
65 "--classic",
66 action="store_true",
67 help="классический prompt-интерфейс вместо TUI",
68 )
69
70 sub = parser.add_subparsers(dest="command")
71 run = sub.add_parser("run", help="выполнить цель без интерактивного режима")
72 _common_options(run)
73 run.add_argument("goal", nargs="+", help="цель для главной модели")
74
75 tui = sub.add_parser("tui", help="запустить интерактивный TUI")
76 _common_options(tui)
77 tui.add_argument(
78 "--classic", action="store_true", default=argparse.SUPPRESS, help=argparse.SUPPRESS
79 )
80
81 models = sub.add_parser("models", help="показать каталог моделей")
82 _common_options(models)
83 models.add_argument("--refresh", action="store_true")
84
85 sessions = sub.add_parser("sessions", help="показать сессии в текущей папке")
86 _common_options(sessions)
87
88 init = sub.add_parser("init", help="создать .airouter.toml")
89 init.add_argument("--force", action="store_true")
90
91 doctor = sub.add_parser("doctor", help="проверить окружение и доступ к API")
92 _common_options(doctor)
93 doctor.add_argument("--live", action="store_true", help="сделать тестовый запрос к модели")
94
95 sub.add_parser("version", help="показать версию")
96
97 return parser
98
99
100def _opt(args: argparse.Namespace, name: str, default: Any = None) -> Any:
101 return getattr(args, name, default)
102
103
104def _sessions_root(cwd: Path) -> Path:
105 return cwd / ".airouter" / "sessions"
106
107
108def _make_config(args: argparse.Namespace, cwd: Path) -> Config:
109 config = load_config(
110 cwd,
111 config_path=_opt(args, "config"),
112 base_url=_opt(args, "base_url"),
113 model=_opt(args, "model"),
114 worker_model=_opt(args, "worker_model"),
115 )
116 max_workers = _opt(args, "max_workers")
117 if max_workers:
118 config.limits.max_workers = max(1, max_workers)
119 return config
120
121
122def _make_provider(config: Config) -> tuple[OpenAIClient, list[Any]]:
123 tokens = resolve_tokens(config)
124 if not tokens and "opencode.ai" in config.provider.base_url:
125 raise ConfigError(token_hint(config))
126 return OpenAIClient(config, tokens), tokens
127
128
129def _catalog(config: Config, tokens: list[Any], *, refresh: bool = False) -> list[ModelInfo]:
130 token = tokens[0].value if tokens else None
131 return fetch_models(config.provider.base_url, token=token, refresh=refresh, timeout=6)
132
133
134async def _open_session(
135 *,
136 args: argparse.Namespace,
137 config: Config,
138 provider: OpenAIClient,
139 cwd: Path,
140 ui: UI,
141) -> tuple[Session, bool]:
142 sessions_root = _sessions_root(cwd)
143 resumed = False
144 if _opt(args, "session_id"):
145 session = await asyncio.to_thread(
146 Session.load,
147 sessions_root=sessions_root,
148 session_id=_opt(args, "session_id"),
149 config=config,
150 provider=provider,
151 )
152 resumed = True
153 elif _opt(args, "continue_session", False):
154 latest = SessionStore.latest(sessions_root)
155 if latest is None:
156 raise StorageError("Нет сохранённых сессий в этой папке")
157 session = await asyncio.to_thread(
158 Session.load,
159 sessions_root=sessions_root,
160 session_id=latest.id,
161 config=config,
162 provider=provider,
163 )
164 resumed = True
165 else:
166 session = Session.create(
167 sessions_root=sessions_root,
168 config=config,
169 provider=provider,
170 cwd=cwd,
171 )
172 if resumed:
173 if _opt(args, "model"):
174 session.config.orchestrator_model = _opt(args, "model")
175 if _opt(args, "worker_model"):
176 session.config.worker_model = _opt(args, "worker_model")
177 if _opt(args, "max_workers"):
178 session.config.limits.max_workers = max(1, int(_opt(args, "max_workers")))
179 session.refresh_system_prompt()
180 session.listener = ui.on_event
181 ui.attach(session)
182 return session, resumed
183
184
185def _safe_unknown_model(ui: UI, model: str) -> None:
186 if not ui.models_loaded:
187 return
188 if not any(item.id == model for item in ui.get_models()):
189 ui.console.print(
190 f"[yellow]Модель {model!r} отсутствует в каталоге. Запрос всё равно будет отправлен.[/yellow]"
191 )
192
193
194async def _interactive(
195 args: argparse.Namespace, config: Config, provider: OpenAIClient, ui: UI
196) -> int:
197 workspace = _opt(args, "workspace")
198 cwd = (Path(workspace).expanduser().resolve() if workspace else Path.cwd().resolve())
199 cwd.mkdir(parents=True, exist_ok=True)
200 try:
201 session, resumed = await _open_session(
202 args=args, config=config, provider=provider, cwd=cwd, ui=ui
203 )
204 except (StorageError, ConfigError, OSError) as exc:
205 ui.error(str(exc))
206 return 2
207 tokens = provider.tokens
208 ui.print_banner(session, describe_auth(tokens))
209 if resumed:
210 ui.print_resumed(session)
211
212 try:
213 models = await asyncio.to_thread(_catalog, config, tokens)
214 ui.set_models(models)
215 except Exception:
216 ui.set_models([])
217
218 while True:
219 try:
220 line = await ui.prompt_text()
221 except KeyboardInterrupt:
222 ui.console.print("[dim]Ctrl+D — выход.[/dim]")
223 continue
224 except EOFError:
225 break
226 text = line.strip()
227 if not text:
228 continue
229 if text.startswith("/"):
230 try:
231 action = await _handle_command(text, session, ui, config, provider, args)
232 except (ProviderError, SessionError, ConfigError, OSError) as exc:
233 ui.error(exc.display() if isinstance(exc, ProviderError) else str(exc))
234 continue
235 if action == "quit":
236 break
237 if isinstance(action, tuple) and action[0] == "session":
238 session = action[1]
239 ui.attach(session)
240 continue
241 try:
242 await session.run_turn(text)
243 except KeyboardInterrupt:
244 await session.cancel_all_workers()
245 ui.error("Выполнение прервано пользователем. Воркеры остановлены.", title="Остановлено")
246 except (ProviderError, SessionError, ConfigError) as exc:
247 ui.error(exc.display() if isinstance(exc, ProviderError) else str(exc))
248 except Exception as exc: # pragma: no cover - defensive
249 if _opt(args, "debug", False):
250 ui.console.print(traceback.format_exc())
251 else:
252 ui.error(f"{type(exc).__name__}: {exc}")
253 if session.running_workers():
254 ui.console.print(
255 f"[yellow]В фоне остаются воркеры: "
256 f"{', '.join(w.id for w in session.running_workers())}. /cancel — остановить.[/yellow]"
257 )
258
259 try:
260 await session.cancel_all_workers()
261 session.save_all()
262 await provider.aclose()
263 except Exception:
264 pass
265 return 0
266
267
268async def _handle_command(
269 text: str,
270 session: Session,
271 ui: UI,
272 config: Config,
273 provider: OpenAIClient,
274 args: argparse.Namespace,
275) -> Any:
276 parts = text.split(maxsplit=1)
277 command = parts[0][1:]
278 arg = parts[1].strip() if len(parts) > 1 else ""
279 if command in {"quit", "exit", "q"}:
280 return "quit"
281 if command in {"help", "h", "?"}:
282 ui.print_help()
283 return None
284 if command == "models":
285 try:
286 models = await asyncio.to_thread(_catalog, config, provider.tokens, refresh=True)
287 ui.set_models(models)
288 except Exception as exc:
289 ui.error(f"Не удалось получить каталог моделей: {exc}")
290 return None
291 ui.print_models(models, session.config.orchestrator_model, session.config.worker_model)
292 return None
293 if command == "model":
294 if not arg:
295 ui.console.print(f"main: [cyan]{session.config.orchestrator_model}[/cyan]")
296 return None
297 session.config.orchestrator_model = arg
298 session.refresh_system_prompt()
299 session.save_all()
300 _safe_unknown_model(ui, arg)
301 ui.console.print(f"Главная модель: [cyan]{arg}[/cyan]")
302 return None
303 if command in {"worker-model", "worker_model"}:
304 if not arg:
305 ui.console.print(f"worker: [cyan]{session.config.worker_model}[/cyan]")
306 return None
307 session.config.worker_model = arg
308 session.refresh_system_prompt()
309 session.save_all()
310 _safe_unknown_model(ui, arg)
311 ui.console.print(f"Модель воркеров по умолчанию: [cyan]{arg}[/cyan]")
312 return None
313 if command in {"workers", "tasks"}:
314 ui.print_workers(session, arg or None)
315 return None
316 if command == "plan":
317 ui.print_plan(session)
318 return None
319 if command == "stats":
320 ui.print_stats(session)
321 return None
322 if command == "context":
323 ui.print_context(session)
324 return None
325 if command == "config":
326 ui.print_config(session)
327 return None
328 if command == "compact":
329 try:
330 await session.compact()
331 except (ProviderError, SessionError) as exc:
332 ui.error(exc.display() if isinstance(exc, ProviderError) else str(exc))
333 return None
334 if command == "cancel":
335 if not session.running_workers():
336 ui.console.print("[dim]Нет работающих воркеров.[/dim]")
337 return None
338 await session.cancel_all_workers()
339 ui.console.print("[yellow]Все воркеры остановлены.[/yellow]")
340 return None
341 if command == "workspace":
342 if not arg:
343 ui.console.print(f"workspace: [cyan]{session.cwd}[/cyan]")
344 return None
345 new_path = Path(arg).expanduser()
346 if not new_path.is_absolute():
347 new_path = (session.cwd / new_path).resolve()
348 if new_path.exists() and not new_path.is_dir():
349 ui.error(f"Это не директория: {new_path}")
350 return None
351 new_path.mkdir(parents=True, exist_ok=True)
352 session.cwd = new_path
353 session.read_fs = ReadOnlyFS(new_path, session.config.limits)
354 session.refresh_system_prompt()
355 session.main_messages.append(
356 {
357 "role": "user",
358 "content": (
359 f"[system] Рабочая папка сессии изменена на {new_path}. "
360 "Новые воркеры без явного workspace будут работать там."
361 ),
362 }
363 )
364 session.save_all()
365 ui.console.print(f"Workspace: [cyan]{new_path}[/cyan]")
366 return None
367 if command == "new":
368 if session.running_workers():
369 ui.error("Сначала дождитесь завершения воркеров или выполните /cancel.")
370 return None
371 session.save_all()
372 new = Session.create(
373 sessions_root=session.store.sessions_root,
374 config=session.config,
375 provider=provider,
376 cwd=session.cwd,
377 )
378 new.listener = ui.on_event
379 ui.attach(new)
380 ui.print_banner(new, describe_auth(provider.tokens))
381 return ("session", new)
382 if command == "sessions":
383 ui.print_sessions(SessionStore.list(session.store.sessions_root), session.id)
384 return None
385 if command == "resume":
386 if not arg:
387 ui.print_sessions(SessionStore.list(session.store.sessions_root), session.id)
388 return None
389 if session.running_workers():
390 ui.error("Сначала дождитесь завершения воркеров или выполните /cancel.")
391 return None
392 try:
393 session.save_all()
394 new = await asyncio.to_thread(
395 Session.load,
396 sessions_root=session.store.sessions_root,
397 session_id=arg,
398 config=session.config,
399 provider=provider,
400 )
401 except (StorageError, ConfigError, OSError) as exc:
402 ui.error(str(exc))
403 return None
404 new.listener = ui.on_event
405 ui.attach(new)
406 ui.print_resumed(new)
407 return ("session", new)
408 ui.error(f"Неизвестная команда: /{command}. /help — список команд.")
409 return None
410
411
412async def _run_once(
413 args: argparse.Namespace, config: Config, provider: OpenAIClient, ui: UI, goal: str
414) -> int:
415 workspace = _opt(args, "workspace")
416 cwd = (Path(workspace).expanduser().resolve() if workspace else Path.cwd().resolve())
417 cwd.mkdir(parents=True, exist_ok=True)
418 try:
419 session, resumed = await _open_session(
420 args=args, config=config, provider=provider, cwd=cwd, ui=ui
421 )
422 except (StorageError, ConfigError, OSError) as exc:
423 ui.error(str(exc))
424 return 2
425 if ui.is_tty:
426 ui.console.print(
427 f"[bold #22d3ee]AiRouter[/] [dim]· {config.orchestrator_model} + "
428 f"{config.worker_model} · {cwd}[/dim]"
429 )
430 elif resumed:
431 print(f"resumed session {session.id}", file=sys.stderr)
432 try:
433 await session.run_turn(goal)
434 except KeyboardInterrupt:
435 await session.cancel_all_workers()
436 print("\ninterrupted", file=sys.stderr)
437 return 130
438 except (ProviderError, SessionError, ConfigError) as exc:
439 ui.error(exc.display() if isinstance(exc, ProviderError) else str(exc))
440 return 1
441 except Exception as exc: # pragma: no cover
442 if _opt(args, "debug", False):
443 traceback.print_exc()
444 else:
445 ui.error(f"{type(exc).__name__}: {exc}")
446 return 1
447 finally:
448 try:
449 session.save_all()
450 await session.cancel_all_workers()
451 await provider.aclose()
452 except Exception:
453 pass
454 return 0
455
456
457async def async_main(args: argparse.Namespace) -> int:
458 cwd = Path.cwd().resolve()
459 command = _opt(args, "command", "interactive") or "interactive"
460 workspace = _opt(args, "workspace")
461 project_cwd = (Path(workspace).expanduser().resolve() if workspace else cwd)
462
463 if command in {"version", "--version"}:
464 print(f"{APP_NAME} {__version__}")
465 return 0
466
467 if command == "init":
468 force = bool(_opt(args, "force", False))
469 try:
470 path = write_sample_config(cwd / CONFIG_FILENAME, force=force)
471 print(f"Создан {path}")
472 print("Отредактируйте модели и запустите `airouter`.")
473 return 0
474 except ConfigError as exc:
475 print(str(exc), file=sys.stderr)
476 return 2
477
478 try:
479 config = _make_config(args, project_cwd)
480 except ConfigError as exc:
481 print(f"Ошибка конфигурации: {exc}", file=sys.stderr)
482 return 2
483
484 if command == "sessions":
485 sessions = SessionStore.list(_sessions_root(project_cwd))
486 console = Console(no_color=_opt(args, "no_color", False))
487 if not sessions:
488 console.print("[dim]Сессий пока нет.[/dim]")
489 else:
490 table = Table(title="Сессии", box=None)
491 table.add_column("id", style="cyan")
492 table.add_column("обновлена")
493 table.add_column("сообщений", justify="right")
494 table.add_column("модель")
495 table.add_column("цель")
496 for item in sessions:
497 table.add_row(
498 str(item.get("id")),
499 time.strftime("%Y-%m-%d %H:%M", time.localtime(item.get("updated_at", 0))),
500 str(item.get("messages", 0)),
501 str(item.get("model", "")),
502 str(item.get("goal", ""))[:80],
503 )
504 console.print(table)
505 return 0
506
507 if command == "doctor":
508 return await _doctor(args, config)
509
510 if command == "models":
511 ui = UI(config, no_color=_opt(args, "no_color", False))
512 tokens = resolve_tokens(config)
513 models = await asyncio.to_thread(
514 _catalog, config, tokens, refresh=bool(_opt(args, "refresh", False))
515 )
516 ui.set_models(models)
517 ui.print_models(models, config.orchestrator_model, config.worker_model)
518 console = ui.console
519 console.print(
520 f"[dim]base_url: {config.provider.base_url} · auth: {describe_auth(tokens)}[/dim]"
521 )
522 return 0
523
524 if command == "run":
525 goal = " ".join(getattr(args, "goal", [])).strip()
526 if not goal:
527 print("Использование: airouter run \"цель\"", file=sys.stderr)
528 return 2
529 try:
530 provider, _ = _make_provider(config)
531 except ConfigError as exc:
532 UI(config, no_color=_opt(args, "no_color", False)).error(str(exc))
533 return 2
534 ui = UI(config, no_color=_opt(args, "no_color", False))
535 return await _run_once(args, config, provider, ui, goal)
536
537 if command not in {"interactive", "tui", "chat"}:
538 print(f"Неизвестная команда: {command}. Доступно: run, tui, models, sessions, init, doctor.", file=sys.stderr)
539 return 2
540
541 if not sys.stdin.isatty():
542 print(
543 "Интерактивный режим требует терминал. Используйте: airouter run \"цель\"",
544 file=sys.stderr,
545 )
546 return 2
547
548 try:
549 provider, _ = _make_provider(config)
550 except ConfigError as exc:
551 UI(config, no_color=_opt(args, "no_color", False)).error(str(exc))
552 return 2
553 ui = UI(config, no_color=_opt(args, "no_color", False))
554 try:
555 return await _interactive(args, config, provider, ui)
556 finally:
557 try:
558 await provider.aclose()
559 except Exception:
560 pass
561
562
563async def _doctor(args: argparse.Namespace, config: Config) -> int:
564 console = Console(no_color=_opt(args, "no_color", False))
565 table = Table(title="AiRouter doctor", box=None)
566 table.add_column("проверка", style="cyan")
567 table.add_column("значение")
568 table.add_row("версия", __version__)
569 table.add_row("python", platform.python_version())
570 table.add_row("cwd", str(Path.cwd()))
571 table.add_row("base_url", config.provider.base_url)
572 table.add_row("main model", config.orchestrator_model)
573 table.add_row("worker model", config.worker_model)
574 table.add_row("project config", str(config.project_config_path or "—"))
575 table.add_row("global config", str(config.global_config_path or "—"))
576 table.add_row("opencode CLI", shutil.which("opencode") or "не найден")
577 try:
578 import textual
579
580 table.add_row("textual", textual.__version__)
581 except Exception:
582 table.add_row("textual", "не найден (TUI недоступен)")
583 table.add_row("git", shutil.which("git") or "не найден")
584 table.add_row("ripgrep", shutil.which("rg") or "не найден (fallback поиск)")
585
586 tokens = resolve_tokens(config)
587 if tokens:
588 for index, token in enumerate(tokens[:4]):
589 state = "просрочен" if token.expired else "не проверен"
590 table.add_row(f"token {index + 1}", f"{token.source} · {token.kind} · {state}")
591 else:
592 table.add_row("token", "не найден" + (" (нужен для OpenCode)" if "opencode.ai" in config.provider.base_url else ""))
593 console.print(table)
594
595 if not tokens and "opencode.ai" in config.provider.base_url:
596 console.print(f"[yellow]{token_hint(config)}[/yellow]")
597 return 2
598
599 try:
600 models = await asyncio.to_thread(_catalog, config, tokens)
601 console.print(f"[green]Каталог моделей доступен:[/green] {len(models)} моделей")
602 if not any(model.id == config.orchestrator_model for model in models):
603 console.print(
604 f"[yellow]Главная модель {config.orchestrator_model!r} не найдена в каталоге.[/yellow]"
605 )
606 except Exception as exc:
607 console.print(f"[yellow]Каталог моделей недоступен:[/yellow] {exc}")
608
609 if _opt(args, "live", False):
610 provider = OpenAIClient(config, tokens)
611 try:
612 turn = await provider.stream_chat(
613 model=config.orchestrator_model,
614 messages=[{"role": "user", "content": "Reply with exactly: OK"}],
615 session_id="ses_airouter_doctor",
616 max_tokens=64,
617 )
618 text = (turn.content or turn.reasoning or "").strip().replace("\n", " ")[:120]
619 console.print(f"[green]Live-проверка:[/green] {text or '(пустой ответ)'}")
620 except ProviderError as exc:
621 console.print(f"[red]Live-проверка не прошла:[/red] {exc.display()}")
622 return 1
623 finally:
624 await provider.aclose()
625 return 0
626
627
628def _run_tui_cli(args: argparse.Namespace) -> int:
629 workspace = _opt(args, "workspace")
630 project_cwd = (Path(workspace).expanduser().resolve() if workspace else Path.cwd().resolve())
631 try:
632 config = _make_config(args, project_cwd)
633 except ConfigError as exc:
634 print(f"Ошибка конфигурации: {exc}", file=sys.stderr)
635 return 2
636 try:
637 provider, _ = _make_provider(config)
638 except ConfigError as exc:
639 UI(config, no_color=_opt(args, "no_color", False)).error(str(exc))
640 return 2
641 try:
642 from .tui.app import run_tui_app
643
644 return run_tui_app(
645 config=config,
646 provider=provider,
647 sessions_root=_sessions_root(project_cwd),
648 cwd=project_cwd,
649 resume=bool(_opt(args, "continue_session", False)),
650 session_id=_opt(args, "session_id"),
651 model_override=_opt(args, "model"),
652 worker_model_override=_opt(args, "worker_model"),
653 max_workers_override=_opt(args, "max_workers"),
654 )
655 finally:
656 try:
657 asyncio.run(provider.aclose())
658 except Exception:
659 pass
660
661
662def main() -> None:
663 parser = _build_parser()
664 args = parser.parse_args()
665 command = _opt(args, "command", None)
666 use_tui = (
667 command in {None, "tui"}
668 and not bool(_opt(args, "classic", False))
669 and sys.stdin.isatty()
670 and sys.stdout.isatty()
671 )
672 if use_tui:
673 try:
674 code = _run_tui_cli(args)
675 except KeyboardInterrupt:
676 code = 130
677 sys.exit(code)
678 try:
679 code = asyncio.run(async_main(args))
680 except KeyboardInterrupt:
681 code = 130
682 sys.exit(code)
683
684
685if __name__ == "__main__":
686 main()