418 lines
16 KiB
Python
418 lines
16 KiB
Python
"""CLI commands for the AiRouter sync service and OpenCode integration."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import asyncio
|
|
import json
|
|
import os
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from .config import Config, ConfigError, load_config
|
|
from .providers import ProviderRegistry
|
|
from .service import (
|
|
DEFAULT_SERVICE_HOST,
|
|
DEFAULT_SERVICE_PORT,
|
|
SERVICE_RUNTIME,
|
|
ServiceClient,
|
|
load_service_runtime,
|
|
run_service,
|
|
)
|
|
from .update import check_for_updates, install_update
|
|
|
|
|
|
INTEGRATION_COMMANDS = {"service", "attach", "ctl", "skill", "update"}
|
|
|
|
|
|
def _opt(args: argparse.Namespace, name: str, default: Any = None) -> Any:
|
|
return getattr(args, name, default)
|
|
|
|
|
|
def add_integration_parsers(subparsers: Any) -> None:
|
|
service = subparsers.add_parser("service", help="фоновый сервис синхронизации воркеров")
|
|
service_sub = service.add_subparsers(dest="service_command")
|
|
start = service_sub.add_parser("start", help="запустить сервис")
|
|
_common(start)
|
|
start.add_argument("--foreground", action="store_true")
|
|
start.add_argument("--host", default=DEFAULT_SERVICE_HOST)
|
|
start.add_argument("--port", type=int, default=DEFAULT_SERVICE_PORT)
|
|
start.add_argument("--session", dest="service_session")
|
|
service_sub.add_parser("stop", help="остановить сервис")
|
|
service_sub.add_parser("status", help="показать состояние сервиса")
|
|
|
|
attach = subparsers.add_parser("attach", help="открыть TUI с подключением к сервису")
|
|
_common(attach)
|
|
attach.add_argument("--url", help="URL сервиса; по умолчанию из service.json")
|
|
|
|
ctl = subparsers.add_parser("ctl", help="управление сервисом из OpenCode")
|
|
ctl.add_argument("--url", help="URL сервиса; по умолчанию из service.json")
|
|
ctl_sub = ctl.add_subparsers(dest="ctl_command")
|
|
ctl_sub.add_parser("state", help="полное состояние")
|
|
worker = ctl_sub.add_parser("worker", help="действия с воркерами")
|
|
worker_sub = worker.add_subparsers(dest="worker_command")
|
|
create = worker_sub.add_parser("create", help="создать воркера")
|
|
create.add_argument("--task", required=True)
|
|
create.add_argument("--role", default="coder")
|
|
create.add_argument("--workspace")
|
|
create.add_argument("--name")
|
|
create.add_argument("--model")
|
|
create.add_argument("--provider")
|
|
create.add_argument("--intelligence", choices=["low", "medium", "high"])
|
|
message = worker_sub.add_parser("message", help="отправить follow-up")
|
|
message.add_argument("worker_id")
|
|
message.add_argument("message", nargs="?")
|
|
message.add_argument("--message", dest="message_option")
|
|
retry = worker_sub.add_parser("retry", help="повторить воркера")
|
|
retry.add_argument("worker_id")
|
|
cancel = worker_sub.add_parser("cancel", help="отменить воркера")
|
|
cancel.add_argument("worker_id")
|
|
cancel.add_argument("--reason", default="")
|
|
worker_sub.add_parser("list", help="список воркеров")
|
|
|
|
skill = subparsers.add_parser("skill", help="установить скилл OpenCode")
|
|
skill_sub = skill.add_subparsers(dest="skill_command")
|
|
install = skill_sub.add_parser("install", help="скопировать скилл")
|
|
install.add_argument("--global", dest="global_install", action="store_true")
|
|
install.add_argument("--force", action="store_true")
|
|
status = skill_sub.add_parser("status", help="проверить установку скилла")
|
|
status.add_argument("--global", dest="global_install", action="store_true")
|
|
|
|
update = subparsers.add_parser("update", help="проверить или установить обновление")
|
|
update_sub = update.add_subparsers(dest="update_command")
|
|
check = update_sub.add_parser("check", help="проверить последнюю версию")
|
|
check.add_argument("--force", action="store_true")
|
|
update_sub.add_parser("install", help="обновить git-чек-аут")
|
|
|
|
|
|
def _common(parser: argparse.ArgumentParser) -> None:
|
|
parser.add_argument("--config", type=Path, default=argparse.SUPPRESS)
|
|
parser.add_argument("--workspace", default=argparse.SUPPRESS)
|
|
parser.add_argument("--provider", dest="provider_id", default=argparse.SUPPRESS)
|
|
parser.add_argument("--model", default=argparse.SUPPRESS)
|
|
parser.add_argument("--worker-model", default=argparse.SUPPRESS)
|
|
parser.add_argument("--base-url", default=argparse.SUPPRESS)
|
|
parser.add_argument("--max-workers", type=int, default=argparse.SUPPRESS)
|
|
parser.add_argument("--no-color", action="store_true", default=argparse.SUPPRESS)
|
|
|
|
|
|
def _config(args: argparse.Namespace, cwd: Path) -> Config:
|
|
workspace = _opt(args, "workspace")
|
|
project = (Path(workspace).expanduser().resolve() if workspace else cwd)
|
|
project.mkdir(parents=True, exist_ok=True)
|
|
config = load_config(
|
|
project,
|
|
config_path=_opt(args, "config"),
|
|
base_url=_opt(args, "base_url"),
|
|
model=_opt(args, "model"),
|
|
worker_model=_opt(args, "worker_model"),
|
|
)
|
|
provider_id = _opt(args, "provider_id")
|
|
if provider_id:
|
|
if provider_id not in config.providers:
|
|
raise ConfigError(f"Неизвестный провайдер: {provider_id}")
|
|
config.active_provider = provider_id
|
|
config.orchestrator_provider = provider_id
|
|
config.worker_provider = provider_id
|
|
max_workers = _opt(args, "max_workers")
|
|
if max_workers:
|
|
config.limits.max_workers = max(1, max_workers)
|
|
return config
|
|
|
|
|
|
def _runtime_client(args: argparse.Namespace) -> ServiceClient:
|
|
url = _opt(args, "url")
|
|
runtime = load_service_runtime()
|
|
if url:
|
|
token = str((runtime or {}).get("token", ""))
|
|
else:
|
|
if not runtime:
|
|
raise ConfigError("Сервис не запущен. Выполните `airouter service start`.")
|
|
url = str(runtime["url"])
|
|
token = str(runtime["token"])
|
|
return ServiceClient(url, token)
|
|
|
|
|
|
def _print_json(value: Any) -> None:
|
|
print(json.dumps(value, ensure_ascii=False, indent=2, default=str))
|
|
|
|
|
|
async def _service(args: argparse.Namespace, cwd: Path) -> int:
|
|
action = _opt(args, "service_command")
|
|
if action == "status":
|
|
runtime = load_service_runtime()
|
|
if not runtime:
|
|
print("Сервис не запущен")
|
|
return 1
|
|
client = ServiceClient(str(runtime["url"]), str(runtime["token"]))
|
|
try:
|
|
health = await client.health()
|
|
print(
|
|
f"Сервис работает: {health['url'] if 'url' in health else runtime['url']} "
|
|
f"· сессия {health.get('session_id', '—')}"
|
|
)
|
|
return 0
|
|
except Exception as exc:
|
|
print(f"Сервис недоступен: {exc}")
|
|
return 1
|
|
finally:
|
|
await client.aclose()
|
|
|
|
if action == "stop":
|
|
runtime = load_service_runtime()
|
|
if not runtime:
|
|
print("Сервис не запущен")
|
|
return 0
|
|
pid = int(runtime.get("pid") or 0)
|
|
if pid > 0:
|
|
try:
|
|
os.kill(pid, 15)
|
|
except ProcessLookupError:
|
|
pass
|
|
for _ in range(30):
|
|
if not SERVICE_RUNTIME.exists():
|
|
break
|
|
await asyncio.sleep(0.1)
|
|
if SERVICE_RUNTIME.exists():
|
|
try:
|
|
os.kill(pid, 0)
|
|
except ProcessLookupError:
|
|
SERVICE_RUNTIME.unlink(missing_ok=True)
|
|
print("Сервис остановлен")
|
|
return 0
|
|
|
|
if action != "start":
|
|
print("Использование: airouter service start|stop|status")
|
|
return 2
|
|
|
|
config = _config(args, cwd)
|
|
workspace = (Path(_opt(args, "workspace")).expanduser().resolve() if _opt(args, "workspace") else cwd)
|
|
sessions_root = workspace / ".airouter" / "sessions"
|
|
host = str(_opt(args, "host", DEFAULT_SERVICE_HOST))
|
|
port = int(_opt(args, "port", DEFAULT_SERVICE_PORT))
|
|
session_id = _opt(args, "service_session")
|
|
|
|
if _opt(args, "foreground", False):
|
|
registry = ProviderRegistry(config)
|
|
try:
|
|
await run_service(
|
|
config=config,
|
|
provider_registry=registry,
|
|
sessions_root=sessions_root,
|
|
cwd=workspace,
|
|
session_id=session_id,
|
|
host=host,
|
|
port=port,
|
|
)
|
|
finally:
|
|
await registry.aclose()
|
|
return 0
|
|
|
|
existing = load_service_runtime()
|
|
if existing:
|
|
client = ServiceClient(str(existing["url"]), str(existing["token"]))
|
|
try:
|
|
await client.health()
|
|
print(f"Сервис уже работает: {existing['url']}")
|
|
return 0
|
|
except Exception:
|
|
pass
|
|
finally:
|
|
await client.aclose()
|
|
|
|
state_dir = SERVICE_RUNTIME.parent
|
|
state_dir.mkdir(parents=True, exist_ok=True)
|
|
log_path = state_dir / "service.log"
|
|
command = [
|
|
sys.executable,
|
|
"-m",
|
|
"airouter",
|
|
"service",
|
|
"start",
|
|
"--foreground",
|
|
"--host",
|
|
host,
|
|
"--port",
|
|
str(port),
|
|
"--workspace",
|
|
str(workspace),
|
|
]
|
|
for option, value in (
|
|
("--config", _opt(args, "config")),
|
|
("--provider", _opt(args, "provider_id")),
|
|
("--model", _opt(args, "model")),
|
|
("--worker-model", _opt(args, "worker_model")),
|
|
("--base-url", _opt(args, "base_url")),
|
|
):
|
|
if value:
|
|
command.extend([option, str(value)])
|
|
if session_id:
|
|
command.extend(["--session", str(session_id)])
|
|
with open(log_path, "ab") as log:
|
|
subprocess.Popen(
|
|
command,
|
|
cwd=workspace,
|
|
stdin=subprocess.DEVNULL,
|
|
stdout=log,
|
|
stderr=log,
|
|
start_new_session=True,
|
|
env=os.environ.copy(),
|
|
)
|
|
for _ in range(100):
|
|
runtime = load_service_runtime()
|
|
if runtime:
|
|
client = ServiceClient(str(runtime["url"]), str(runtime["token"]))
|
|
try:
|
|
await client.health()
|
|
print(f"Сервис запущен: {runtime['url']}")
|
|
return 0
|
|
except Exception:
|
|
pass
|
|
finally:
|
|
await client.aclose()
|
|
await asyncio.sleep(0.1)
|
|
print(f"Сервис не ответил. Журнал: {log_path}")
|
|
return 1
|
|
|
|
|
|
async def _attach(args: argparse.Namespace, cwd: Path) -> int:
|
|
from .tui.app import run_tui_app
|
|
|
|
config = _config(args, cwd)
|
|
client = _runtime_client(args)
|
|
workspace = (Path(_opt(args, "workspace")).expanduser().resolve() if _opt(args, "workspace") else cwd)
|
|
return run_tui_app(
|
|
config=config,
|
|
provider=None, # type: ignore[arg-type]
|
|
sessions_root=workspace / ".airouter" / "sessions",
|
|
cwd=workspace,
|
|
service_client=client,
|
|
)
|
|
|
|
|
|
async def _ctl(args: argparse.Namespace, cwd: Path) -> int:
|
|
del cwd
|
|
client = _runtime_client(args)
|
|
try:
|
|
command = _opt(args, "ctl_command")
|
|
if command == "state":
|
|
_print_json(await client.state())
|
|
return 0
|
|
if command == "worker":
|
|
action = _opt(args, "worker_command")
|
|
if action == "create":
|
|
result = await client.request(
|
|
"POST",
|
|
"/worker/spawn",
|
|
{
|
|
"task": _opt(args, "task"),
|
|
"role": _opt(args, "role", "coder"),
|
|
"workspace": _opt(args, "workspace"),
|
|
"name": _opt(args, "name"),
|
|
"model": _opt(args, "model"),
|
|
"provider": _opt(args, "provider"),
|
|
"intelligence": _opt(args, "intelligence"),
|
|
},
|
|
)
|
|
elif action == "message":
|
|
result = await client.request(
|
|
"POST",
|
|
"/worker/message",
|
|
{
|
|
"worker_id": _opt(args, "worker_id"),
|
|
"message": _opt(args, "message_option") or _opt(args, "message") or "",
|
|
},
|
|
)
|
|
elif action == "retry":
|
|
result = await client.request(
|
|
"POST", "/worker/retry", {"worker_id": _opt(args, "worker_id")}
|
|
)
|
|
elif action == "cancel":
|
|
result = await client.request(
|
|
"POST",
|
|
"/worker/cancel",
|
|
{"worker_id": _opt(args, "worker_id"), "reason": _opt(args, "reason", "")},
|
|
)
|
|
elif action == "list":
|
|
state = await client.state()
|
|
result = [
|
|
{
|
|
"id": worker["meta"]["id"],
|
|
"name": worker["meta"]["name"],
|
|
"status": worker["meta"]["status"],
|
|
"model": worker["meta"]["model"],
|
|
}
|
|
for worker in state.get("workers", [])
|
|
]
|
|
else:
|
|
print("Использование: airouter ctl worker create|message|retry|cancel|list")
|
|
return 2
|
|
_print_json(result)
|
|
return 0
|
|
print("Использование: airouter ctl state|worker ...")
|
|
return 2
|
|
finally:
|
|
await client.aclose()
|
|
|
|
|
|
def _skill_target(args: argparse.Namespace, cwd: Path) -> Path:
|
|
base = Path.home() / ".config" / "opencode" / "skills" if _opt(args, "global_install") else cwd / ".opencode" / "skills"
|
|
return base / "airouter"
|
|
|
|
|
|
def _skill(args: argparse.Namespace, cwd: Path) -> int:
|
|
target = _skill_target(args, cwd)
|
|
source = Path(__file__).parent / "skill" / "SKILL.md"
|
|
action = _opt(args, "skill_command")
|
|
if action == "status":
|
|
print(f"Скилл установлен: {target / 'SKILL.md'}" if (target / "SKILL.md").is_file() else "Скилл не установлен")
|
|
return 0 if (target / "SKILL.md").is_file() else 1
|
|
if action != "install":
|
|
print("Использование: airouter skill install [--global]")
|
|
return 2
|
|
if (target / "SKILL.md").exists() and not _opt(args, "force", False):
|
|
print(f"{target / 'SKILL.md'} уже существует. Используйте --force.")
|
|
return 2
|
|
target.mkdir(parents=True, exist_ok=True)
|
|
shutil.copy2(source, target / "SKILL.md")
|
|
print(f"Скилл AiRouter Workers установлен: {target / 'SKILL.md'}")
|
|
return 0
|
|
|
|
|
|
async def _update(args: argparse.Namespace, cwd: Path) -> int:
|
|
del cwd
|
|
action = _opt(args, "update_command", "check")
|
|
if action == "install":
|
|
result = await asyncio.to_thread(install_update)
|
|
print(result.message)
|
|
if result.updated or result.message == "AiRouter is already up to date.":
|
|
return 0
|
|
return 1
|
|
info = await asyncio.to_thread(check_for_updates, force=bool(_opt(args, "force", False)))
|
|
if info.error:
|
|
print(f"Не удалось проверить обновление: {info.error}")
|
|
return 1
|
|
if info.available:
|
|
print(f"Доступна версия {info.latest}; установлена {info.current}. `airouter update install`")
|
|
else:
|
|
print(f"Установлена последняя версия: {info.current}")
|
|
return 0
|
|
|
|
|
|
async def handle_integration_command(args: argparse.Namespace, cwd: Path) -> int | None:
|
|
command = _opt(args, "command")
|
|
if command == "service":
|
|
return await _service(args, cwd)
|
|
if command == "attach":
|
|
return await _attach(args, cwd)
|
|
if command == "ctl":
|
|
return await _ctl(args, cwd)
|
|
if command == "skill":
|
|
return _skill(args, cwd)
|
|
if command == "update":
|
|
return await _update(args, cwd)
|
|
return None
|