feat: add synchronized OpenCode worker service, adaptive animations and auto-updates

This commit is contained in:
KoDer committed 2026-11-24 23:16:07 +07:00
1 parent 390e8657d3
commit b7f66a6566
23 files changed
+4714 -94

No files matched your search

+79
View File
@@ -0,0 +1,79 @@
---
name: AiRouter Workers
description: Auto-invoke when the user wants OpenCode workers shown in the AiRouter console, synchronized worker chats, or a local agent dashboard.
---
# AiRouter Workers
Use AiRouter as the local console for OpenCode-driven work. Keep the service,
workers, and console synchronized; never run a second, disconnected worker loop.
## Workflow
1. Ensure the local service is running:
```sh
airouter service start
```
2. Create each worker explicitly and use the requested role and workspace:
```sh
airouter ctl worker create --task "Describe the task" --role coder --workspace "/absolute/workspace"
```
Optional flags are `--name`, `--model`, and `--provider`. Read the returned
worker ID (for example, `w1`) and use that exact ID in later commands. Do not
invent IDs or assume creation order.
3. Open the AiRouter console **inside OpenCode** by creating a PTY through the
OpenCode V2 API. Replace `<absolute cwd>` with the real absolute path:
```sh
opencode api post /api/pty --data '{"command":"airouter","args":["attach"],"cwd":"<absolute cwd>","title":"AiRouter Workers"}'
```
Switch to the created PTY to use the console. Do **not** run blocking
`airouter attach` directly in a shell tool.
4. Keep worker chats synchronized through the service SSE stream. The console
receives worker messages, progress, completion, failures, and direct-chat
events without starting local worker tasks. Use the console to inspect the
conversation and reports.
5. Message, retry, or cancel workers through `airouter ctl` using their IDs:
```sh
airouter ctl worker message w1 --message "Additional context or next step"
airouter ctl worker retry w1
airouter ctl worker cancel w1 --reason "No longer needed"
```
Use `airouter ctl worker list` to confirm current IDs and statuses. Wait for a
worker to finish before sending a follow-up or retrying it.
## Security
The service token authenticates local clients. Do not print it, paste it into a
worker prompt, commit it, or read it from the runtime file just to configure the
console. Let `airouter service` and `airouter attach` manage authentication.
## Updates
AiRouter checks remote Git tags for `vMAJOR.MINOR.PATCH` releases and caches a
successful check for six hours:
```sh
airouter update
```
If an update is available, tell the user and install it with:
```sh
airouter update install
```
Updates only fast-forward a clean Git checkout. If the working tree is dirty or
history is not fast-forward, stop and report that the update was refused; never
stash, reset, or discard the user's changes. Restart AiRouter after source files
change.
+15
View File
@@ -1,5 +1,20 @@
# Changelog
## 0.4.0 — 2026-11-24
### Добавлено
- Адаптивный TUI: на узких терминалах боковая панель скрывается, кнопки
сокращаются, а длинные пути корректно переносятся.
- Анимированный equalizer активности, цветовой цикл логотипа, уведомления о
завершении и ошибках воркеров; настройка отключения анимаций.
- Локальный HTTP/SSE сервис синхронизации сессии и воркеров.
- `airouter attach` — TUI, подключённый к работающему сервису.
- Команды `airouter ctl` для создания, сообщения, retry и отмены воркеров.
- Устанавливаемый скилл OpenCode `airouter` и открытие консоли через PTY API.
- Проверка новых git-тегов при запуске и безопасное fast-forward обновление.
- CLI-команды `service`, `ctl`, `skill`, `update` и флаг `--no-update-check`.
## 0.3.0 — 2026-11-24
### Добавлено
+61 -1
View File
@@ -182,6 +182,53 @@ auto_auth = false
дублирования пользовательского сообщения. Независимые чаты сохраняются в
`chats.json` внутри сессии.
## OpenCode Skill и синхронный сервис
AiRouter можно использовать как консоль воркеров внутри OpenCode. Установите
скилл глобально или в проект:
```bash
airouter skill install --global
# или
airouter skill install
```
В OpenCode загрузите скилл `@airouter` (он также подхватывается автоматически
по описанию). Сервис хранит сессию и воркеров в одном процессе, а TUI получает
состояние и события через локальный HTTP/SSE-канал:
```bash
airouter service start
airouter service status
airouter ctl worker create --task "Проверить API" --role coder --workspace "$PWD"
airouter ctl worker list
airouter attach
```
Скилл открывает `airouter attach` через PTY API OpenCode, поэтому консоль
работает внутри OpenCode, а не блокирует shell-инструмент. Воркеры, созданные
через `airouter ctl`, сразу появляются в TUI; сообщения, retry и отчёты
синхронизируются в обе стороны. `airouter service stop` останавливает сервис.
Сервис слушает только `127.0.0.1` и требует локальный токен из
`~/.local/state/airouter/service.json`. Не публикуйте и не отправляйте этот
файл воркерам.
## Обновления
При интерактивном запуске AiRouter проверяет теги удалённого репозитория (кеш
на 6 часов) и предлагает обновление, если версия новее. Обновление выполняется
только через fast-forward и только при чистом git-дереве:
```bash
airouter update check
airouter update install
```
Проверку можно отключить флагом `--no-update-check` или переменной
`AIROUTER_NO_UPDATE_CHECK=1`. После обновления исходников перезапустите
приложение или сервис.
## Быстрый старт
### Один запуск
@@ -226,7 +273,8 @@ airouter
- **Провайдеры / Ctrl+P** — добавить облачный или локальный провайдер, проверить
`/models`, настроить повторы и выбрать основной.
- **⚙ Настройки / Ctrl+S** — максимум воркеров, провайдеры и модели главного
агента/воркеров, модели для `low` / `medium` / `high` и отдельных ролей.
агента/воркеров, модели для `low` / `medium` / `high`, отдельных ролей и
переключатель анимаций.
- **Панель TODO** — клик по задаче переключает на чат связанного воркера.
- **Панель воркеров** — клик открывает мини-чат воркера; кнопка **Отчёт** показывает
отчёт, файлы, команды и транскрипт.
@@ -496,6 +544,11 @@ airouter --provider ollama models
airouter sessions # сессии в текущей папке
airouter init [--force] # создать .airouter.toml
airouter doctor [--live] # диагностика
airouter service start|stop|status
airouter attach # TUI к синхронному сервису
airouter ctl worker create|list|message|retry|cancel
airouter skill install [--global]
airouter update check|install
```
Полезные флаги: `--workspace`, `--provider`, `--model`, `--worker-model`,
@@ -550,6 +603,10 @@ airouter/
provider.py # OpenAI-совместимый streaming client, retries
providers.py # реестр провайдеров и маршрутизация моделей
chats.py # независимые чаты, fork и message actions
service.py # локальный HTTP/SSE сервис синхронизации
remote.py # Session-адаптер для подключения к сервису
update.py # проверка и безопасное обновление
skill/SKILL.md # устанавливаемый скилл OpenCode
workspace.py # файлы и bash, ограничения путей
storage.py # сессии на диске
ui.py # классический Rich + prompt_toolkit интерфейс
@@ -567,6 +624,9 @@ tests/
test_chats.py
test_session_actions.py
test_tui_chats.py
test_service.py
test_remote.py
test_update.py
test_compact.py
test_resume_interrupted.py
```
+1 -1
View File
@@ -1,5 +1,5 @@
"""AiRouter: event-driven orchestration of AI coding workers."""
__version__ = "0.3.0"
__version__ = "0.4.0"
APP_NAME = "AiRouter"
+91 -10
View File
@@ -15,6 +15,7 @@ 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__
@@ -30,9 +31,12 @@ from .config import (
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
@@ -62,6 +66,12 @@ def _common_options(parser: argparse.ArgumentParser) -> None:
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:
@@ -107,6 +117,7 @@ def _build_parser() -> argparse.ArgumentParser:
doctor.add_argument("--live", action="store_true", help="сделать тестовый запрос к модели")
sub.add_parser("version", help="показать версию")
add_integration_parsers(sub)
return parser
@@ -163,6 +174,48 @@ def _make_provider(config: Config) -> tuple[OpenAIClient, list[Any], ProviderReg
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],
@@ -247,6 +300,8 @@ async def _interactive(
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)
@@ -630,6 +685,15 @@ async def async_main(args: argparse.Namespace) -> int:
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:
@@ -715,8 +779,8 @@ async def async_main(args: argparse.Namespace) -> int:
args, config, provider, ui, goal, provider_registry=registry
)
if command not in {"interactive", "tui", "chat"}:
print(f"Неизвестная команда: {command}. Доступно: run, tui, models, providers, sessions, init, doctor.", file=sys.stderr)
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():
@@ -824,17 +888,30 @@ def _run_tui_cli(args: argparse.Namespace) -> int:
except ConfigError as exc:
print(f"Ошибка конфигурации: {exc}", 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
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,
provider=provider, # type: ignore[arg-type]
sessions_root=_sessions_root(project_cwd),
cwd=project_cwd,
resume=bool(_opt(args, "continue_session", False)),
@@ -843,10 +920,14 @@ def _run_tui_cli(args: argparse.Namespace) -> int:
worker_model_override=_opt(args, "worker_model"),
max_workers_override=_opt(args, "max_workers"),
provider_registry=registry,
service_client=service_client,
)
finally:
try:
asyncio.run(registry.aclose())
if registry is not None:
asyncio.run(registry.aclose())
elif service_client is not None:
asyncio.run(service_client.aclose())
except Exception:
pass
@@ -856,7 +937,7 @@ def main() -> None:
args = parser.parse_args()
command = _opt(args, "command", None)
use_tui = (
command in {None, "tui"}
command in {None, "tui", "attach"}
and not bool(_opt(args, "classic", False))
and sys.stdin.isatty()
and sys.stdout.isatty()
+3
View File
@@ -219,6 +219,7 @@ class UIConfig:
show_reasoning: bool = False
language: str = "ru"
max_worker_line: int = 120
animations: bool = True
@dataclass
@@ -536,6 +537,7 @@ def load_config(
show_reasoning=bool(ui_raw.get("show_reasoning", ui_defaults.show_reasoning)),
language=str(ui_raw.get("language", ui_defaults.language)),
max_worker_line=int(ui_raw.get("max_worker_line", ui_defaults.max_worker_line)),
animations=bool(ui_raw.get("animations", ui_defaults.animations)),
)
intelligence = dict(DEFAULT_INTELLIGENCE)
@@ -648,6 +650,7 @@ auto_compact_tokens = 0
[ui]
show_reasoning = false
animations = true
# Именованные провайдеры. Профили из TUI хранятся в providers.json.
active_provider = "opencode"
+521
View File
@@ -0,0 +1,521 @@
"""Session-compatible remote snapshots for the AiRouter TUI."""
from __future__ import annotations
import asyncio
import copy
import json
import time
from collections.abc import Awaitable, Mapping
from dataclasses import fields
from pathlib import Path
from typing import Any
from .chats import DirectChat
from .config import Config, ProviderProfile
from .provider import Usage
from .service import ServiceClient, ServiceError
from .service_state import config_from_data, worker_from_state
from .session import Session
from .storage import SessionStore
from .utils import estimate_messages_tokens
from .worker import Worker
from .workspace import ReadOnlyFS, ToolError
class RemoteSession(Session):
"""A local view of a service-owned session.
Snapshot updates mutate existing lists, worker objects and nested config
objects in place. A worker detail screen that holds a ``Worker`` reference
therefore continues to see refreshed messages and status.
"""
remote = True
def __init__(self, client: ServiceClient, state: Mapping[str, Any]) -> None:
self.client = client
self.store = self._store_for_state(state)
self.config = config_from_data(state.get("config") or {})
self.cwd = Path(str(state.get("cwd") or Path.cwd())).resolve()
self.listener = None
self.main_messages: list[dict[str, Any]] = []
self.workers: dict[str, Worker] = {}
self.worker_tasks: dict[str, asyncio.Task[Any]] = {}
self.main_usage = Usage()
self.goal = ""
self.turns = 0
self.todos: list[dict[str, Any]] = []
self.created_at = time.time()
self.api_session = ""
self.changed = asyncio.Event()
self.busy = False
self.worker_seq = 0
self.read_fs = ReadOnlyFS(self.cwd, self.config.limits)
self.provider = None
self.provider_registry = None
self._direct_state: list[dict[str, Any]] = []
self.apply_state(state)
@classmethod
def from_state(
cls, client: ServiceClient, state: Mapping[str, Any]
) -> RemoteSession:
return cls(client, state)
@staticmethod
def _state_id(state: Mapping[str, Any]) -> str:
meta = state.get("meta")
session_id = state.get("id") or state.get("session_id")
if not session_id and isinstance(meta, Mapping):
session_id = meta.get("id")
return str(session_id or "")
@classmethod
def _store_for_state(cls, state: Mapping[str, Any]) -> SessionStore:
session_id = cls._state_id(state)
sessions_root = state.get("sessions_root")
if not sessions_root:
meta = state.get("sessions_root")
sessions_root = meta
if not sessions_root:
raise ValueError("state.sessions_root is required")
return SessionStore.open(Path(str(sessions_root)), session_id)
# ------------------------------------------------------------------ snapshots
def apply_state(self, state: Mapping[str, Any]) -> None:
if not isinstance(state, Mapping):
raise TypeError("session state must be an object")
new_store = self._store_for_state(state)
if new_store.id != self.store.id or new_store.sessions_root != self.store.sessions_root:
self.store = new_store
self._apply_config(config_from_data(state.get("config") or {}))
self.cwd = Path(str(state.get("cwd") or self.cwd)).resolve()
self.read_fs = ReadOnlyFS(self.cwd, self.config.limits)
messages = state.get("main_messages")
self.main_messages[:] = copy.deepcopy(messages) if isinstance(messages, list) else []
self.main_usage.__dict__.update(
Usage.from_dict(state.get("main_usage")).__dict__
)
direct_chats = state.get("direct_chats")
self._direct_state = copy.deepcopy(direct_chats) if isinstance(direct_chats, list) else []
self.goal = str(state.get("goal") or "")
self.turns = int(state.get("turns") or 0)
todos = state.get("todos")
if todos is None and isinstance(state.get("meta"), Mapping):
todos = state["meta"].get("plan")
self.todos[:] = copy.deepcopy(todos) if isinstance(todos, list) else []
self.created_at = float(state.get("created_at") or self.created_at)
self.api_session = str(state.get("api_session") or "")
self.busy = bool(state.get("busy", False))
self.worker_seq = int(state.get("worker_seq") or 0)
raw_workers = state.get("workers") or []
if isinstance(raw_workers, Mapping):
raw_workers = list(raw_workers.values())
updated: dict[str, Worker] = {}
for item in raw_workers:
fresh = worker_from_state(item, self.config)
existing = self.workers.get(fresh.id)
if existing is None:
updated[fresh.id] = fresh
else:
self._apply_worker(existing, fresh, self.config)
updated[fresh.id] = existing
self.workers.clear()
self.workers.update(updated)
if not self.worker_seq:
self.worker_seq = max(
[int(worker.id[1:]) for worker in self.workers.values() if worker.id.startswith("w") and worker.id[1:].isdigit()]
or [0]
)
# A remote snapshot never owns local agent tasks.
self.worker_tasks.clear()
self.changed.set()
def _apply_config(self, fresh: Config) -> None:
for field in fields(Config):
name = field.name
if name in {"limits", "ui", "provider"}:
getattr(self.config, name).__dict__.update(
copy.deepcopy(getattr(fresh, name).__dict__)
)
elif name == "roles":
roles: dict[str, Any] = {}
for role_name, role in fresh.roles.items():
existing = self.config.roles.get(role_name)
if existing is None:
roles[role_name] = copy.deepcopy(role)
else:
existing.__dict__.update(copy.deepcopy(role.__dict__))
roles[role_name] = existing
self.config.roles.clear()
self.config.roles.update(roles)
elif name == "providers":
providers: dict[str, ProviderProfile] = {}
for provider_id, profile in fresh.providers.items():
existing = self.config.providers.get(provider_id)
if existing is None:
providers[provider_id] = copy.deepcopy(profile)
else:
existing.__dict__.update(copy.deepcopy(profile.__dict__))
providers[provider_id] = existing
self.config.providers.clear()
self.config.providers.update(providers)
else:
setattr(self.config, name, copy.deepcopy(getattr(fresh, name)))
@staticmethod
def _apply_worker(existing: Worker, fresh: Worker, config: Config) -> None:
for field in fields(Worker):
if field.name in {"role", "messages", "usage", "snapshot_before"}:
continue
setattr(existing, field.name, copy.deepcopy(getattr(fresh, field.name)))
existing.role.__dict__.update(copy.deepcopy(fresh.role.__dict__))
existing.messages[:] = copy.deepcopy(fresh.messages)
existing.usage.__dict__.update(copy.deepcopy(fresh.usage.__dict__))
existing.bind(config)
@staticmethod
def _apply_direct_chat(chat: DirectChat, raw: Mapping[str, Any]) -> None:
fresh = DirectChat.from_meta(dict(raw))
for field in fields(DirectChat):
if field.name in {"messages", "usage"}:
continue
setattr(chat, field.name, copy.deepcopy(getattr(fresh, field.name)))
chat.messages[:] = copy.deepcopy(fresh.messages)
chat.usage.__dict__.update(copy.deepcopy(fresh.usage.__dict__))
async def refresh(self) -> RemoteSession:
self.apply_state(await self.client.state())
return self
async def _after_mutation(self, operation: Awaitable[Any]) -> Any:
try:
result = await operation
except asyncio.CancelledError:
raise
except Exception:
try:
await self.refresh()
except Exception: # noqa: BLE001, S110 - preserve the original mutation error
pass
raise
await self.refresh()
return result
# ------------------------------------------------------------------ local no-ops
def save_all(self) -> None:
return None
def save_main(self) -> None:
return None
def save_worker(self, worker: Worker) -> None:
return None
def refresh_system_prompt(self) -> None:
return None
def emit(self, event_type: str, *, worker_id: str | None = None, transient: bool = False, **data: Any) -> None:
self.changed.set()
async def close(self) -> None:
# Closing a TUI snapshot must never stop the shared service.
return None
# ------------------------------------------------------------------ remote actions
async def run_turn(self, user_text: str) -> str:
result = await self._after_mutation(
self.client.request("POST", "/turn", {"text": user_text})
)
return _text_result(result)
async def continue_turn(self) -> str:
result = await self._after_mutation(self.client.request("POST", "/continue"))
return _text_result(result)
async def cancel_all_workers(self) -> None:
await self._after_mutation(self.client.request("POST", "/cancel"))
async def interrupt(self) -> None:
await self._after_mutation(self.client.request("POST", "/interrupt"))
async def compact(self) -> str:
result = await self._after_mutation(self.client.request("POST", "/compact"))
return _text_result(result)
async def change_workspace(self, path: str | Path, *, create: bool = True) -> Path:
result = await self._after_mutation(
self.client.request(
"POST", "/workspace", {"path": str(path), "create": bool(create)}
)
)
if isinstance(result, Mapping) and result.get("cwd"):
return Path(str(result["cwd"]))
return self.cwd
async def apply_settings(
self,
*,
max_workers: int | None = None,
orchestrator_model: str | None = None,
worker_model: str | None = None,
intelligence: dict[str, str] | None = None,
roles: dict[str, str] | None = None,
orchestrator_provider: str | None = None,
worker_provider: str | None = None,
animations: bool | None = None,
) -> None:
data = {
"max_workers": max_workers,
"orchestrator_model": orchestrator_model,
"worker_model": worker_model,
"intelligence": intelligence,
"roles": roles,
"orchestrator_provider": orchestrator_provider,
"worker_provider": worker_provider,
"animations": animations,
}
await self._after_mutation(
self.client.request("POST", "/settings", data)
)
async def spawn_worker(
self,
*,
task: str,
role: str = "coder",
workspace: str | None = None,
name: str | None = None,
model: str | None = None,
provider: str | None = None,
intelligence: str | None = None,
) -> Worker:
result = await self._after_mutation(
self.client.request(
"POST",
"/worker/spawn",
{
"task": task,
"role": role,
"workspace": workspace,
"name": name,
"model": model,
"provider": provider,
"intelligence": intelligence,
},
)
)
worker_id = _result_worker_id(result)
if not worker_id:
raise ServiceError("worker spawn response has no id")
return self._worker(worker_id)
async def _tool_message_worker(self, worker_id: str, message: str) -> Any:
result = await self._after_mutation(
self.client.request(
"POST",
"/worker/message",
{"worker_id": worker_id, "message": message},
)
)
return result.get("result", result) if isinstance(result, Mapping) else result
async def retry_worker(self, worker_id: str) -> Worker:
result = await self._after_mutation(
self.client.request("POST", "/worker/retry", {"worker_id": worker_id})
)
return self._worker(_result_worker_id(result) or worker_id)
async def _tool_cancel_worker(self, worker_id: str, reason: str = "") -> Any:
result = await self._after_mutation(
self.client.request(
"POST",
"/worker/cancel",
{"worker_id": worker_id, "reason": reason},
)
)
return result.get("result", result) if isinstance(result, Mapping) else result
async def fork_worker(
self, worker_id: str, messages: list[dict[str, Any]]
) -> Worker:
result = await self._after_mutation(
self.client.request(
"POST",
"/worker/fork",
{"worker_id": worker_id, "messages": messages},
)
)
return self._worker(_result_worker_id(result) or "")
async def fork_session(self, messages: list[dict[str, Any]]) -> RemoteSession:
state = await self.client.request(
"POST", "/session/fork", {"messages": messages}
)
if not isinstance(state, Mapping):
raise ServiceError("session fork response must be an object")
return RemoteSession.from_state(self.client, state)
async def run_direct_chat(self, chat: Any, emit: Any = None) -> str:
# Events arrive through the client's SSE iterator; ``emit`` remains in
# the signature for Session/run_direct_chat compatibility.
result = await self._after_mutation(
self.client.request("POST", "/direct/run", {"chat": chat.meta()})
)
for raw_chat in self._direct_state:
if str(raw_chat.get("id") or "") == chat.id:
self._apply_direct_chat(chat, raw_chat)
break
return _text_result(result)
async def cancel_direct_chat(self, chat_id: str) -> None:
await self._after_mutation(
self.client.request("POST", "/direct/cancel", {"chat_id": chat_id})
)
async def delete_message(self, chat_id: str, index: int) -> None:
await self._after_mutation(
self.client.request(
"POST", "/message/delete", {"chat_id": chat_id, "index": index}
)
)
async def truncate_messages(self, chat_id: str, index: int) -> None:
await self._after_mutation(
self.client.request(
"POST", "/message/truncate", {"chat_id": chat_id, "index": index}
)
)
async def update_provider(self, action: str, profile: Any) -> dict[str, Any]:
action = {"save": "upsert", "delete": "remove"}.get(action, action)
if isinstance(profile, ProviderProfile):
raw = {
field.name: copy.deepcopy(getattr(profile, field.name))
for field in fields(profile)
}
elif isinstance(profile, Mapping):
raw = copy.deepcopy(dict(profile))
else:
raw = {"id": str(profile)}
if action != "upsert":
raw = {"id": raw.get("id")}
elif raw.get("token") is None:
raw.pop("token", None)
result = await self._after_mutation(
self.client.request(
"POST", "/providers", {"action": action, "profile": raw}
)
)
return dict(result) if isinstance(result, Mapping) else {}
async def wait_for_workers(
self,
worker_ids: list[str] | None = None,
mode: str = "any",
timeout: float | None = None,
) -> dict[str, Any]:
if mode not in {"any", "all"}:
raise ToolError("mode должен быть 'any' или 'all'")
if worker_ids:
targets = [self._worker(str(worker_id)) for worker_id in worker_ids]
else:
targets = list(self.workers.values())
if not targets:
return {"completed": [], "still_running": [], "message": "Воркеров нет."}
wait_seconds = float(
timeout if timeout is not None else self.config.limits.wait_timeout
)
wait_seconds = max(0.01, min(wait_seconds, 3600.0))
started = time.monotonic()
await self.refresh()
targets = [self._worker(target.id) for target in targets]
pending = [worker for worker in targets if not worker.is_terminal]
if not pending and not any(worker.is_terminal and not worker.reported for worker in targets):
return {
"completed": [],
"still_running": [],
"already_reported": True,
"message": "Все результаты уже были переданы ранее.",
}
if pending:
self.emit(
"main_sleep",
waiting_for=[{"id": worker.id, "name": worker.name} for worker in pending],
mode=mode,
timeout=wait_seconds,
)
timed_out = False
while True:
if mode == "all":
ready = all(worker.is_terminal for worker in targets)
else:
ready = not any(worker.status in {"pending", "running"} for worker in targets)
ready = ready or any(worker.is_terminal and not worker.reported for worker in targets)
if ready:
break
remaining = wait_seconds - (time.monotonic() - started)
if remaining <= 0:
timed_out = True
break
await asyncio.sleep(min(0.1, remaining))
await self.refresh()
targets = [self._worker(target.id) for target in targets]
completed = [worker for worker in targets if worker.is_terminal and not worker.reported]
for worker in completed:
worker.reported = True
still_running = [worker.id for worker in targets if worker.status in {"pending", "running"}]
cap = max(4000, self.config.limits.tool_output_max_chars)
result: dict[str, Any] = {}
for factor in (0.5, 0.35, 0.2):
per_report = max(700, int(cap * factor) // max(1, len(completed)))
result = {
"completed": [self.worker_payload(worker, report_limit=per_report) for worker in completed],
"still_running": still_running,
"timed_out": timed_out,
"waited_seconds": round(time.monotonic() - started, 2),
"mode": mode,
}
if len(json.dumps(result, ensure_ascii=False)) <= cap * 0.9:
break
if timed_out:
result["message"] = (
"Таймаут ожидания. Воркеры всё ещё работают; вызови wait_for_workers снова "
"или отмени их."
)
elif completed:
result["message"] = "Готовые результаты ниже. Продолжай планирование или заверши работу."
if pending:
self.emit(
"main_wake",
completed=[worker.id for worker in completed],
still_running=still_running,
timed_out=timed_out,
waited_seconds=result["waited_seconds"],
)
return result
# Small local helpers also make the inherited Session computations reusable.
def context_tokens(self) -> int:
return estimate_messages_tokens(self.main_messages)
def _text_result(result: Any) -> str:
if isinstance(result, Mapping):
return str(result.get("text", ""))
return str(result or "")
def _result_worker_id(result: Any) -> str:
if isinstance(result, Mapping):
return str(result.get("id") or result.get("worker_id") or "")
return ""
+1204
View File
File diff suppressed because it is too large. Load diff
+417
View File
@@ -0,0 +1,417 @@
"""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
+240
View File
@@ -0,0 +1,240 @@
"""JSON snapshots for the local AiRouter service.
Snapshots intentionally contain provider metadata, but never inline provider
credentials. They are self-contained enough for a remote TUI to reconstruct a
session without starting any local agent tasks.
"""
from __future__ import annotations
import math
from collections.abc import Mapping
from dataclasses import fields, is_dataclass
from enum import Enum
from pathlib import Path
from typing import Any
from .chats import DirectChatStore
from .config import (
Config,
ConfigError,
LimitsConfig,
ProviderConfig,
ProviderProfile,
RoleConfig,
UIConfig,
)
from .session import Session
from .worker import Worker
STATE_VERSION = 1
def _json_safe(value: Any) -> Any:
if value is None or isinstance(value, (str, bool, int)):
return value
if isinstance(value, float):
return value if math.isfinite(value) else None
if isinstance(value, Path):
return str(value)
if isinstance(value, Enum):
return _json_safe(value.value)
if is_dataclass(value) and not isinstance(value, type):
return {field.name: _json_safe(getattr(value, field.name)) for field in fields(value)}
if isinstance(value, Mapping):
return {str(key): _json_safe(item) for key, item in value.items()}
if isinstance(value, (list, tuple)):
return [_json_safe(item) for item in value]
if isinstance(value, (set, frozenset)):
return sorted((_json_safe(item) for item in value), key=lambda item: str(item))
return str(value)
def _dataclass_data(value: Any) -> dict[str, Any]:
return {field.name: _json_safe(getattr(value, field.name)) for field in fields(value)}
def _known_data(cls: type, raw: Any, *, name: str) -> dict[str, Any]:
if raw is None:
return {}
if not isinstance(raw, Mapping):
raise ConfigError(f"{name} должен быть объектом")
allowed = {field.name for field in fields(cls)}
return {key: value for key, value in raw.items() if key in allowed}
def config_to_data(config: Config) -> dict[str, Any]:
"""Serialize configuration without copying inline provider tokens."""
provider = _dataclass_data(config.provider)
provider.pop("token", None)
providers: dict[str, dict[str, Any]] = {}
for provider_id, profile in config.providers.items():
item = _dataclass_data(profile)
item.pop("token", None)
providers[str(provider_id)] = item
return _json_safe(
{
"provider": provider,
"limits": _dataclass_data(config.limits),
"ui": _dataclass_data(config.ui),
"models": {
"orchestrator": config.orchestrator_model,
"worker": config.worker_model,
},
"intelligence": dict(config.intelligence),
"roles": {
name: _dataclass_data(role) for name, role in config.roles.items()
},
"providers": providers,
"active_provider": config.active_provider,
"orchestrator_provider": config.orchestrator_provider,
"worker_provider": config.worker_provider,
"project_config_path": config.project_config_path,
"global_config_path": config.global_config_path,
}
)
def config_from_data(data: Mapping[str, Any]) -> Config:
"""Reconstruct a config from :func:`config_to_data` output.
Token fields are ignored even if a caller supplies them: remote state is not
a credential transport. The service process retains its own credentials.
"""
if not isinstance(data, Mapping):
raise ConfigError("config должен быть объектом")
provider_raw = _known_data(ProviderConfig, data.get("provider"), name="provider")
provider_raw.pop("token", None)
if provider_raw.get("base_url") is not None:
provider_raw["base_url"] = str(provider_raw["base_url"])
provider = ProviderConfig(**provider_raw)
limits = LimitsConfig(
**_known_data(LimitsConfig, data.get("limits"), name="limits")
)
ui = UIConfig(**_known_data(UIConfig, data.get("ui"), name="ui"))
models_raw = data.get("models") or {}
if not isinstance(models_raw, Mapping):
raise ConfigError("models должен быть объектом")
orchestrator_model = str(
models_raw.get("orchestrator", data.get("orchestrator_model", Config().orchestrator_model))
)
worker_model = str(
models_raw.get("worker", data.get("worker_model", Config().worker_model))
)
intelligence_raw = data.get("intelligence") or {}
if not isinstance(intelligence_raw, Mapping):
raise ConfigError("intelligence должен быть объектом")
intelligence = {
str(level): str(model)
for level, model in intelligence_raw.items()
if model is not None
}
roles_raw = data.get("roles") or {}
if not isinstance(roles_raw, Mapping):
raise ConfigError("roles должен быть объектом")
roles: dict[str, RoleConfig] = {}
for raw_name, raw_role in roles_raw.items():
name = str(raw_name)
role_data = _known_data(RoleConfig, raw_role, name=f"roles.{name}")
role_data.pop("name", None)
roles[name] = RoleConfig(name=name, **role_data)
providers_raw = data.get("providers") or {}
if isinstance(providers_raw, list):
providers_raw = {
str(item.get("id")): item
for item in providers_raw
if isinstance(item, Mapping) and item.get("id")
}
if not isinstance(providers_raw, Mapping):
raise ConfigError("providers должен быть объектом")
providers: dict[str, ProviderProfile] = {}
for raw_id, raw_profile in providers_raw.items():
provider_id = str(raw_id)
profile_data = _known_data(
ProviderProfile, raw_profile, name=f"providers.{provider_id}"
)
profile_data.pop("token", None)
profile_data["id"] = provider_id
profile_data.setdefault("name", provider_id)
providers[provider_id] = ProviderProfile(**profile_data)
project_path = data.get("project_config_path")
global_path = data.get("global_config_path")
return Config(
provider=provider,
limits=limits,
ui=ui,
orchestrator_model=orchestrator_model,
worker_model=worker_model,
intelligence=intelligence,
roles=roles,
providers=providers,
active_provider=str(data.get("active_provider") or "opencode"),
orchestrator_provider=(
str(data["orchestrator_provider"])
if data.get("orchestrator_provider")
else None
),
worker_provider=(
str(data["worker_provider"]) if data.get("worker_provider") else None
),
project_config_path=Path(project_path) if project_path else None,
global_config_path=Path(global_path) if global_path else None,
)
def session_to_state(session: Session) -> dict[str, Any]:
"""Return a complete, JSON-safe UI snapshot of ``session``."""
store = DirectChatStore(session.store.dir / "chats.json")
chats = store.load()
meta = session.meta()
state = {
"version": STATE_VERSION,
"id": session.id,
"session_id": session.id,
"sessions_root": str(session.store.sessions_root),
"cwd": str(session.cwd),
"meta": meta,
"config": config_to_data(session.config),
"main_messages": session.main_messages,
"main_usage": session.main_usage.to_dict(),
"workers": [
{"meta": worker.meta(), "messages": worker.messages}
for worker in session.workers.values()
],
"todos": session.todos,
"goal": session.goal,
"turns": session.turns,
"created_at": session.created_at,
"api_session": session.api_session,
"worker_seq": session.worker_seq,
"busy": bool(session.busy),
"direct_chats": [chat.meta() for chat in chats.values()],
}
# Keep the session metadata fields available at the top level as well as in
# ``meta``. This makes the snapshot convenient for simple HTTP clients.
for key, value in meta.items():
if key not in state:
state[key] = value
return _json_safe(state)
def worker_from_state(item: Mapping[str, Any], config: Config) -> Worker:
"""Construct one worker snapshot from a ``workers`` state entry."""
if not isinstance(item, Mapping) or not isinstance(item.get("meta"), Mapping):
raise TypeError("worker snapshot должен содержать meta")
worker = Worker.from_meta(dict(item["meta"]), config)
messages = item.get("messages")
worker.messages = list(messages) if isinstance(messages, list) else []
if worker.messages and worker.messages[0].get("role") == "system":
worker.system_prompt = str(worker.messages[0].get("content") or "")
return worker
+7
View File
@@ -132,6 +132,8 @@ class Session:
config.worker_model = str(meta.get("worker_model") or config.worker_model)
settings = meta.get("settings") or {}
if isinstance(settings, dict):
if "animations" in settings:
config.ui.animations = bool(settings["animations"])
if settings.get("max_workers"):
try:
config.limits.max_workers = max(1, int(settings["max_workers"]))
@@ -245,6 +247,7 @@ class Session:
"plan": self.todos,
"settings": {
"max_workers": self.config.limits.max_workers,
"animations": self.config.ui.animations,
"intelligence": dict(self.config.intelligence),
"roles": {
name: role.model for name, role in self.config.roles.items()
@@ -1158,6 +1161,7 @@ class Session:
roles: dict[str, str] | None = None,
orchestrator_provider: str | None = None,
worker_provider: str | None = None,
animations: bool | None = None,
) -> None:
if max_workers is not None:
self.config.limits.max_workers = max(1, min(int(max_workers), 32))
@@ -1178,6 +1182,8 @@ class Session:
self.config.orchestrator_provider = str(orchestrator_provider)
if worker_provider is not None:
self.config.worker_provider = str(worker_provider)
if animations is not None:
self.config.ui.animations = bool(animations)
self.refresh_system_prompt()
self.save_all()
self.emit(
@@ -1189,6 +1195,7 @@ class Session:
roles={name: role.model for name, role in self.config.roles.items()},
orchestrator_provider=self.config.orchestrator_provider,
worker_provider=self.config.worker_provider,
animations=self.config.ui.animations,
)
def set_plan(self, raw_tasks: Any) -> dict[str, Any]:
+79
View File
@@ -0,0 +1,79 @@
---
name: AiRouter Workers
description: Auto-invoke when the user wants OpenCode workers shown in the AiRouter console, synchronized worker chats, or a local agent dashboard.
---
# AiRouter Workers
Use AiRouter as the local console for OpenCode-driven work. Keep the service,
workers, and console synchronized; never run a second, disconnected worker loop.
## Workflow
1. Ensure the local service is running:
```sh
airouter service start
```
2. Create each worker explicitly and use the requested role and workspace:
```sh
airouter ctl worker create --task "Describe the task" --role coder --workspace "/absolute/workspace"
```
Optional flags are `--name`, `--model`, and `--provider`. Read the returned
worker ID (for example, `w1`) and use that exact ID in later commands. Do not
invent IDs or assume creation order.
3. Open the AiRouter console **inside OpenCode** by creating a PTY through the
OpenCode V2 API. Replace `<absolute cwd>` with the real absolute path:
```sh
opencode api post /api/pty --data '{"command":"airouter","args":["attach"],"cwd":"<absolute cwd>","title":"AiRouter Workers"}'
```
Switch to the created PTY to use the console. Do **not** run blocking
`airouter attach` directly in a shell tool.
4. Keep worker chats synchronized through the service SSE stream. The console
receives worker messages, progress, completion, failures, and direct-chat
events without starting local worker tasks. Use the console to inspect the
conversation and reports.
5. Message, retry, or cancel workers through `airouter ctl` using their IDs:
```sh
airouter ctl worker message w1 --message "Additional context or next step"
airouter ctl worker retry w1
airouter ctl worker cancel w1 --reason "No longer needed"
```
Use `airouter ctl worker list` to confirm current IDs and statuses. Wait for a
worker to finish before sending a follow-up or retrying it.
## Security
The service token authenticates local clients. Do not print it, paste it into a
worker prompt, commit it, or read it from the runtime file just to configure the
console. Let `airouter service` and `airouter attach` manage authentication.
## Updates
AiRouter checks remote Git tags for `vMAJOR.MINOR.PATCH` releases and caches a
successful check for six hours:
```sh
airouter update
```
If an update is available, tell the user and install it with:
```sh
airouter update install
```
Updates only fast-forward a clean Git checkout. If the working tree is dirty or
history is not fast-forward, stop and report that the update was refused; never
stash, reset, or discard the user's changes. Restart AiRouter after source files
change.
+53
View File
@@ -75,6 +75,59 @@ class BrailleSpinner(Static):
self.update(Text(spinner_frame(self._tick), style="#f0a35e"))
_ACTIVITY_FRAMES = (
"▁▂▃▄▅▆▇",
"▂▃▄▅▆▇▆",
"▃▄▅▆▇▆▅",
"▄▅▆▇▆▅▄",
"▅▆▇▆▅▄▃",
"▆▇▆▅▄▃▂",
"▇▆▅▄▃▂▁",
"▆▅▄▃▂▁▂",
"▅▄▃▂▁▂▃",
"▄▃▂▁▂▃▄",
"▃▂▁▂▃▄▅",
"▂▁▂▃▄▅▆",
)
class ActivityWave(Static):
"""A compact animated equalizer for active agent work."""
def __init__(self, *, active: bool = False, reduced: bool = False, **kwargs) -> None:
super().__init__("", **kwargs)
self.active = active
self.reduced = reduced
self._tick = 0
def on_mount(self) -> None:
self.set_interval(0.12, self._advance)
self._draw()
def set_active(self, active: bool, *, reduced: bool | None = None) -> None:
self.active = active
if reduced is not None:
self.reduced = reduced
self._draw()
def _advance(self) -> None:
if not self.display or self.reduced:
return
self._tick += 1
self._draw()
def _draw(self) -> None:
if not self.active:
self.update(Text("▁▁▁▁▁▁▁", style="#3a3f49"))
return
frame = "▁▂▃▄▅▆▇" if self.reduced else _ACTIVITY_FRAMES[self._tick % len(_ACTIVITY_FRAMES)]
text = Text()
colors = ("#7dd3fc", "#818cf8", "#a78bfa", "#c084fc", "#e879f9")
for index, char in enumerate(frame):
text.append(char, style=f"bold {colors[index % len(colors)]}")
self.update(text)
class BootLoader(Static):
"""BIPfR-style startup screen: breathing braille word, halo, star dust."""
+368 -72
View File
@@ -4,6 +4,8 @@ from __future__ import annotations
import asyncio
import copy
import inspect
import os
import time
from pathlib import Path
from typing import Any
@@ -15,6 +17,7 @@ from rich.text import Text
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Horizontal, Vertical
from textual.events import Resize
from textual.message import Message
from textual.widgets import Button, Input, RichLog, Static, TabbedContent
@@ -32,10 +35,12 @@ from ..events import Event
from ..models import ModelInfo, fetch_models
from ..provider import OpenAIClient, ProviderError
from ..providers import ProviderRegistry
from ..remote import RemoteSession
from ..service import ServiceClient
from ..session import Session, SessionError
from ..storage import SessionStore, StorageError
from ..utils import format_cost, format_duration, format_tokens, truncate
from .anim import BootLoader, BrailleSpinner
from .anim import BootLoader, ActivityWave
from .screens import (
ConfirmScreen,
NewChatScreen,
@@ -61,6 +66,12 @@ class SessionEvent(Message):
self.event = event
def _wrap_path(path: str | Path) -> str:
"""Allow long paths to wrap in narrow chat panes."""
return str(path).replace("/", "/\u200b")
class AirouterApp(App[int]):
TITLE = "AiRouter"
SUB_TITLE = "orchestrator · chats · workers · providers"
@@ -78,8 +89,9 @@ class AirouterApp(App[int]):
}
#brand { width: 12; content-align: left middle; color: #f0a35e; text-style: bold; }
#session-label { width: 1fr; content-align: left middle; color: #7f8490; }
#busy { width: 2; height: 3; content-align: center middle; color: #f0a35e; }
#busy { width: 8; height: 3; content-align: center middle; color: #f0a35e; }
#main-state { width: auto; content-align: right middle; color: #7f8490; padding: 0 1; }
#session-label { min-width: 0; overflow: hidden; }
#topbar Button {
height: 3; min-width: 0; padding: 0 1; background: transparent; border: none; color: #8b909b;
}
@@ -146,6 +158,18 @@ class AirouterApp(App[int]):
TodoRow:hover, WorkerRow:hover { background: #191c23; }
TodoRow.-highlight, WorkerRow.-highlight { background: #1c2028; }
.todo-body, .worker-body { height: auto; }
#workers-activity { width: 8; height: 1; }
Screen.compact #sidebar { display: none; }
Screen.compact #main-state { display: none; }
Screen.compact #message-fork, Screen.compact #worker-report { display: none; }
Screen.narrow #session-label, Screen.narrow #main-state { display: none; }
Screen.narrow #topbar { padding: 0 1; }
Screen.narrow #topbar Button { padding: 0; min-width: 3; }
Screen.narrow #chat-selection { max-width: 16; overflow: hidden; }
Screen.narrow #message-fork, Screen.narrow #worker-report { display: none; }
Screen.narrow #send { width: 6; }
Screen.narrow #stop { width: 5; }
Screen.narrow #prompt { min-width: 8; }
#statusbar { height: 1; background: #0b0d11; color: #6f747e; padding: 0 2; }
"""
@@ -164,7 +188,7 @@ class AirouterApp(App[int]):
self,
*,
config: Config,
provider: OpenAIClient,
provider: OpenAIClient | None,
sessions_root: Path,
cwd: Path,
resume: bool = False,
@@ -174,10 +198,12 @@ class AirouterApp(App[int]):
max_workers_override: int | None = None,
models: list[ModelInfo] | None = None,
provider_registry: ProviderRegistry | None = None,
service_client: ServiceClient | None = None,
) -> None:
super().__init__()
self.config = config
self.provider = provider
self.service_client = service_client
self.provider_registry = provider_registry
if self.provider_registry is None and isinstance(provider, OpenAIClient):
self.provider_registry = ProviderRegistry(config, tokens=provider.tokens)
@@ -201,6 +227,7 @@ class AirouterApp(App[int]):
self._active_chat = "main"
self._chat_tasks: dict[str, asyncio.Task[Any]] = {}
self._busy = False
self._stopping = False
self._turn_task: asyncio.Task[Any] | None = None
self._main_error = ""
self._stream_text = ""
@@ -219,6 +246,8 @@ class AirouterApp(App[int]):
self._ui_ready = False
self._failed = False
self._init_task: asyncio.Task[Any] | None = None
self._service_events_task: asyncio.Task[Any] | None = None
self._service_online = True
self._panels_lock = asyncio.Lock()
@property
@@ -239,7 +268,7 @@ class AirouterApp(App[int]):
with Horizontal(id="topbar"):
yield Static("AiRouter", id="brand")
yield Static(id="session-label")
yield BrailleSpinner(id="busy")
yield ActivityWave(id="busy")
yield Static("загрузка…", id="main-state")
yield Button("+ Чат", id="new-chat", compact=True)
yield Button("Папка", id="workspace", compact=True)
@@ -285,15 +314,60 @@ class AirouterApp(App[int]):
self.root.query_one("#chat-actions").display = False
self.root.query_one("#composer").display = False
self.root.query_one("#sidebar").display = False
self.root.query_one("#busy", BrailleSpinner).display = True
self.root.query_one("#busy", ActivityWave).display = True
self.root.query_one("#boot", BootLoader).set_message("инициализация сессии")
for button_id in ("settings", "providers", "new-chat", "workspace"):
self.root.query_one(f"#{button_id}", Button).disabled = True
self.root.query_one("#prompt", Input).focus()
self._apply_responsive(self.size.width)
self.set_interval(0.15, self._tick)
self.set_interval(1.0, self._stats_tick)
self._init_task = asyncio.create_task(self._initialize())
def on_resize(self, event: Resize) -> None:
self._apply_responsive(event.size.width)
def _apply_responsive(self, width: int) -> None:
narrow = width < 100
compact = width < 120
self.set_class(narrow, "narrow")
self.set_class(compact, "compact")
self.screen.set_class(narrow, "narrow")
self.screen.set_class(compact, "compact")
for widget_id, visible in (
("sidebar", not compact),
("session-label", not narrow),
("main-state", not compact),
("message-fork", not compact),
("worker-report", not compact),
):
try:
self.root.query_one(f"#{widget_id}").display = visible
except Exception:
pass
labels = {
"new-chat": "+" if narrow else "+ Чат",
"workspace": "Папка",
"providers": "API" if narrow else "Провайдеры",
"settings": "⚙" if narrow else "Настройки",
"quit": "×" if narrow else "Выход",
"send": "▶" if narrow else "Отправить",
"stop": "■" if narrow else "Стоп",
}
for button_id, label in labels.items():
try:
button = self.root.query_one(f"#{button_id}", Button)
button.label = label
except Exception:
pass
def _animations_enabled(self) -> bool:
return bool(
getattr(self.config.ui, "animations", True)
and os.environ.get("AIROUTER_REDUCED_MOTION", "").lower()
not in {"1", "true", "yes", "on"}
)
async def _initialize(self) -> None:
boot = self.root.query_one("#boot", BootLoader)
started = asyncio.get_event_loop().time()
@@ -303,7 +377,10 @@ class AirouterApp(App[int]):
boot.set_message("подключаю модели")
if not self.models:
try:
self.models = await asyncio.to_thread(self._fetch_models)
if self.service_client is not None:
self.models = await self.service_client.models()
else:
self.models = await asyncio.to_thread(self._fetch_models)
except Exception:
self.models = []
await self._restore_chat_tabs()
@@ -318,7 +395,7 @@ class AirouterApp(App[int]):
self.root.query_one("#chat-tabs", TabbedContent).display = True
self.root.query_one("#chat-actions").display = True
self.root.query_one("#composer").display = True
self.root.query_one("#sidebar").display = True
self.root.query_one("#sidebar").display = self.size.width >= 120
for button_id in ("settings", "providers", "new-chat", "workspace"):
self.root.query_one(f"#{button_id}", Button).disabled = False
self._welcome()
@@ -337,6 +414,17 @@ class AirouterApp(App[int]):
self._update_busy_controls()
async def _load_session(self) -> None:
if self.service_client is not None:
state = await self.service_client.state()
session = RemoteSession.from_state(self.service_client, state)
self.session = session
self.config = session.config
self.cwd = session.cwd
self._resumed = True
self.chat_store = DirectChatStore(session.store.dir / "chats.json")
self.direct_chats = self.chat_store.load()
self._service_events_task = asyncio.create_task(self._listen_service_events())
return
session: Session | None = None
resumed = False
if self.session_id:
@@ -486,7 +574,7 @@ class AirouterApp(App[int]):
Text(
f"{worker.id} · {worker.name} · {worker.role.name}\n"
f"{worker.provider_id + '/' if worker.provider_id else ''}{worker.model}"
f" · {worker.workspace_path}",
f" · {_wrap_path(worker.workspace_path)}",
style="#8b909b",
)
)
@@ -509,7 +597,7 @@ class AirouterApp(App[int]):
log.write(
Text(
f"{chat.title} · {chat.provider_id + '/' if chat.provider_id else ''}{chat.model}"
f"\n{chat.workspace}",
f"\n{_wrap_path(chat.workspace)}",
style="#8b909b",
)
)
@@ -684,6 +772,52 @@ class AirouterApp(App[int]):
return
self.post_message(SessionEvent(event))
async def _listen_service_events(self) -> None:
if self.service_client is None:
return
while not self._closed:
try:
async for payload in self.service_client.events():
if not self._service_online:
self._service_online = True
self.notify("Сервис синхронизации снова доступен", title="AiRouter", timeout=3)
event_type = str(payload.get("type") or "")
data = payload.get("data") or {}
if payload.get("direct") or event_type.startswith("direct_"):
chat_id = str(data.get("chat_id") or "")
if chat_id:
self._direct_event(chat_id, event_type, data)
continue
event = Event(
type=event_type,
worker_id=payload.get("worker_id"),
data=data,
transient=bool(payload.get("transient", False)),
)
if event_type not in {
"main_text_delta",
"main_reasoning_delta",
"worker_text_delta",
"worker_reasoning_delta",
} and self.session is not None:
await self.session.refresh()
self.config = self.session.config
self._session_listener(event)
except asyncio.CancelledError:
raise
except Exception:
if self._closed:
return
if self._service_online:
self._service_online = False
self.notify(
"Сервис синхронизации недоступен; переподключаюсь…",
title="AiRouter",
severity="warning",
timeout=4,
)
await asyncio.sleep(1.0)
async def on_session_event(self, message: SessionEvent) -> None:
event = message.event
t = event.type
@@ -758,6 +892,12 @@ class AirouterApp(App[int]):
)
await self._refresh_panels()
if t == "worker_done":
self.notify(
f"{event.worker_id} {d.get('name')}: готово",
title="AiRouter",
severity="information",
timeout=4,
)
self._write_event(
f"ok {event.worker_id} {d.get('name')} · "
f"{format_duration(d.get('duration'))} · файлов: "
@@ -765,6 +905,12 @@ class AirouterApp(App[int]):
"#7fbf9f",
)
elif t == "worker_failed":
self.notify(
f"{event.worker_id}: {truncate(str(d.get('error', '')), 120)}",
title="AiRouter",
severity="warning",
timeout=6,
)
self._write_event(
f"!! {event.worker_id} {d.get('name')} · {d.get('error', '')}",
"#e06c75",
@@ -863,6 +1009,26 @@ class AirouterApp(App[int]):
frame = spinner_frame(self._tick_count)
if self._failed:
return
try:
self.root.query_one("#busy", ActivityWave).set_active(
bool(
not self._ui_ready
or self._busy
or self._chat_tasks
or (self.session and self.session.running_workers())
),
reduced=not self._animations_enabled(),
)
if self._animations_enabled():
palette = ("#f0a35e", "#f6b878", "#c084fc", "#818cf8", "#7dd3fc")
self.root.query_one("#brand", Static).update(
Text(
"AiRouter",
style=f"bold {palette[(self._tick_count // 3) % len(palette)]}",
)
)
except Exception:
pass
if not self._ui_ready:
self._set_state("загрузка…")
self._update_busy_controls()
@@ -922,6 +1088,7 @@ class AirouterApp(App[int]):
provider = self.session.config.orchestrator_provider or self.session.config.active_provider
self.root.query_one("#session-label", Static).update(
Text(
f"{'sync · ' if self.service_client else ''}"
f"{provider}/{self.session.config.orchestrator_model}"
f" · воркеров {len(self.session.workers)}/{self.session.config.limits.max_workers}",
style="#7f8490",
@@ -952,7 +1119,7 @@ class AirouterApp(App[int]):
self.root.query_one("#stop", Button).disabled = not (
active_task or self._busy or running
)
self.root.query_one("#busy", BrailleSpinner).display = bool(
self.root.query_one("#busy", ActivityWave).display = bool(
(self._busy or running or any(self._chat_tasks.values()) or not self._ui_ready)
and not self._failed
)
@@ -1032,7 +1199,7 @@ class AirouterApp(App[int]):
self._rendered_direct[chat.id] = len(chat.messages)
self._select_default_message(chat.id)
self._start_direct_turn(chat)
if self.chat_store:
if self.chat_store and self.service_client is None:
self.chat_store.save(self.direct_chats)
def _start_main_turn(self, text: str) -> None:
@@ -1058,6 +1225,8 @@ class AirouterApp(App[int]):
Panel(Text(self._main_error), title="Ошибка", border_style="#e06c75", padding=(0, 1))
)
except Exception as exc: # pragma: no cover - defensive
if self._stopping:
return
self._main_error = f"{type(exc).__name__}: {exc}"
self._chat_log("main").write(
Panel(Text(self._main_error), title="Ошибка", border_style="#e06c75", padding=(0, 1))
@@ -1092,6 +1261,8 @@ class AirouterApp(App[int]):
Panel(Text(self._main_error), title="Ошибка", border_style="#e06c75", padding=(0, 1))
)
except Exception as exc:
if self._stopping:
return
self._main_error = f"{type(exc).__name__}: {exc}"
self._chat_log("main").write(Panel(Text(self._main_error), title="Ошибка", border_style="red"))
finally:
@@ -1110,11 +1281,11 @@ class AirouterApp(App[int]):
async def _run_direct_turn(self, chat: DirectChat) -> None:
assert self.session is not None
try:
await run_direct_chat(
self.session,
chat,
emit=lambda event_type, data: self._direct_event(chat.id, event_type, data),
)
emit = lambda event_type, data: self._direct_event(chat.id, event_type, data)
if getattr(self.session, "remote", False):
await self.session.run_direct_chat(chat, emit=emit) # type: ignore[attr-defined]
else:
await run_direct_chat(self.session, chat, emit=emit)
except asyncio.CancelledError:
pass
except Exception:
@@ -1123,11 +1294,35 @@ class AirouterApp(App[int]):
finally:
self._chat_tasks.pop(chat.id, None)
self._finalize_stream(chat.id)
if self.chat_store:
if self.service_client is not None:
await self._refresh_remote_directs()
if self.chat_store and self.service_client is None:
self.chat_store.save(self.direct_chats)
self._select_default_message(chat.id)
self._update_busy_controls()
async def _refresh_remote_directs(self) -> None:
if self.service_client is None:
return
try:
state = await self.service_client.state()
except Exception:
return
for raw in state.get("direct_chats", []):
if not isinstance(raw, dict) or not raw.get("id"):
continue
incoming = DirectChat.from_meta(raw)
current = self.direct_chats.get(incoming.id)
if current is None:
self.direct_chats[incoming.id] = incoming
continue
current.messages = incoming.messages
current.usage = incoming.usage
current.error = incoming.error
current.updated_at = incoming.updated_at
for chat_id in list(self._direct_panes):
self._sync_direct_chat(chat_id)
def _direct_event(self, chat_id: str, event_type: str, data: dict[str, Any]) -> None:
if chat_id not in self.direct_chats or chat_id not in self._direct_panes:
return
@@ -1137,19 +1332,26 @@ class AirouterApp(App[int]):
)
self._direct_stream_dirty.add(chat_id)
elif event_type == "direct_assistant_message":
self._finalize_stream(chat_id, write_text=False)
if self.service_client is None:
self._finalize_stream(chat_id, write_text=False)
self._sync_direct_chat(chat_id)
elif event_type == "direct_tool_result":
self._sync_direct_chat(chat_id)
elif event_type == "direct_error":
self._finalize_stream(chat_id)
if chat_id in self.direct_chats:
self.direct_chats[chat_id].error = str(data.get("text", ""))
self._chat_log(chat_id).write(
Panel(Text(str(data.get("text", ""))), title="Ошибка", border_style="#e06c75")
)
asyncio.create_task(self._refresh_remote_directs())
elif event_type in {"direct_done", "direct_cancelled"}:
if chat_id in self.direct_chats and event_type == "direct_done":
self.direct_chats[chat_id].error = ""
self._finalize_stream(chat_id, write_text=False)
self._sync_direct_chat(chat_id)
if self.chat_store and event_type not in {
asyncio.create_task(self._refresh_remote_directs())
if self.chat_store and self.service_client is None and event_type not in {
"direct_step",
"direct_text_delta",
"direct_reasoning_delta",
@@ -1186,22 +1388,34 @@ class AirouterApp(App[int]):
async def _stop(self) -> None:
active = self._active_chat
task = self._chat_tasks.get(active)
if task:
task.cancel()
await asyncio.gather(task, return_exceptions=True)
self._chat_tasks.pop(active, None)
elif active.startswith("worker:") and self.session:
await self.session._tool_cancel_worker(active.split(":", 1)[1], "Остановлено пользователем")
elif self._turn_task:
self._turn_task.cancel()
await asyncio.gather(self._turn_task, return_exceptions=True)
self._turn_task = None
if self.session and (active == "main" or not task):
await self.session.cancel_all_workers()
self._set_busy(False)
self._finalize_stream(active)
self._write_event("остановлено", "yellow")
await self._refresh_panels()
self._stopping = True
try:
if self.service_client is not None and self.session is not None:
try:
if active == "main":
await self.session.interrupt() # type: ignore[attr-defined]
elif active != "main" and not active.startswith("worker:"):
await self.session.cancel_direct_chat(active) # type: ignore[attr-defined]
except Exception:
pass
if task:
task.cancel()
await asyncio.gather(task, return_exceptions=True)
self._chat_tasks.pop(active, None)
elif active.startswith("worker:") and self.session:
await self.session._tool_cancel_worker(active.split(":", 1)[1], "Остановлено пользователем")
elif self._turn_task:
self._turn_task.cancel()
await asyncio.gather(self._turn_task, return_exceptions=True)
self._turn_task = None
if self.session and (active == "main" or not task):
await self.session.cancel_all_workers()
finally:
self._stopping = False
self._set_busy(False)
self._finalize_stream(active)
self._write_event("остановлено", "yellow")
await self._refresh_panels()
# ------------------------------------------------------------------ message actions
@@ -1239,6 +1453,18 @@ class AirouterApp(App[int]):
return
chat_id = self._active_chat
messages = self._messages_for(chat_id)
if self.service_client is not None:
try:
await self.session.delete_message(chat_id, index) # type: ignore[attr-defined]
if chat_id != "main" and not chat_id.startswith("worker:"):
await self._refresh_remote_directs()
self._selected_messages.pop(chat_id, None)
self._manual_selections.discard(chat_id)
self._rerender_active()
self._write_event("сообщение удалено", "dim")
except Exception as exc:
self._write_event(str(exc), "red")
return
try:
updated = delete_visible_message(messages, index)
except ValueError as exc:
@@ -1266,8 +1492,13 @@ class AirouterApp(App[int]):
role = messages[index].get("role")
chat_id = self._active_chat
if role == "assistant":
del messages[index:]
self._save_messages(chat_id)
if self.service_client is not None:
await self.session.truncate_messages(chat_id, index) # type: ignore[attr-defined]
if chat_id != "main" and not chat_id.startswith("worker:"):
await self._refresh_remote_directs()
else:
del messages[index:]
self._save_messages(chat_id)
self._rerender_active()
if chat_id == "main":
self._start_main_continuation()
@@ -1306,7 +1537,11 @@ class AirouterApp(App[int]):
if messages and messages[-1].get("role") == "assistant" and not messages[-1].get("tool_calls"):
index = last_visible_index(messages)
if index is not None:
del messages[index:]
if self.service_client is not None:
await self.session.truncate_messages(chat_id, index) # type: ignore[attr-defined]
await self._refresh_remote_directs()
else:
del messages[index:]
chat.error = ""
self._rerender_active()
self._start_direct_turn(chat)
@@ -1324,10 +1559,14 @@ class AirouterApp(App[int]):
try:
if chat_id == "main":
forked = self.session.fork_session(prefix)
if inspect.isawaitable(forked):
forked = await forked
await self._attach_session(forked, resumed=False)
self._write_event(f"создан fork сессии {forked.id}", "cyan")
elif chat_id.startswith("worker:"):
worker = self.session.fork_worker(chat_id.split(":", 1)[1], prefix)
if inspect.isawaitable(worker):
worker = await worker
await self._add_worker_tab(worker.id)
await self._activate_chat(f"worker:{worker.id}")
await self._refresh_panels()
@@ -1479,7 +1718,9 @@ class AirouterApp(App[int]):
if command in {"workspace", "cd", "dir"}:
if arg:
try:
self.session.change_workspace(arg)
changed = self.session.change_workspace(arg)
if inspect.isawaitable(changed):
await changed
self._refresh_header()
except Exception as exc:
self._write_event(str(exc), "red")
@@ -1540,7 +1781,13 @@ class AirouterApp(App[int]):
)
return
if command == "cancel":
if self.service_client is not None:
await self.session.interrupt() # type: ignore[attr-defined]
await self.session.cancel_all_workers()
if self.service_client is not None:
for chat_id in list(self._chat_tasks):
if chat_id != "main" and not chat_id.startswith("worker:"):
await self.session.cancel_direct_chat(chat_id) # type: ignore[attr-defined]
for task in list(self._chat_tasks.values()):
task.cancel()
self._write_event("все воркеры и активные чаты остановлены", "yellow")
@@ -1564,13 +1811,17 @@ class AirouterApp(App[int]):
self._write_event("сначала дождитесь воркеров/чатов или /cancel", "yellow")
return
self.session.save_all()
new_session = Session.create(
sessions_root=self.session.store.sessions_root,
config=self.session.config,
provider=self.provider,
cwd=self.session.cwd,
provider_registry=self.provider_registry,
)
if self.service_client is not None:
state = await self.service_client.request("POST", "/session/new", {})
new_session = RemoteSession.from_state(self.service_client, state)
else:
new_session = Session.create(
sessions_root=self.session.store.sessions_root,
config=self.session.config,
provider=self.provider,
cwd=self.session.cwd,
provider_registry=self.provider_registry,
)
await self._attach_session(new_session, resumed=False)
return
if command == "sessions":
@@ -1584,14 +1835,20 @@ class AirouterApp(App[int]):
self._write_event("сначала дождитесь завершения работы", "yellow")
return
try:
new_session = await asyncio.to_thread(
Session.load,
sessions_root=self.session.store.sessions_root,
session_id=arg,
config=self.session.config,
provider=self.provider,
provider_registry=self.provider_registry,
)
if self.service_client is not None:
state = await self.service_client.request(
"POST", "/session/resume", {"session_id": arg}
)
new_session = RemoteSession.from_state(self.service_client, state)
else:
new_session = await asyncio.to_thread(
Session.load,
sessions_root=self.session.store.sessions_root,
session_id=arg,
config=self.session.config,
provider=self.provider,
provider_registry=self.provider_registry,
)
except (StorageError, ConfigError, OSError) as exc:
self._write_event(str(exc), "red")
return
@@ -1727,13 +1984,15 @@ class AirouterApp(App[int]):
callback=self._settings_saved,
)
def _settings_saved(self, result: dict[str, Any] | None) -> None:
async def _settings_saved(self, result: dict[str, Any] | None) -> None:
if not result or not self.session:
return
if result.get("action") == "providers":
self.action_open_providers()
return
self.session.apply_settings(**result)
applied = self.session.apply_settings(**result)
if inspect.isawaitable(applied):
await applied
self._refresh_header()
self._write_event(
f"настройки: max воркеров {result['max_workers']}, "
@@ -1761,6 +2020,14 @@ class AirouterApp(App[int]):
return
action = result.get("action")
try:
if self.service_client is not None:
await self.session.update_provider(action, profile) # type: ignore[attr-defined]
await self.session.refresh() # type: ignore[attr-defined]
self.config = self.session.config
self.models = await self.service_client.models()
self._refresh_header()
self._write_event(f"провайдер {profile.id}: {action}", "cyan")
return
if action == "delete":
if len(self.config.providers) <= 1:
raise ConfigError("Нельзя удалить последний провайдер")
@@ -1844,10 +2111,12 @@ class AirouterApp(App[int]):
if not result or not self.session:
return
try:
self.session.change_workspace(
changed = self.session.change_workspace(
result.get("path", self.session.cwd),
create=bool(result.get("create", True)),
)
if inspect.isawaitable(changed):
await changed
self._refresh_header()
except Exception as exc:
self._write_event(str(exc), "red")
@@ -1873,19 +2142,35 @@ class AirouterApp(App[int]):
callback=self._confirm_delete_session,
)
return
loaded = await asyncio.to_thread(
Session.load,
sessions_root=self.session.store.sessions_root,
session_id=session_id,
config=self.session.config,
provider=self.provider,
provider_registry=self.provider_registry,
)
if self.service_client is not None:
state = await self.service_client.request(
"POST", "/session/resume", {"session_id": session_id}
)
loaded = RemoteSession.from_state(self.service_client, state)
else:
loaded = await asyncio.to_thread(
Session.load,
sessions_root=self.session.store.sessions_root,
session_id=session_id,
config=self.session.config,
provider=self.provider,
provider_registry=self.provider_registry,
)
if action == "fork":
index = last_visible_index(loaded.main_messages)
if index is None:
raise SessionError("В сессии нет сообщений для форка")
loaded = loaded.fork_session(copy.deepcopy(loaded.main_messages[: index + 1]))
if self.service_client is not None:
state = await self.service_client.request(
"POST",
"/session/fork",
{"messages": copy.deepcopy(loaded.main_messages[: index + 1])},
)
loaded = RemoteSession.from_state(self.service_client, state)
else:
loaded = loaded.fork_session(
copy.deepcopy(loaded.main_messages[: index + 1])
)
await self._attach_session(loaded, resumed=action == "open")
except Exception as exc:
self._write_event(str(exc), "red")
@@ -1923,12 +2208,19 @@ class AirouterApp(App[int]):
if self._init_task:
self._init_task.cancel()
await asyncio.gather(self._init_task, return_exceptions=True)
if self._service_events_task:
self._service_events_task.cancel()
await asyncio.gather(self._service_events_task, return_exceptions=True)
self._service_events_task = None
if self.session:
await self.session.cancel_all_workers()
if self.service_client is None:
await self.session.cancel_all_workers()
self.session.save_all()
if self.provider_registry is not None:
if self.service_client is not None:
await self.service_client.aclose()
elif self.provider_registry is not None:
await self.provider_registry.aclose()
else:
elif self.provider is not None:
await self.provider.aclose()
except Exception:
pass
@@ -1940,9 +2232,11 @@ class AirouterApp(App[int]):
try:
if self.session:
self.session.save_all()
if self.provider_registry is not None:
if self.service_client is not None:
asyncio.get_running_loop().create_task(self.service_client.aclose())
elif self.provider_registry is not None:
asyncio.get_running_loop().create_task(self.provider_registry.aclose())
else:
elif self.provider is not None:
asyncio.get_running_loop().create_task(self.provider.aclose())
except Exception:
pass
@@ -1951,7 +2245,7 @@ class AirouterApp(App[int]):
def run_tui_app(
*,
config: Config,
provider: OpenAIClient,
provider: OpenAIClient | None,
sessions_root: Path,
cwd: Path,
resume: bool = False,
@@ -1961,6 +2255,7 @@ def run_tui_app(
max_workers_override: int | None = None,
models: list[ModelInfo] | None = None,
provider_registry: ProviderRegistry | None = None,
service_client: ServiceClient | None = None,
) -> int:
"""Synchronous TUI entry point (used by the CLI)."""
@@ -1976,6 +2271,7 @@ def run_tui_app(
max_workers_override=max_workers_override,
models=models,
provider_registry=provider_registry,
service_client=service_client,
)
result = app.run(mouse=True)
return int(result or 0)
+7 -3
View File
@@ -90,7 +90,7 @@ class SettingsScreen(ModalScreen[dict[str, Any]]):
CSS = """
SettingsScreen { align: center middle; background: #050608 55%; }
#settings-dialog {
width: 92; height: 88%; border: solid #343945; background: #14171d; padding: 1 2;
width: 92; max-width: 96%; height: 88%; border: solid #343945; background: #14171d; padding: 1 2;
}
#settings-head { height: 3; layout: horizontal; }
#settings-title { width: 1fr; content-align: left middle; text-style: bold; color: #f0a35e; }
@@ -100,7 +100,7 @@ class SettingsScreen(ModalScreen[dict[str, Any]]):
.section-label { height: 2; content-align: left bottom; color: #f0a35e; text-style: bold; margin-top: 1; }
.field { height: 2; layout: horizontal; align-vertical: middle; }
.field-label { width: 29; height: 2; content-align: left middle; color: #9a9fa9; }
.field Select { width: 51; height: 1; }
.field Select { width: 1fr; height: 1; }
#settings-hint { height: auto; color: #7f8490; padding: 1 0; }
Collapsible { background: #171a21; border: solid #262b35; margin: 1 0; }
#settings-buttons { height: 3; align-horizontal: right; margin-top: 1; }
@@ -182,6 +182,9 @@ class SettingsScreen(ModalScreen[dict[str, Any]]):
compact=True,
id="setting-max-workers",
)
with Horizontal(classes="field"):
yield Static("Анимации интерфейса", classes="field-label")
yield Switch(value=config.ui.animations, id="setting-animations")
yield Static(
"Модель можно указать как provider/model. Провайдеры добавляются "
"через /providers; локальные Ollama, LM Studio, vLLM и llama.cpp "
@@ -266,6 +269,7 @@ class SettingsScreen(ModalScreen[dict[str, Any]]):
"worker_model": worker_model,
"orchestrator_provider": main_provider,
"worker_provider": worker_provider,
"animations": bool(self.query_one("#setting-animations", Switch).value),
"intelligence": intelligence,
"roles": roles,
}
@@ -551,7 +555,7 @@ class NewChatScreen(ModalScreen[dict[str, Any]]):
CSS = """
NewChatScreen { align: center middle; background: #050608 60%; }
#new-chat-dialog { width: 78; height: auto; border: solid #343945; background: #14171d; padding: 1 2; }
#new-chat-dialog { width: 78; max-width: 94%; height: auto; border: solid #343945; background: #14171d; padding: 1 2; }
#new-chat-title { height: 2; color: #f0a35e; text-style: bold; }
.chat-field { height: 3; layout: horizontal; }
.chat-field-label { width: 22; content-align: left middle; color: #9a9fa9; }
+19 -6
View File
@@ -14,7 +14,7 @@ from textual.widgets import ListItem, ListView, ProgressBar, RichLog, Static, Ta
from ..session import Session
from ..utils import format_cost, format_duration, format_tokens, truncate
from ..worker import Worker
from .anim import spinner_frame
from .anim import ActivityWave, spinner_frame
STATUS_ICON = {
"pending": ("[ ]", "#6f747e"),
@@ -233,6 +233,7 @@ class WorkersPanel(Vertical):
def compose(self) -> ComposeResult:
with Horizontal(classes="panel-head"):
yield Static("ВОРКЕРЫ", classes="panel-title")
yield ActivityWave(id="workers-activity", classes="panel-meta")
yield Static("0", id="workers-count", classes="panel-meta")
yield Static("Воркеров пока нет.", id="workers-empty", classes="empty-state")
yield ClickListView(id="workers-list")
@@ -272,6 +273,13 @@ class WorkersPanel(Vertical):
row.render_worker(session.workers[row.worker_id])
def tick(self, session: Session, tick: int) -> None:
try:
self.query_one("#workers-activity", ActivityWave).set_active(
bool(session.running_workers()),
reduced=not session.config.ui.animations,
)
except Exception:
pass
for worker_id, row in self._rows.items():
worker = session.workers.get(worker_id)
if worker:
@@ -315,8 +323,12 @@ class StatsLine(Static):
done = sum(1 for task in session.todos if task.get("status") == "done")
percent = min(100, int(stats["context_tokens_estimate"] * 100 / max(1, limit)))
text = Text()
text.append(f" {cwd}", style="#8b909b")
text.append(" · ", style="#3a3f49")
compact = self.size.width < 100
if not compact:
text.append(f" {cwd}", style="#8b909b")
text.append(" · ", style="#3a3f49")
else:
text.append(" ")
text.append(session.config.orchestrator_model, style="#f0a35e")
text.append(" · ", style="#3a3f49")
text.append(
@@ -326,7 +338,8 @@ class StatsLine(Static):
text.append(" · ", style="#3a3f49")
text.append(f"план {done}/{len(session.todos)}", style="#7f8490")
text.append(" · ", style="#3a3f49")
text.append(f"{format_cost(main['cost'])}", style="#7f8490")
text.append(" · ", style="#3a3f49")
text.append("ctrl+s · ctrl+q", style="#4f545e")
if not compact:
text.append(f"{format_cost(main['cost'])}", style="#7f8490")
text.append(" · ", style="#3a3f49")
text.append("ctrl+s · ctrl+q", style="#4f545e")
self.update(text)
+370
View File
@@ -0,0 +1,370 @@
"""Offline-friendly update checks and safe fast-forward installation."""
from __future__ import annotations
import os
import re
import subprocess
import time
import tomllib
from dataclasses import dataclass
from pathlib import Path
from urllib.parse import urlsplit, urlunsplit
from . import __version__
from .utils import atomic_write_json
DEFAULT_REPO_URL = "https://git.bipfr.ru/KoDer/AiRouter.git"
UPDATE_CACHE = Path.home() / ".cache" / "airouter" / "update.json"
UPDATE_TTL = 6 * 60 * 60
CACHE_TTL = UPDATE_TTL
CACHE_PATH = UPDATE_CACHE
REPO_ROOT = Path(__file__).resolve().parents[1]
_VERSION_RE = re.compile(r"^v?(\d+)\.(\d+)\.(\d+)$")
@dataclass
class UpdateInfo:
current: str
latest: str
available: bool
url: str
checked_at: float
error: str = ""
@dataclass
class UpdateResult:
updated: bool
version: str
restart_required: bool
message: str
def parse_version(value: str) -> tuple[int, int, int] | None:
"""Parse ``vMAJOR.MINOR.PATCH`` (or an unprefixed equivalent)."""
if not isinstance(value, str):
return None
match = _VERSION_RE.fullmatch(value.strip())
if not match:
return None
return tuple(int(part) for part in match.groups())
def _git_env() -> dict[str, str]:
env = os.environ.copy()
for key in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"):
env.pop(key, None)
env.update(
{
"GIT_CONFIG_GLOBAL": os.devnull,
"GIT_CONFIG_NOSYSTEM": "1",
"GIT_TERMINAL_PROMPT": "0",
"GCM_INTERACTIVE": "Never",
"LC_ALL": "C",
}
)
return env
def _run(
command: list[str], *, cwd: Path | None = None, timeout: float = 60
) -> subprocess.CompletedProcess[str] | None:
try:
return subprocess.run(
command,
cwd=str(cwd) if cwd is not None else None,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
timeout=max(0.1, float(timeout)),
env=_git_env(),
check=False,
)
except (OSError, subprocess.TimeoutExpired, ValueError):
return None
def _public_repo_url(repo_url: str) -> str:
"""Remove URL credentials and fragments before displaying/caching a URL."""
value = str(repo_url or "").strip()
scp_match = re.fullmatch(r"[^/@\s]+@([^:\s]+):(.+)", value)
if scp_match:
value = f"https://{scp_match.group(1)}/{scp_match.group(2)}"
try:
parsed = urlsplit(value)
if parsed.scheme in {"http", "https"} and parsed.hostname:
host = parsed.hostname
if ":" in host:
host = f"[{host}]"
if parsed.port:
host += f":{parsed.port}"
return urlunsplit((parsed.scheme, host, parsed.path, "", ""))
except ValueError:
pass
# Local paths are useful in tests and private installs. Query/fragment
# syntax has no meaning for them and is omitted.
return value.split("#", 1)[0].split("?", 1)[0]
def _repo_key(repo_url: str) -> str:
return _public_repo_url(repo_url).removesuffix(".git").rstrip("/")
def _tag_url(repo_url: str, tag: str) -> str:
public = _public_repo_url(repo_url).removesuffix(".git").rstrip("/")
try:
parsed = urlsplit(public)
host = (parsed.hostname or "").lower()
except ValueError:
host = ""
if host == "github.com" or host.endswith(".github.com"):
return f"{public}/releases/tag/{tag}"
if host:
return f"{public}/-/tags/{tag}"
return f"{public}/tags/{tag}"
def _read_cache(repo_key: str, current: str) -> UpdateInfo | None:
try:
import json
raw = json.loads(Path(UPDATE_CACHE).read_text(encoding="utf-8"))
except (OSError, ValueError, TypeError):
return None
if not isinstance(raw, dict):
return None
if raw.get("repo_url") != repo_key or raw.get("current") != current:
return None
checked_at = raw.get("checked_at")
latest = raw.get("latest")
if not isinstance(checked_at, (int, float)) or not isinstance(latest, str):
return None
age = time.time() - float(checked_at)
if age < 0 or age >= UPDATE_TTL or raw.get("error"):
return None
current_version = parse_version(current)
latest_version = parse_version(latest)
if current_version is None or latest_version is None:
return None
return UpdateInfo(
current=current,
latest=latest,
available=latest_version > current_version,
url=str(raw.get("url") or _public_repo_url(repo_key)),
checked_at=float(checked_at),
)
def _write_cache(info: UpdateInfo, repo_key: str) -> None:
try:
atomic_write_json(
Path(UPDATE_CACHE),
{
"repo_url": repo_key,
"current": info.current,
"latest": info.latest,
"url": info.url,
"checked_at": info.checked_at,
"error": "",
},
)
except (OSError, ValueError, TypeError):
pass
def _latest_tag(output: str) -> str | None:
best: tuple[tuple[int, int, int], str] | None = None
for line in output.splitlines():
parts = line.split(None, 1)
if len(parts) != 2:
continue
ref = parts[1].strip()
if not ref.startswith("refs/tags/") or ref.endswith("^{}"):
continue
tag = ref[len("refs/tags/") :]
version = parse_version(tag)
if version is None:
continue
if best is None or version > best[0]:
best = (version, tag)
return best[1] if best else None
def check_for_updates(
force: bool = False,
timeout: float = 8,
repo_url: str = DEFAULT_REPO_URL,
) -> UpdateInfo:
"""Check remote Git tags, caching successful checks for six hours."""
current = str(__version__)
current_version = parse_version(current)
repo_key = _repo_key(repo_url)
if current_version is None:
return UpdateInfo(
current=current,
latest=current,
available=False,
url=_public_repo_url(repo_url),
checked_at=time.time(),
error="Invalid current version",
)
if not force:
cached = _read_cache(repo_key, current)
if cached is not None:
return cached
result = _run(
["git", "ls-remote", "--tags", "--", str(repo_url)],
timeout=timeout,
)
if result is None:
return UpdateInfo(
current=current,
latest=current,
available=False,
url=_public_repo_url(repo_url),
checked_at=time.time(),
error="Update check failed or timed out",
)
if result.returncode != 0:
return UpdateInfo(
current=current,
latest=current,
available=False,
url=_public_repo_url(repo_url),
checked_at=time.time(),
error="Update check failed",
)
latest = _latest_tag(result.stdout or "")
if latest is None:
return UpdateInfo(
current=current,
latest=current,
available=False,
url=_public_repo_url(repo_url),
checked_at=time.time(),
error="No version tags found",
)
latest_version = parse_version(latest)
assert latest_version is not None
info = UpdateInfo(
current=current,
latest=latest,
available=latest_version > current_version,
url=_tag_url(repo_url, latest),
checked_at=time.time(),
)
_write_cache(info, repo_key)
return info
def _project_version(repo: Path) -> str:
try:
with (repo / "pyproject.toml").open("rb") as handle:
data = tomllib.load(handle)
value = data.get("project", {}).get("version")
return str(value) if value else str(__version__)
except (OSError, ValueError, TypeError):
return str(__version__)
def _refuse(message: str) -> UpdateResult:
return UpdateResult(
updated=False,
version=str(__version__),
restart_required=False,
message=message,
)
def install_update(*, repo_url: str = DEFAULT_REPO_URL) -> UpdateResult:
"""Fast-forward a clean Git checkout and optionally refresh its venv.
The function never stashes, resets, checks out over, or discards user work.
"""
repo = Path(REPO_ROOT).expanduser().resolve()
root_result = _run(["git", "rev-parse", "--show-toplevel"], cwd=repo)
if root_result is None or root_result.returncode != 0:
return _refuse("AiRouter is not running from a Git checkout.")
try:
if Path((root_result.stdout or "").strip()).resolve() != repo:
return _refuse("AiRouter source root is not a Git checkout.")
except OSError:
return _refuse("AiRouter source root is not accessible.")
before = _run(["git", "rev-parse", "HEAD"], cwd=repo)
if before is None or before.returncode != 0:
return _refuse("Unable to inspect the Git checkout.")
head_before = (before.stdout or "").strip()
status = _run(
["git", "status", "--porcelain=v1", "--untracked-files=all"], cwd=repo
)
if status is None or status.returncode != 0:
return _refuse("Unable to verify that the working tree is clean.")
if (status.stdout or "").strip():
return _refuse("Working tree is not clean; refusing to update.")
fetched = _run(
["git", "fetch", "--tags", "--prune", "--", str(repo_url)],
cwd=repo,
timeout=120,
)
if fetched is None or fetched.returncode != 0:
return _refuse("Unable to fetch updates.")
ancestor = _run(["git", "merge-base", "--is-ancestor", "HEAD", "FETCH_HEAD"], cwd=repo)
if ancestor is None:
return _refuse("Unable to verify fast-forward history.")
if ancestor.returncode == 1:
return _refuse("Remote history is not fast-forward; refusing to merge.")
if ancestor.returncode != 0:
return _refuse("Unable to verify fast-forward history.")
# Re-check immediately before merging in case another process changed files
# while the fetch was running. ``--ff-only`` remains the final safeguard.
status = _run(
["git", "status", "--porcelain=v1", "--untracked-files=all"], cwd=repo
)
if status is None or status.returncode != 0 or (status.stdout or "").strip():
return _refuse("Working tree changed during update; refusing to merge.")
merged = _run(["git", "merge", "--ff-only", "FETCH_HEAD"], cwd=repo)
if merged is None or merged.returncode != 0:
return _refuse("Fast-forward merge failed; no changes were discarded.")
after = _run(["git", "rev-parse", "HEAD"], cwd=repo)
if after is None or after.returncode != 0:
return _refuse("Update completed but the new revision could not be verified.")
head_after = (after.stdout or "").strip()
if head_after == head_before:
return UpdateResult(
updated=False,
version=_project_version(repo),
restart_required=False,
message="AiRouter is already up to date.",
)
version = _project_version(repo)
pip = repo / ".venv" / "bin" / "pip"
if pip.is_file():
installed = _run([str(pip), "install", "-e", "."], cwd=repo, timeout=300)
if installed is None or installed.returncode != 0:
return UpdateResult(
updated=True,
version=version,
restart_required=True,
message=f"Source updated to {version}, but dependency installation failed; restart AiRouter.",
)
return UpdateResult(
updated=True,
version=version,
restart_required=True,
message=f"Updated to {version}; restart AiRouter to use the new version.",
)
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "airouter"
version = "0.3.0"
version = "0.4.0"
description = "Event-driven AI orchestrator: one lead model supervises isolated coding workers"
readme = "README.md"
requires-python = ">=3.11"
+280
View File
@@ -0,0 +1,280 @@
from __future__ import annotations
import asyncio
import copy
import json
from pathlib import Path
from typing import Any
from airouter.chats import DirectChat
from airouter.config import Config, ProviderProfile
from airouter.remote import RemoteSession
from airouter.service_state import session_to_state
from airouter.session import Session
from airouter.worker import Worker
from .fake import FakeProvider
class FakeClient:
def __init__(self, state: dict[str, Any]) -> None:
self.current = copy.deepcopy(state)
self.calls: list[tuple[str, str, Any]] = []
self.state_calls = 0
self.close_calls = 0
self.handler = None
self.state_queue: list[dict[str, Any]] = []
async def state(self) -> dict[str, Any]:
self.state_calls += 1
if self.state_queue:
return copy.deepcopy(self.state_queue.pop(0))
return copy.deepcopy(self.current)
async def request(self, method: str, path: str, data: Any = None) -> Any:
self.calls.append((method, path, copy.deepcopy(data)))
if self.handler is not None:
result = self.handler(method, path, data)
if asyncio.iscoroutine(result):
result = await result
return result
return {"text": "ok"}
async def aclose(self) -> None:
self.close_calls += 1
def make_session(tmp_path: Path, *, suffix: str = "") -> Session:
config = Config()
config.orchestrator_model = "main-fake"
config.worker_model = "worker-fake"
provider = FakeProvider({})
session = Session.create(
sessions_root=tmp_path / "sessions",
config=config,
provider=provider,
cwd=tmp_path,
)
session.main_messages.append({"role": "user", "content": "hello"})
session.turns = 1
worker = Worker(
id="w1",
name="coder-1",
role=config.roles["coder"],
model="worker-fake",
workspace_path=tmp_path,
task="task",
system_prompt="system",
messages=[{"role": "system", "content": "system"}, {"role": "user", "content": "task"}],
status="done",
result="report",
reported=True,
)
worker.bind(config)
session.workers[worker.id] = worker
session.worker_seq = 1
session.save_all()
return session
def raw_worker(worker_id: str, *, status: str = "done", name: str | None = None) -> dict:
return {
"meta": {
"id": worker_id,
"name": name or f"coder-{worker_id[1:]}",
"role": "coder",
"model": "worker-fake",
"provider_id": "opencode",
"workspace": "/tmp",
"task": "task",
"status": status,
"result": "report",
"reported": False,
},
"messages": [
{"role": "system", "content": "system"},
{"role": "user", "content": "task"},
{"role": "assistant", "content": "report"},
],
}
def test_remote_refresh_preserves_worker_identity_and_never_starts_tasks(tmp_path: Path):
async def scenario():
session = make_session(tmp_path)
state = session_to_state(session)
client = FakeClient(state)
remote = RemoteSession.from_state(client, state)
worker = remote.workers["w1"]
messages = worker.messages
role = worker.role
assert remote.remote is True
assert remote.id == session.id
assert remote.store.dir == session.store.dir
assert remote.worker_tasks == {}
assert remote.provider is None
assert remote.provider_registry is None
assert remote.stats()["workers"] == 1
assert remote.context_tokens() > 0
changed_state = copy.deepcopy(state)
changed_state["workers"][0]["meta"]["name"] = "renamed"
changed_state["workers"][0]["meta"]["status"] = "failed"
changed_state["workers"][0]["messages"].append(
{"role": "assistant", "content": "new message"}
)
changed_state["turns"] = 4
remote.apply_state(changed_state)
assert remote.workers["w1"] is worker
assert worker.messages is messages
assert worker.role is role
assert worker.name == "renamed"
assert worker.status == "failed"
assert worker.messages[-1]["content"] == "new message"
assert remote.turns == 4
assert remote.worker_tasks == {}
await remote.close()
assert client.close_calls == 0
await session.close()
asyncio.run(scenario())
def test_remote_methods_forward_and_refresh(tmp_path: Path):
async def scenario():
session = make_session(tmp_path)
state = session_to_state(session)
client = FakeClient(state)
def handler(method: str, path: str, data: Any):
if path == "/turn":
client.current["turns"] += 1
client.current["main_messages"].append({"role": "assistant", "content": "answer"})
return {"text": "answer"}
if path == "/settings":
client.current["config"]["limits"]["max_workers"] = data["max_workers"]
client.current["config"]["ui"]["animations"] = data["animations"]
return client.current
if path == "/workspace":
client.current["cwd"] = data["path"]
return {"cwd": data["path"]}
if path == "/worker/spawn":
client.current["workers"].append(raw_worker("w2", status="pending", name="new-worker"))
client.current["worker_seq"] = 2
return {"id": "w2", "status": "pending"}
if path == "/worker/retry":
client.current["workers"][0]["meta"]["status"] = "pending"
return {"id": "w1", "status": "pending"}
if path == "/worker/fork":
client.current["workers"].append(raw_worker("w3", name="forked"))
client.current["worker_seq"] = 3
return {"id": "w3"}
if path == "/worker/message":
return {"result": json.dumps({"worker_id": "w1", "status": "running"})}
if path == "/worker/cancel":
return {"result": json.dumps({"worker_id": "w1", "status": "cancelled"})}
if path == "/direct/run":
return {"text": "direct answer"}
if path == "/providers":
return client.current
return {"text": "ok", "ok": True}
client.handler = handler
remote = RemoteSession.from_state(client, state)
assert await remote.run_turn("hello") == "answer"
assert remote.turns == 2
assert await remote.continue_turn() == "ok"
await remote.apply_settings(max_workers=7, animations=False)
assert remote.config.limits.max_workers == 7
assert remote.config.ui.animations is False
assert await remote.change_workspace(tmp_path / "new", create=True) == tmp_path / "new"
spawned = await remote.spawn_worker(task="new", role="coder")
assert spawned.id == "w2"
assert remote.workers["w2"] is spawned
assert remote.worker_tasks == {}
retried = await remote.retry_worker("w1")
assert retried.id == "w1"
assert retried.status == "pending"
message = await remote._tool_message_worker("w1", "follow up")
assert json.loads(message)["status"] == "running"
cancelled = await remote._tool_cancel_worker("w1", "stop")
assert json.loads(cancelled)["status"] == "cancelled"
forked = await remote.fork_worker("w1", remote.workers["w1"].messages)
assert forked.id == "w3"
chat = DirectChat(id="chat-one", title="Direct", model="worker-fake", workspace=tmp_path)
assert await remote.run_direct_chat(chat, lambda *_: None) == "direct answer"
profile = ProviderProfile(
id="local", name="Local", base_url="http://127.0.0.1:9999/v1", token="secret"
)
await remote.update_provider("upsert", profile)
provider_call = [call for call in client.calls if call[1] == "/providers"][-1]
assert provider_call[2]["profile"]["token"] == "secret"
assert remote.config.providers.get("local") is None
await remote.cancel_all_workers()
await remote.interrupt()
await remote.cancel_direct_chat("chat-one")
assert await remote.compact() == "ok"
paths = [call[1] for call in client.calls]
assert "/interrupt" in paths
assert "/direct/cancel" in paths
assert "/worker/message" in paths
assert "/worker/cancel" in paths
assert "/direct/run" in paths
assert remote.worker_tasks == {}
await remote.close()
assert client.close_calls == 0
await session.close()
asyncio.run(scenario())
def test_remote_wait_for_workers_polls_until_terminal(tmp_path: Path):
async def scenario():
session = make_session(tmp_path)
pending = session_to_state(session)
pending["workers"][0]["meta"]["status"] = "running"
pending["workers"][0]["meta"]["reported"] = False
done = copy.deepcopy(pending)
done["workers"][0]["meta"]["status"] = "done"
client = FakeClient(pending)
client.state_queue = [pending, done]
remote = RemoteSession.from_state(client, pending)
result = await remote.wait_for_workers(["w1"], mode="all", timeout=1)
assert result["completed"][0]["id"] == "w1"
assert result["still_running"] == []
assert result["timed_out"] is False
assert remote.workers["w1"].reported is True
assert client.state_calls >= 2
await session.close()
asyncio.run(scenario())
def test_remote_fork_session_returns_new_snapshot(tmp_path: Path):
async def scenario():
session = make_session(tmp_path)
forked_session = make_session(tmp_path)
state = session_to_state(session)
forked_state = session_to_state(forked_session)
client = FakeClient(state)
def handler(method, path, data):
assert path == "/session/fork"
return forked_state
client.handler = handler
remote = RemoteSession.from_state(client, state)
forked = await remote.fork_session(remote.main_messages)
assert isinstance(forked, RemoteSession)
assert forked.id == forked_session.id
assert forked.id != remote.id
assert remote.id == session.id
await session.close()
await forked_session.close()
asyncio.run(scenario())
+542
View File
@@ -0,0 +1,542 @@
from __future__ import annotations
import asyncio
import json
import stat
from pathlib import Path
import httpx
import pytest
from airouter.chats import DirectChat, DirectChatStore
from airouter.config import Config, ProviderProfile, RoleConfig
from airouter.models import ModelInfo
from airouter.provider import Usage
from airouter.service import (
ServiceClient,
ServiceError,
load_service_runtime,
run_service,
)
from airouter.service_state import config_from_data, config_to_data, session_to_state
from airouter.session import Session
from airouter.worker import Worker
from .fake import FakeProvider, turn_text
class FakeRegistry:
def __init__(self, config: Config, provider: FakeProvider) -> None:
self.config = config
self.provider = provider
self.closed = False
def default_client(self, role: str = "worker") -> FakeProvider:
return self.provider
def resolve(self, model: str, provider_id: str | None = None, role: str = "worker"):
if provider_id is None:
prefix, separator, _ = model.partition("/")
if separator and prefix in self.config.providers:
provider_id, model = prefix, model.split("/", 1)[1]
else:
provider_id = (
self.config.orchestrator_provider
if role == "orchestrator"
else self.config.worker_provider
) or self.config.active_provider
return self.provider, provider_id, model
def catalog(self, refresh: bool = False, timeout: float = 6):
return [
ModelInfo(
id="main-fake",
name="Main Fake",
context=12345,
output=678,
tools=False,
reasoning=True,
input_price=0.1,
output_price=0.2,
description="Fake model",
provider="opencode",
provider_name="OpenCode Fake",
)
]
def upsert(self, profile: ProviderProfile) -> None:
self.config.providers[profile.id] = profile
def remove(self, provider_id: str) -> None:
self.config.providers.pop(provider_id, None)
async def aclose(self) -> None:
self.closed = True
await self.provider.aclose()
def make_config() -> Config:
config = Config()
config.orchestrator_model = "main-fake"
config.worker_model = "worker-fake"
config.providers["opencode"].token = "inline-secret-must-not-leak"
config.provider.token = config.providers["opencode"].token
return config
async def wait_for_runtime(path: Path, task: asyncio.Task) -> dict:
for _ in range(200):
runtime = load_service_runtime(path)
if runtime:
return runtime
if task.done():
await task
raise AssertionError("service exited before writing runtime")
await asyncio.sleep(0.01)
raise AssertionError("service runtime was not written")
async def wait_for_state(client: ServiceClient, predicate, timeout: float = 3):
deadline = asyncio.get_running_loop().time() + timeout
while asyncio.get_running_loop().time() < deadline:
state = await client.state()
if predicate(state):
return state
await asyncio.sleep(0.01)
raise AssertionError("service state condition was not met")
def assert_no_inline_tokens(value) -> None:
if isinstance(value, dict):
assert "token" not in value
for item in value.values():
assert_no_inline_tokens(item)
elif isinstance(value, list):
for item in value:
assert_no_inline_tokens(item)
def test_state_roundtrip_preserves_config_and_omits_tokens(tmp_path: Path):
config = make_config()
config.limits.max_workers = 9
config.limits.auto_compact_tokens = 1234
config.ui.show_reasoning = True
config.ui.language = "en"
config.ui.animations = False
config.intelligence["high"] = "high-fake"
config.roles["auditor"] = RoleConfig(
name="auditor", model="audit-fake", description="Audit", prompt_extra="Careful"
)
config.roles["coder"].model = "coder-fake"
config.worker_provider = "opencode"
config.providers["local"] = ProviderProfile(
id="local",
name="Local",
base_url="http://127.0.0.1:9999/v1",
token="another-inline-secret",
enabled=False,
models=["local-fake"],
)
async def scenario():
provider = FakeProvider({})
session = Session.create(
sessions_root=tmp_path / "sessions",
config=config,
provider=provider,
cwd=tmp_path,
)
session.main_messages.extend(
[
{"role": "user", "content": "hello"},
{"role": "assistant", "content": "hi"},
]
)
session.main_usage = Usage(prompt_tokens=3, completion_tokens=2, total_tokens=5)
session.todos = [{"id": "t1", "title": "test", "status": "pending"}]
session.goal = "goal"
session.turns = 2
worker = Worker(
id="w1",
name="auditor-1",
role=config.roles["auditor"],
model="audit-fake",
workspace_path=tmp_path,
task="audit",
system_prompt="system",
messages=[{"role": "system", "content": "system"}, {"role": "user", "content": "audit"}],
status="done",
result="done",
reported=True,
)
worker.bind(config)
session.workers[worker.id] = worker
session.worker_seq = 1
chat = DirectChat(
id="chat-one",
title="Direct",
model="worker-fake",
workspace=tmp_path,
messages=[{"role": "user", "content": "hello"}],
)
DirectChatStore(session.store.dir / "chats.json").save({chat.id: chat})
session.save_all()
state = session_to_state(session)
json.dumps(state, allow_nan=False)
assert state["id"] == session.id
assert state["sessions_root"] == str(session.store.sessions_root)
assert state["worker_seq"] == 1
assert state["direct_chats"][0]["id"] == "chat-one"
assert_no_inline_tokens(state["config"])
assert "inline-secret-must-not-leak" not in json.dumps(state)
assert "another-inline-secret" not in json.dumps(state)
restored = config_from_data(state["config"])
assert config_to_data(restored) == config_to_data(config)
assert restored.providers["local"].token is None
assert restored.roles["auditor"].prompt_extra == "Careful"
assert restored.worker_provider == "opencode"
assert restored.ui.animations is False
await session.close()
asyncio.run(scenario())
def test_service_client_models_are_normalized_without_losing_fields():
async def scenario():
client = ServiceClient("http://127.0.0.1:1", "test-token")
async def fake_request(method, path, *, data=None, timeout=None):
return [
{
"id": "api-model",
"name": "API Model",
"limit": {"context": 99},
"capabilities": {
"tools": {"supported": False},
"reasoning": {"supported": True},
},
"cost": {
"text": {
"input": {"price": 0.3},
"output": {"price": 0.4},
}
},
"provider": "local",
"provider_name": "Local Fake",
},
{
"id": "normalized-model",
"context": 12,
"tools": False,
"reasoning": True,
"provider": "local",
"provider_name": "Local Fake",
},
]
client._request = fake_request
try:
models = await client.models()
assert all(isinstance(model, ModelInfo) for model in models)
assert models[0].context == 99
assert models[0].tools is False
assert models[0].reasoning is True
assert models[0].input_price == 0.3
assert models[1].context == 12
assert models[1].tools is False
assert models[1].provider_name == "Local Fake"
finally:
await client.aclose()
asyncio.run(scenario())
def test_http_service_auth_state_turn_worker_sse_and_direct_chat(
tmp_path: Path, monkeypatch
):
monkeypatch.setattr("airouter.service.GLOBAL_PROVIDERS", tmp_path / "providers.json")
async def scenario():
worker_gate = asyncio.Event()
async def worker_response(messages, count, session_id):
await worker_gate.wait()
return turn_text("worker done")
provider = FakeProvider(
{
"main-fake": [turn_text("main answer")],
"worker-fake": worker_response,
}
)
config = make_config()
registry = FakeRegistry(config, provider)
runtime_path = tmp_path / "runtime" / "service.json"
service_task = asyncio.create_task(
run_service(
config=config,
provider_registry=registry,
sessions_root=tmp_path / "sessions",
cwd=tmp_path,
host="127.0.0.1",
port=0,
runtime_path=runtime_path,
)
)
runtime = await wait_for_runtime(runtime_path, service_task)
client = ServiceClient(runtime["url"], runtime["token"])
try:
health = await client.health()
assert health["ok"] is True
assert health["session_id"] == runtime["session_id"]
assert health["pid"] == runtime["pid"]
assert stat.S_IMODE(runtime_path.stat().st_mode) == 0o600
async with httpx.AsyncClient(trust_env=False) as raw:
assert (await raw.get(runtime["url"] + "/health")).status_code == 200
assert (await raw.get(runtime["url"] + "/state")).status_code == 401
assert (
await raw.get(
runtime["url"] + "/state",
headers={"X-Airouter-Token": "wrong"},
)
).status_code == 401
assert (
await raw.get(
runtime["url"] + "/state",
headers={"X-Airouter-Token": runtime["token"]},
)
).status_code == 200
malformed = await raw.post(
runtime["url"] + "/turn",
content="{",
headers={
"Authorization": f"Bearer {runtime['token']}",
"Content-Type": "application/json",
},
)
assert malformed.status_code == 400
assert "error" in malformed.json()
state = await client.state()
assert state["id"] == runtime["session_id"]
assert state["config"]["providers"]["opencode"].get("token") is None
assert "animations" in state["config"]["ui"]
models = await client.models()
assert isinstance(models[0], ModelInfo)
assert models[0].id == "main-fake"
assert models[0].context == 12345
assert models[0].tools is False
assert models[0].reasoning is True
assert models[0].input_price == 0.1
assert models[0].provider_name == "OpenCode Fake"
settings = await client.request("POST", "/settings", {"animations": False})
assert settings["config"]["ui"]["animations"] is False
assert await client.request("POST", "/turn", {"text": "hello"}) == {
"text": "main answer"
}
state = await wait_for_state(client, lambda item: item["turns"] == 1)
assert state["main_messages"][-1]["content"] == "main answer"
events = client.events()
first_event = asyncio.create_task(anext(events))
await asyncio.sleep(0.05)
spawned = await client.request(
"POST",
"/worker/spawn",
{"task": "do work", "role": "coder", "workspace": "."},
)
assert spawned["id"] == "w1"
event = await asyncio.wait_for(first_event, 2)
assert event["type"] == "worker_spawned"
assert event["worker_id"] == "w1"
assert event["direct"] is False
worker_gate.set()
state = await wait_for_state(
client, lambda item: item["workers"][0]["meta"]["status"] == "done"
)
assert state["workers"][0]["messages"]
await events.aclose()
chat = DirectChat(
id="chat-direct",
title="Direct",
model="worker-fake",
workspace=tmp_path,
messages=[
{"role": "system", "content": "system"},
{"role": "user", "content": "hello"},
],
)
DirectChatStore(client_store_path(runtime, tmp_path)).save({chat.id: chat})
direct_client = ServiceClient(runtime["url"], runtime["token"])
direct_events = direct_client.events()
first_event = asyncio.create_task(anext(direct_events))
await asyncio.sleep(0.05)
answer = await client.request("POST", "/direct/run", {"chat": chat.meta()})
assert answer == {"text": "worker done"}
event = await asyncio.wait_for(first_event, 2)
while not event.get("direct"):
event = await asyncio.wait_for(anext(direct_events), 2)
assert event["type"] == "direct_step"
assert event["direct"] is True
assert event["data"]["chat_id"] == chat.id
state = await client.state()
assert state["direct_chats"][0]["messages"][-1]["content"] == "worker done"
await direct_events.aclose()
await direct_client.aclose()
profile_state = await client.request(
"POST",
"/providers",
{
"action": "upsert",
"profile": {
"id": "local",
"name": "Local",
"base_url": "http://127.0.0.1:9999/v1",
"token": "provider-secret",
},
},
)
assert "provider-secret" not in json.dumps(profile_state)
assert_no_inline_tokens(profile_state["config"])
assert "provider-secret" not in (tmp_path / "providers.json").read_text()
finally:
await client.aclose()
service_task.cancel()
try:
await service_task
except asyncio.CancelledError:
pass
assert not runtime_path.exists()
assert registry.closed
asyncio.run(scenario())
def client_store_path(runtime: dict, tmp_path: Path) -> Path:
# The runtime intentionally exposes the root, not credentials beyond its
# token. Tests use the known ephemeral session layout.
return Path(runtime["sessions_root"]) / runtime["session_id"] / "chats.json"
def test_service_interrupts_main_turn_and_direct_chat(tmp_path: Path):
async def scenario():
main_started = asyncio.Event()
worker_started = asyncio.Event()
direct_started = asyncio.Event()
never = asyncio.Event()
async def main_response(messages, count, session_id):
main_started.set()
await never.wait()
return turn_text("unused")
async def worker_response(messages, count, session_id):
worker_started.set()
await never.wait()
return turn_text("unused")
async def direct_response(messages, count, session_id):
direct_started.set()
await never.wait()
return turn_text("unused")
provider = FakeProvider(
{
"main-fake": main_response,
"worker-fake": worker_response,
"direct-fake": direct_response,
}
)
config = make_config()
registry = FakeRegistry(config, provider)
runtime_path = tmp_path / "service.json"
service_task = asyncio.create_task(
run_service(
config=config,
provider_registry=registry,
sessions_root=tmp_path / "sessions",
cwd=tmp_path,
port=0,
runtime_path=runtime_path,
)
)
runtime = await wait_for_runtime(runtime_path, service_task)
client = ServiceClient(runtime["url"], runtime["token"])
try:
await client.request(
"POST", "/worker/spawn", {"task": "wait", "role": "coder"}
)
await asyncio.wait_for(worker_started.wait(), 2)
turn_task = asyncio.create_task(
client.request("POST", "/turn", {"text": "wait"})
)
await asyncio.wait_for(main_started.wait(), 2)
interrupted = await client.request("POST", "/interrupt")
assert interrupted == {"ok": True, "interrupted": True}
with pytest.raises(ServiceError):
await asyncio.wait_for(turn_task, 2)
state = await client.state()
assert state["busy"] is False
assert state["workers"][0]["meta"]["status"] == "cancelled"
chat = DirectChat(
id="chat-wait",
title="Wait",
model="direct-fake",
workspace=tmp_path,
messages=[
{"role": "system", "content": "system"},
{"role": "user", "content": "wait"},
],
)
DirectChatStore(client_store_path(runtime, tmp_path)).save({chat.id: chat})
direct_task = asyncio.create_task(
client.request("POST", "/direct/run", {"chat": chat.meta()})
)
await asyncio.wait_for(direct_started.wait(), 2)
cancelled = await client.request(
"POST", "/direct/cancel", {"chat_id": chat.id}
)
assert cancelled == {"ok": True, "cancelled": 1}
with pytest.raises(ServiceError):
await asyncio.wait_for(direct_task, 2)
assert (await client.health())["ok"] is True
finally:
await client.aclose()
service_task.cancel()
try:
await service_task
except asyncio.CancelledError:
pass
assert not runtime_path.exists()
asyncio.run(scenario())
def test_service_rejects_non_loopback_host(tmp_path: Path):
async def scenario():
provider = FakeProvider({})
config = make_config()
with_error = False
try:
await run_service(
config=config,
provider_registry=FakeRegistry(config, provider),
sessions_root=tmp_path / "sessions",
cwd=tmp_path,
host="0.0.0.0",
port=0,
runtime_path=tmp_path / "service.json",
)
except ValueError as exc:
with_error = "loopback" in str(exc)
assert with_error
assert not (tmp_path / "service.json").exists()
asyncio.run(scenario())
+147
View File
@@ -0,0 +1,147 @@
from __future__ import annotations
import asyncio
import json
from pathlib import Path
from airouter.config import Config
from airouter.service import ServiceClient, run_service
from airouter.tui.app import AirouterApp
from .fake import FakeProvider, turn_text
class FakeRegistry:
def __init__(self, provider: FakeProvider) -> None:
self.provider = provider
def default_client(self, role: str = "worker"):
return self.provider
def resolve(self, model: str, provider_id=None, role: str = "worker"):
return self.provider, provider_id or "opencode", model
def catalog(self, refresh: bool = False, timeout: float = 6):
return []
async def aclose(self) -> None:
await self.provider.aclose()
async def wait_runtime(path: Path) -> dict:
for _ in range(100):
if path.is_file():
raw = json.loads(path.read_text())
if raw.get("url"):
return raw
await asyncio.sleep(0.05)
raise AssertionError("service runtime was not written")
def test_tui_attaches_to_service_and_worker_chat_stays_synchronized(tmp_path: Path):
async def scenario():
config = Config()
config.orchestrator_model = "main-fake"
config.worker_model = "worker-fake"
config.intelligence = {"low": "worker-fake", "medium": "worker-fake", "high": "worker-fake"}
provider = FakeProvider(
{"worker-fake": [turn_text("first report"), turn_text("follow-up report")]}
)
registry = FakeRegistry(provider)
runtime_path = tmp_path / "runtime.json"
sessions_root = tmp_path / ".airouter" / "sessions"
service_task = asyncio.create_task(
run_service(
config=config,
provider_registry=registry,
sessions_root=sessions_root,
cwd=tmp_path,
port=0,
runtime_path=runtime_path,
)
)
runtime = await wait_runtime(runtime_path)
client = ServiceClient(runtime["url"], runtime["token"])
app = AirouterApp(
config=config,
provider=None,
sessions_root=sessions_root,
cwd=tmp_path,
service_client=client,
)
try:
async with app.run_test(size=(130, 42)) as pilot:
for _ in range(60):
await pilot.pause(0.05)
if app._ui_ready:
break
assert app._ui_ready
assert app.session is not None and app.session.remote
await client.request(
"POST",
"/worker/spawn",
{"task": "first task", "role": "coder", "workspace": str(tmp_path)},
)
for _ in range(60):
await pilot.pause(0.05)
worker = app.session.workers.get("w1")
if worker and worker.status == "done" and "w1" in app._worker_panes:
break
assert app.session.workers["w1"].status == "done"
await app.open_worker("w1")
prompt = app.query_one("#prompt")
prompt.value = "continue"
await pilot.press("enter")
for _ in range(60):
await pilot.pause(0.05)
worker = app.session.workers["w1"]
if worker.followups == 1 and worker.status == "done":
break
assert worker.followups == 1
assert any(m.get("content") == "follow-up report" for m in worker.messages)
await app._new_chat_saved(
{
"title": "Remote direct",
"provider_id": "opencode",
"model": "worker-fake",
"workspace": str(tmp_path),
}
)
chat_id = app._active_chat
await pilot.pause()
prompt.focus()
prompt.value = "direct hello"
await pilot.press("enter")
for _ in range(60):
await pilot.pause(0.05)
if chat_id not in app._chat_tasks:
break
assert any(
message.get("role") == "assistant"
for message in app.direct_chats[chat_id].messages
)
await app._submit("/delete 1")
state = await client.state()
remote_chat = next(
item for item in state["direct_chats"] if item["id"] == chat_id
)
assert not any(
message.get("content") == "direct hello"
for message in remote_chat["messages"]
)
await app.action_quit_app()
await pilot.pause()
assert not service_task.done()
health_client = ServiceClient(runtime["url"], runtime["token"])
try:
assert (await health_client.health())["ok"]
finally:
await health_client.aclose()
finally:
service_task.cancel()
await asyncio.gather(service_task, return_exceptions=True)
await client.aclose()
asyncio.run(asyncio.wait_for(scenario(), timeout=30))
+21
View File
@@ -97,6 +97,27 @@ def test_direct_chat_fork_delete_and_close(tmp_path: Path):
asyncio.run(asyncio.wait_for(scenario(), timeout=25))
def test_narrow_layout_hides_sidebar_and_shortens_controls(tmp_path: Path):
async def scenario():
app = make_app(tmp_path)
async with app.run_test(size=(80, 24)) as pilot:
await wait_ready(app, pilot)
assert app.has_class("narrow")
assert app.has_class("compact")
assert not app.query_one("#sidebar").display
assert app.query_one("#send").label == "▶"
assert app.query_one("#stop").label == "■"
assert not app.query_one("#message-fork").display
topbar = app.query_one("#topbar")
for child in topbar.children:
if getattr(child, "display", False):
assert child.region.x >= topbar.region.x
assert child.region.right <= topbar.region.right
await app.action_quit_app()
asyncio.run(asyncio.wait_for(scenario(), timeout=25))
def test_direct_chat_retry_after_error(tmp_path: Path):
calls = 0
+188
View File
@@ -0,0 +1,188 @@
from __future__ import annotations
import os
import subprocess
from pathlib import Path
import pytest
from airouter import update
@pytest.fixture(autouse=True)
def isolate_home(tmp_path: Path, monkeypatch):
home = tmp_path / "home"
home.mkdir()
monkeypatch.setenv("HOME", str(home))
monkeypatch.setenv("XDG_CONFIG_HOME", str(home / ".config"))
monkeypatch.setattr(update, "UPDATE_CACHE", tmp_path / "update-cache.json")
monkeypatch.setattr(update, "__version__", "0.3.0")
def git(repo: Path, *args: str) -> str:
env = os.environ.copy()
env.update(
{
"GIT_CONFIG_GLOBAL": os.devnull,
"GIT_CONFIG_NOSYSTEM": "1",
"GIT_TERMINAL_PROMPT": "0",
}
)
result = subprocess.run(
["git", *args],
cwd=repo,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
check=True,
)
return result.stdout.strip()
def init_repo(path: Path) -> None:
path.mkdir(parents=True)
git(path, "init")
git(path, "config", "user.email", "tests@example.invalid")
git(path, "config", "user.name", "AiRouter Tests")
(path / "tracked.txt").write_text("one\n", encoding="utf-8")
git(path, "add", "tracked.txt")
git(path, "commit", "-m", "initial")
def test_parse_version_is_numeric_and_strict():
assert update.parse_version("v1.2.3") == (1, 2, 3)
assert update.parse_version("10.20.30") == (10, 20, 30)
assert update.parse_version("v1.2.3-rc1") is None
assert update.parse_version("1.2") is None
assert update.parse_version("v1.x.3") is None
def test_check_for_updates_parses_tags_and_uses_cache(tmp_path: Path, monkeypatch):
calls = []
def fake_run(command, **kwargs):
calls.append((command, kwargs))
output = (
"aaa\trefs/tags/v0.9.0\n"
"bbb\trefs/tags/v0.3.1\n"
"ccc\trefs/tags/v0.3.1^{}\n"
"ddd\trefs/tags/not-a-version\n"
"eee\trefs/tags/v0.10.0\n"
"fff\trefs/tags/v0.10.0^{}"
)
return subprocess.CompletedProcess(command, 0, stdout=output, stderr="")
monkeypatch.setattr(update.subprocess, "run", fake_run)
first = update.check_for_updates(repo_url="https://example.invalid/org/repo.git")
assert first.current == "0.3.0"
assert first.latest == "v0.10.0"
assert first.available is True
assert first.error == ""
assert first.url.endswith("/-/tags/v0.10.0")
assert len(calls) == 1
assert calls[0][0][-1] == "https://example.invalid/org/repo.git"
second = update.check_for_updates(repo_url="https://example.invalid/org/repo.git")
assert second == first
assert len(calls) == 1
update.check_for_updates(
force=True, repo_url="https://example.invalid/org/repo.git"
)
assert len(calls) == 2
assert update.UPDATE_CACHE.is_file()
def test_update_check_timeout_is_unavailable_and_not_cached(tmp_path: Path, monkeypatch):
def fake_run(command, **kwargs):
raise subprocess.TimeoutExpired(command, kwargs.get("timeout"))
monkeypatch.setattr(update.subprocess, "run", fake_run)
info = update.check_for_updates(force=True)
assert info.available is False
assert info.latest == info.current
assert "timed out" in info.error
assert not update.UPDATE_CACHE.exists()
def test_update_urls_never_include_credentials(monkeypatch):
monkeypatch.setattr(
update.subprocess,
"run",
lambda command, **kwargs: subprocess.CompletedProcess(
command, 0, stdout="aaa\trefs/tags/v0.3.1\n", stderr=""
),
)
info = update.check_for_updates(
force=True,
repo_url="https://user:password@example.invalid/org/repo.git?secret=yes",
)
assert "user" not in info.url
assert "password" not in info.url
assert "secret" not in info.url
assert "password" not in update.UPDATE_CACHE.read_text(encoding="utf-8")
def test_install_update_refuses_dirty_tree_without_fetching(
tmp_path: Path, monkeypatch
):
repo = tmp_path / "repo"
init_repo(repo)
monkeypatch.setattr(update, "REPO_ROOT", repo)
before = git(repo, "rev-parse", "HEAD")
(repo / "untracked.txt").write_text("keep me\n", encoding="utf-8")
result = update.install_update(repo_url=str(tmp_path / "missing-remote"))
assert result.updated is False
assert result.restart_required is False
assert "clean" in result.message.lower()
assert git(repo, "rev-parse", "HEAD") == before
assert (repo / "untracked.txt").read_text(encoding="utf-8") == "keep me\n"
def test_install_update_clean_checkout_with_no_changes(tmp_path: Path, monkeypatch):
repo = tmp_path / "repo"
init_repo(repo)
monkeypatch.setattr(update, "REPO_ROOT", repo)
result = update.install_update(repo_url=str(repo))
assert result.updated is False
assert result.restart_required is False
assert "up to date" in result.message.lower()
def test_install_update_fast_forwards_clean_checkout(tmp_path: Path, monkeypatch):
remote = tmp_path / "remote.git"
remote.mkdir()
git(remote, "init", "--bare")
seed = tmp_path / "seed"
init_repo(seed)
(seed / "pyproject.toml").write_text(
'[project]\nname = "airouter"\nversion = "0.3.0"\n', encoding="utf-8"
)
git(seed, "add", "pyproject.toml")
git(seed, "commit", "-m", "version")
branch = git(seed, "branch", "--show-current")
git(seed, "remote", "add", "origin", str(remote))
git(seed, "push", "-u", "origin", branch)
work = tmp_path / "work"
git(tmp_path, "clone", str(remote), str(work))
git(work, "config", "user.email", "tests@example.invalid")
git(work, "config", "user.name", "AiRouter Tests")
before = git(work, "rev-parse", "HEAD")
(seed / "pyproject.toml").write_text(
'[project]\nname = "airouter"\nversion = "0.3.1"\n', encoding="utf-8"
)
git(seed, "add", "pyproject.toml")
git(seed, "commit", "-m", "new version")
git(seed, "push", "origin", branch)
monkeypatch.setattr(update, "REPO_ROOT", work)
result = update.install_update(repo_url=str(remote))
assert result.updated is True
assert result.version == "0.3.1"
assert result.restart_required is True
assert git(work, "rev-parse", "HEAD") != before
assert 'version = "0.3.1"' in (work / "pyproject.toml").read_text(encoding="utf-8")