522 lines
20 KiB
Python
522 lines
20 KiB
Python
"""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 ""
|