394 lines
14 KiB
Python
394 lines
14 KiB
Python
"""Standalone coding chats, persistence and conversation helpers.
|
|
|
|
Worker and lead conversations remain in their session files. A direct chat is
|
|
an independent, forkable conversation with its own provider, model and
|
|
workspace; it uses the same file/shell tools as a worker.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
import time
|
|
from dataclasses import dataclass, field
|
|
from pathlib import Path
|
|
from typing import TYPE_CHECKING, Any, Callable
|
|
from uuid import uuid4
|
|
|
|
from .config import Config
|
|
from .provider import ProviderError, Usage
|
|
from .tools import WORKER_TOOLS
|
|
from .utils import (
|
|
atomic_write_json,
|
|
compact_args,
|
|
now,
|
|
parse_int,
|
|
read_json,
|
|
redact_secrets,
|
|
truncate,
|
|
)
|
|
from .workspace import ToolError, Workspace
|
|
|
|
if TYPE_CHECKING:
|
|
from .session import Session
|
|
|
|
|
|
ChatEmitter = Callable[[str, dict[str, Any]], None]
|
|
|
|
|
|
def new_chat_id() -> str:
|
|
return f"chat-{uuid4().hex[:10]}"
|
|
|
|
|
|
def visible_message_indices(messages: list[dict[str, Any]]) -> list[int]:
|
|
"""Message indexes that can safely be selected, deleted or branched.
|
|
|
|
System messages, tool payloads and assistant tool-call envelopes are an
|
|
implementation detail of the agent loop and must stay paired.
|
|
"""
|
|
|
|
return [
|
|
index
|
|
for index, message in enumerate(messages)
|
|
if message.get("role") in {"user", "assistant"}
|
|
and isinstance(message.get("content"), str)
|
|
and message["content"].strip()
|
|
and not message.get("tool_calls")
|
|
]
|
|
|
|
|
|
def last_visible_index(messages: list[dict[str, Any]]) -> int | None:
|
|
indexes = visible_message_indices(messages)
|
|
return indexes[-1] if indexes else None
|
|
|
|
|
|
def repair_direct_messages(messages: list[dict[str, Any]]) -> None:
|
|
"""Close dangling direct-chat tool calls before retrying a failed turn."""
|
|
|
|
last_assistant: dict[str, Any] | None = None
|
|
answered: set[str] = set()
|
|
for message in messages:
|
|
if message.get("role") == "assistant":
|
|
last_assistant = message
|
|
answered = set()
|
|
elif message.get("role") == "tool":
|
|
answered.add(str(message.get("tool_call_id")))
|
|
if not last_assistant or not last_assistant.get("tool_calls"):
|
|
return
|
|
for call in last_assistant["tool_calls"]:
|
|
if str(call.get("id")) not in answered:
|
|
messages.append(
|
|
{
|
|
"role": "tool",
|
|
"tool_call_id": str(call.get("id")),
|
|
"content": "ERROR: выполнение инструмента было прервано.",
|
|
}
|
|
)
|
|
|
|
|
|
def delete_visible_message(
|
|
messages: list[dict[str, Any]], index: int
|
|
) -> list[dict[str, Any]]:
|
|
"""Delete one plain message without breaking a tool-call sequence."""
|
|
|
|
if index not in visible_message_indices(messages):
|
|
raise ValueError("Это сообщение нельзя удалить: оно является частью tool-call.")
|
|
updated = list(messages)
|
|
del updated[index]
|
|
return updated
|
|
|
|
|
|
@dataclass
|
|
class DirectChat:
|
|
id: str
|
|
title: str
|
|
provider_id: str = ""
|
|
model: str = ""
|
|
workspace: Path = field(default_factory=Path.cwd)
|
|
messages: list[dict[str, Any]] = field(default_factory=list)
|
|
usage: Usage = field(default_factory=Usage)
|
|
created_at: float = field(default_factory=now)
|
|
updated_at: float = field(default_factory=now)
|
|
parent_id: str = ""
|
|
fork_from: int | None = None
|
|
error: str = ""
|
|
|
|
def __post_init__(self) -> None:
|
|
self.workspace = Path(self.workspace).expanduser().resolve()
|
|
|
|
@property
|
|
def tab_id(self) -> str:
|
|
return f"chat-tab-{self.id}"
|
|
|
|
@property
|
|
def pane_id(self) -> str:
|
|
return f"chat-pane-{self.id}"
|
|
|
|
def initialize(self, config: Config, model: str, provider_id: str = "") -> None:
|
|
self.model = model
|
|
self.provider_id = provider_id
|
|
if self.messages:
|
|
return
|
|
self.messages = [
|
|
{
|
|
"role": "system",
|
|
"content": build_direct_chat_prompt(config, self.workspace, self.title),
|
|
}
|
|
]
|
|
|
|
def meta(self) -> dict[str, Any]:
|
|
return {
|
|
"id": self.id,
|
|
"title": self.title,
|
|
"provider_id": self.provider_id,
|
|
"model": self.model,
|
|
"workspace": str(self.workspace),
|
|
"messages": self.messages,
|
|
"usage": self.usage.to_dict(),
|
|
"created_at": self.created_at,
|
|
"updated_at": self.updated_at,
|
|
"parent_id": self.parent_id,
|
|
"fork_from": self.fork_from,
|
|
"error": self.error,
|
|
}
|
|
|
|
@classmethod
|
|
def from_meta(cls, raw: dict[str, Any]) -> DirectChat:
|
|
messages = raw.get("messages")
|
|
return cls(
|
|
id=str(raw.get("id") or new_chat_id()),
|
|
title=str(raw.get("title") or "Новый чат"),
|
|
provider_id=str(raw.get("provider_id") or ""),
|
|
model=str(raw.get("model") or ""),
|
|
workspace=Path(raw.get("workspace") or Path.cwd()),
|
|
messages=list(messages) if isinstance(messages, list) else [],
|
|
usage=Usage.from_dict(raw.get("usage")),
|
|
created_at=float(raw.get("created_at") or now()),
|
|
updated_at=float(raw.get("updated_at") or now()),
|
|
parent_id=str(raw.get("parent_id") or ""),
|
|
fork_from=raw.get("fork_from"),
|
|
error=str(raw.get("error") or ""),
|
|
)
|
|
|
|
|
|
class DirectChatStore:
|
|
def __init__(self, path: Path) -> None:
|
|
self.path = path
|
|
|
|
def load(self) -> dict[str, DirectChat]:
|
|
raw = read_json(self.path, [])
|
|
if not isinstance(raw, list):
|
|
return {}
|
|
chats: dict[str, DirectChat] = {}
|
|
for item in raw:
|
|
if not isinstance(item, dict) or not item.get("id"):
|
|
continue
|
|
chat = DirectChat.from_meta(item)
|
|
chats[chat.id] = chat
|
|
return chats
|
|
|
|
def save(self, chats: dict[str, DirectChat]) -> None:
|
|
ordered = sorted(chats.values(), key=lambda chat: chat.updated_at)
|
|
atomic_write_json(self.path, [chat.meta() for chat in ordered])
|
|
|
|
def delete(self, chats: dict[str, DirectChat], chat_id: str) -> None:
|
|
chats.pop(chat_id, None)
|
|
self.save(chats)
|
|
|
|
|
|
def build_direct_chat_prompt(config: Config, workspace: Path, title: str) -> str:
|
|
return f"""You are a direct coding assistant in AiRouter.
|
|
|
|
Conversation: {title}
|
|
Workspace: {workspace}
|
|
You work independently from the lead orchestrator. You may read, write and edit
|
|
files inside the workspace and run shell commands there. Never modify or delete
|
|
an `.airouter` session directory.
|
|
|
|
Inspect before editing, make minimal coherent changes, and verify important work
|
|
with tests, builds, linters or a focused smoke test. Ask a clarifying question
|
|
only when it is genuinely necessary. Answer in the user's language. Be concise,
|
|
state failed checks honestly, and never invent file changes or command results.
|
|
"""
|
|
|
|
|
|
async def run_direct_chat(
|
|
session: Session,
|
|
chat: DirectChat,
|
|
*,
|
|
user_text: str | None = None,
|
|
emit: ChatEmitter,
|
|
max_steps: int | None = None,
|
|
) -> str:
|
|
"""Run one direct-chat turn, including any file/shell tool calls."""
|
|
|
|
if not chat.model:
|
|
raise ToolError("Для чата не выбрана модель")
|
|
if user_text:
|
|
chat.messages.append({"role": "user", "content": user_text.strip()})
|
|
repair_direct_messages(chat.messages)
|
|
if not any(message.get("role") == "user" for message in chat.messages):
|
|
raise ToolError("Нет пользовательского сообщения для ответа")
|
|
if not user_text and chat.messages[-1].get("role") == "assistant" and not chat.messages[-1].get("tool_calls"):
|
|
raise ToolError("Нет сообщения для продолжения")
|
|
|
|
workspace = Workspace(chat.workspace, session.config.limits)
|
|
provider, routed_model = session.resolve_provider(
|
|
chat.model, provider_id=chat.provider_id, role="worker"
|
|
)
|
|
steps = max(1, int(max_steps or session.config.limits.max_worker_steps))
|
|
chat.error = ""
|
|
chat.updated_at = now()
|
|
|
|
try:
|
|
for step in range(1, steps + 1):
|
|
emit("direct_step", {"chat_id": chat.id, "step": step})
|
|
|
|
def on_text(delta: str) -> None:
|
|
emit("direct_text_delta", {"chat_id": chat.id, "delta": delta})
|
|
|
|
def on_reasoning(delta: str) -> None:
|
|
emit(
|
|
"direct_reasoning_delta",
|
|
{"chat_id": chat.id, "delta": delta},
|
|
)
|
|
|
|
turn = await provider.stream_chat(
|
|
model=routed_model,
|
|
messages=chat.messages,
|
|
tools=WORKER_TOOLS,
|
|
session_id=f"ses_airouter_{session.id}_{chat.id}",
|
|
on_text=on_text,
|
|
on_reasoning=on_reasoning,
|
|
)
|
|
chat.usage.add(turn.usage)
|
|
chat.messages.append(turn.as_message())
|
|
chat.updated_at = now()
|
|
emit(
|
|
"direct_assistant_message",
|
|
{
|
|
"chat_id": chat.id,
|
|
"content": turn.content,
|
|
"tool_calls": len(turn.tool_calls),
|
|
},
|
|
)
|
|
if not turn.tool_calls:
|
|
answer = turn.content.strip() or "(пустой ответ)"
|
|
if turn.finish_reason == "length":
|
|
answer += "\n\n[Ответ обрезан по лимиту токенов.]"
|
|
emit(
|
|
"direct_done",
|
|
{"chat_id": chat.id, "text": answer, "finish_reason": turn.finish_reason},
|
|
)
|
|
return answer
|
|
|
|
for call in turn.tool_calls:
|
|
args: dict[str, Any] = {}
|
|
try:
|
|
args = call.parsed_args()
|
|
except (json.JSONDecodeError, ValueError) as exc:
|
|
result = f"ERROR: некорректные JSON-аргументы: {exc}"
|
|
ok = False
|
|
else:
|
|
emit(
|
|
"direct_tool_call",
|
|
{
|
|
"chat_id": chat.id,
|
|
"name": call.name,
|
|
"args": compact_args(args),
|
|
},
|
|
)
|
|
started = time.monotonic()
|
|
try:
|
|
result = await _execute_direct_tool(
|
|
workspace, session.config, call.name, args
|
|
)
|
|
ok = True
|
|
except ToolError as exc:
|
|
result = f"ERROR: {exc}"
|
|
ok = False
|
|
except Exception as exc: # pragma: no cover - defensive
|
|
result = f"ERROR: {type(exc).__name__}: {exc}"
|
|
ok = False
|
|
emit(
|
|
"direct_tool_result",
|
|
{
|
|
"chat_id": chat.id,
|
|
"name": call.name,
|
|
"ok": ok,
|
|
"summary": truncate(result, 240),
|
|
"duration": round(time.monotonic() - started, 2),
|
|
},
|
|
)
|
|
result = truncate(
|
|
redact_secrets(result), session.config.limits.tool_output_max_chars
|
|
)
|
|
chat.messages.append(
|
|
{"role": "tool", "tool_call_id": call.id, "content": result}
|
|
)
|
|
|
|
answer = "Достигнут лимит шагов. Отправьте уточнение или повторите попытку."
|
|
chat.error = answer
|
|
emit("direct_error", {"chat_id": chat.id, "text": answer})
|
|
return answer
|
|
except asyncio.CancelledError:
|
|
chat.updated_at = now()
|
|
emit("direct_cancelled", {"chat_id": chat.id})
|
|
raise
|
|
except ProviderError as exc:
|
|
chat.error = redact_secrets(exc.display())
|
|
chat.updated_at = now()
|
|
emit("direct_error", {"chat_id": chat.id, "text": chat.error})
|
|
raise
|
|
except Exception as exc:
|
|
chat.error = redact_secrets(f"{type(exc).__name__}: {exc}")
|
|
chat.updated_at = now()
|
|
emit("direct_error", {"chat_id": chat.id, "text": chat.error})
|
|
raise
|
|
finally:
|
|
chat.updated_at = now()
|
|
|
|
|
|
async def _execute_direct_tool(
|
|
workspace: Workspace, config: Config, name: str, args: dict[str, Any]
|
|
) -> str:
|
|
if name == "read_file":
|
|
return await workspace.read_file(
|
|
str(args.get("path", ".")),
|
|
parse_int(args.get("offset"), 1, 1),
|
|
parse_int(args.get("limit"), 400, 1, 2000),
|
|
)
|
|
if name == "write_file":
|
|
return await workspace.write_file(
|
|
str(args.get("path", "")), str(args.get("content", ""))
|
|
)
|
|
if name == "edit_file":
|
|
return await workspace.edit_file(
|
|
str(args.get("path", "")),
|
|
str(args.get("old_string", "")),
|
|
str(args.get("new_string", "")),
|
|
bool(args.get("replace_all", False)),
|
|
)
|
|
if name == "list_files":
|
|
return await workspace.list_files(
|
|
str(args.get("path", ".")),
|
|
parse_int(args.get("depth"), 2, 1, 6),
|
|
parse_int(args.get("limit"), 300, 1, 1000),
|
|
)
|
|
if name == "search_files":
|
|
return await workspace.search_files(
|
|
str(args.get("pattern", "")),
|
|
str(args.get("path", ".")),
|
|
str(args["glob"]) if args.get("glob") else None,
|
|
parse_int(args.get("max_results"), 80, 1, 500),
|
|
)
|
|
if name == "bash":
|
|
command = str(args.get("command", "")).strip()
|
|
if not command:
|
|
raise ToolError("Пустая команда")
|
|
return await workspace.bash(
|
|
command,
|
|
parse_int(args.get("timeout_seconds"), config.limits.bash_timeout, 1, 3600),
|
|
)
|
|
raise ToolError(f"Неизвестный инструмент: {name}")
|