anixcode 0.8.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- anixcode/__init__.py +3 -0
- anixcode/__main__.py +4 -0
- anixcode/agent.py +358 -0
- anixcode/airpc.py +59 -0
- anixcode/checkpoints.py +87 -0
- anixcode/cli.py +185 -0
- anixcode/commands.py +218 -0
- anixcode/compaction.py +91 -0
- anixcode/danger.py +85 -0
- anixcode/i18n.py +67 -0
- anixcode/i18n_en.py +293 -0
- anixcode/llm.py +258 -0
- anixcode/mentions.py +116 -0
- anixcode/projects.py +142 -0
- anixcode/prompts.py +64 -0
- anixcode/providers.py +67 -0
- anixcode/settings.py +105 -0
- anixcode/storage.py +129 -0
- anixcode/tools/__init__.py +15 -0
- anixcode/tools/base.py +203 -0
- anixcode/tools/files.py +248 -0
- anixcode/tools/search.py +107 -0
- anixcode/tools/shell.py +86 -0
- anixcode/tui/__init__.py +0 -0
- anixcode/tui/anim.py +242 -0
- anixcode/tui/app.py +812 -0
- anixcode/tui/app.tcss +281 -0
- anixcode/tui/screens.py +556 -0
- anixcode/tui/widgets.py +374 -0
- anixcode-0.8.0.dist-info/METADATA +241 -0
- anixcode-0.8.0.dist-info/RECORD +35 -0
- anixcode-0.8.0.dist-info/WHEEL +5 -0
- anixcode-0.8.0.dist-info/entry_points.txt +2 -0
- anixcode-0.8.0.dist-info/licenses/LICENSE +21 -0
- anixcode-0.8.0.dist-info/top_level.txt +1 -0
anixcode/tui/app.py
ADDED
|
@@ -0,0 +1,812 @@
|
|
|
1
|
+
"""The terminal app."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from ..i18n import tr
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import time
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from rich.text import Text
|
|
11
|
+
from textual import on, work
|
|
12
|
+
from textual.app import App, ComposeResult
|
|
13
|
+
from textual.binding import Binding
|
|
14
|
+
from textual.containers import Horizontal, Vertical, VerticalScroll
|
|
15
|
+
from textual.screen import ModalScreen
|
|
16
|
+
from textual.widgets import OptionList, Static, TextArea
|
|
17
|
+
|
|
18
|
+
from .. import __version__, commands, projects, providers
|
|
19
|
+
from ..agent import (
|
|
20
|
+
Agent, AgentError, Attached, Compacted, Compacting, PermissionRequest, StepFinished, ToolFinished, ToolStarted,
|
|
21
|
+
)
|
|
22
|
+
from ..danger import check_command
|
|
23
|
+
from ..mentions import index_files, rank_paths
|
|
24
|
+
from ..tools import ToolContext, default_tools
|
|
25
|
+
from ..airpc import AirpcReporter
|
|
26
|
+
from ..llm import LLMClient, LLMError, ReasoningDelta, Retrying, TextDelta
|
|
27
|
+
from ..settings import Credentials, Settings, config_dir, load_auth, save_settings
|
|
28
|
+
from ..storage import Session, Store
|
|
29
|
+
from ..tools import ToolResult
|
|
30
|
+
from .anim import THEME_LABELS, ActivityIndicator, AnimatedLogo, Gradient, make_themes, palette
|
|
31
|
+
from .screens import HelpScreen, ProjectScreen, SessionsScreen, SetupScreen, ThemeScreen
|
|
32
|
+
from .widgets import (
|
|
33
|
+
AssistantMessage, Chip, ErrorMessage, MentionList, Notice, PermissionBar, PromptInput, ReasoningBlock, ToolCard,
|
|
34
|
+
UserMessage,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
def _tokens(n: int) -> str:
|
|
38
|
+
return f"{n / 1000:.1f}k" if n >= 1000 else str(n)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Brand(Static):
|
|
42
|
+
"""Header: logo + project path. Click to switch project."""
|
|
43
|
+
|
|
44
|
+
def on_click(self) -> None:
|
|
45
|
+
self.app.action_projects()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class AnixApp(App):
|
|
49
|
+
CSS_PATH = "app.tcss"
|
|
50
|
+
TITLE = "ANIX Code"
|
|
51
|
+
ENABLE_COMMAND_PALETTE = False # Ctrl+P is our project picker
|
|
52
|
+
BINDINGS = [
|
|
53
|
+
Binding("tab", "toggle_mode", "Build/Plan", priority=True, show=False),
|
|
54
|
+
Binding("shift+tab", "toggle_mode", "Build/Plan", priority=True, show=False),
|
|
55
|
+
Binding("escape", "interrupt", tr("Стоп"), show=False),
|
|
56
|
+
Binding("ctrl+o", "connect", tr("Модель"), show=False),
|
|
57
|
+
Binding("f2", "toggle_access", tr("Полный доступ"), priority=True, show=False),
|
|
58
|
+
Binding("ctrl+p", "projects", tr("Проект"), priority=True, show=False),
|
|
59
|
+
Binding("ctrl+n", "new_session", tr("Новая"), show=False),
|
|
60
|
+
Binding("ctrl+s", "sessions", tr("Сессии"), show=False),
|
|
61
|
+
Binding("ctrl+t", "cycle_theme", tr("Тема"), show=False),
|
|
62
|
+
Binding("f1", "help", tr("Помощь"), show=False),
|
|
63
|
+
Binding("ctrl+q", "quit", tr("Выход"), priority=True, show=False),
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
def __init__(self, root: Path, settings: Settings, store: Store, base: Path | None = None,
|
|
67
|
+
pick_project: bool = False) -> None:
|
|
68
|
+
super().__init__()
|
|
69
|
+
self._pick_project = pick_project
|
|
70
|
+
self._file_index: list[str] | None = None
|
|
71
|
+
self._pending: tuple[PermissionRequest, asyncio.Future] | None = None
|
|
72
|
+
self._cards: dict[str, ToolCard] = {}
|
|
73
|
+
self._index_time = 0.0
|
|
74
|
+
self._indexing = False
|
|
75
|
+
self.project_root = root.resolve()
|
|
76
|
+
self.settings = settings
|
|
77
|
+
self.store = store
|
|
78
|
+
self.config_base = base
|
|
79
|
+
self.auth = load_auth(base)
|
|
80
|
+
self.session: Session = store.create(str(self.project_root), settings.model)
|
|
81
|
+
self.agent: Agent | None = None
|
|
82
|
+
self._llm_client: LLMClient | None = None
|
|
83
|
+
self._agent_busy = False
|
|
84
|
+
self._agent_mode = "build"
|
|
85
|
+
|
|
86
|
+
# -- layout --------------------------------------------------------------------
|
|
87
|
+
def compose(self) -> ComposeResult:
|
|
88
|
+
with Horizontal(id="header"):
|
|
89
|
+
yield Brand(id="brand")
|
|
90
|
+
yield Static(id="mode")
|
|
91
|
+
with VerticalScroll(id="chat"):
|
|
92
|
+
yield self._welcome()
|
|
93
|
+
with Vertical(id="composer"):
|
|
94
|
+
yield ActivityIndicator(id="activity")
|
|
95
|
+
yield PermissionBar(self._resolve_permission, id="permission")
|
|
96
|
+
yield MentionList(id="mentions")
|
|
97
|
+
yield PromptInput(id="prompt")
|
|
98
|
+
with Horizontal(id="statusbar"):
|
|
99
|
+
yield Static(id="status-model")
|
|
100
|
+
yield Static(id="status-usage")
|
|
101
|
+
yield Chip("", self.action_toggle_access, id="status-access")
|
|
102
|
+
|
|
103
|
+
def _welcome(self) -> Static:
|
|
104
|
+
footer = Text()
|
|
105
|
+
footer.append(f"v{__version__}\n\n", style="dim")
|
|
106
|
+
footer.append(tr("Опишите задачу: агент сам прочитает код, внесёт правки и запустит команды.\n"), style="dim")
|
|
107
|
+
footer.append(tr("Tab: Build/Plan · Ctrl+O: модель · F1: все клавиши"), style="dim")
|
|
108
|
+
return AnimatedLogo(footer, animate=self.settings.animations, id="welcome")
|
|
109
|
+
|
|
110
|
+
def on_mount(self) -> None:
|
|
111
|
+
for theme in make_themes():
|
|
112
|
+
try:
|
|
113
|
+
self.register_theme(theme)
|
|
114
|
+
except Exception:
|
|
115
|
+
pass
|
|
116
|
+
self._apply_theme(self.settings.theme)
|
|
117
|
+
self.set_interval(1 / 10, self._pulse_brand)
|
|
118
|
+
self._build_agent()
|
|
119
|
+
self._refresh_bars()
|
|
120
|
+
prompt = self.query_one(PromptInput)
|
|
121
|
+
prompt.mention_list = self.query_one(MentionList)
|
|
122
|
+
prompt.focus()
|
|
123
|
+
self.call_after_refresh(self._warn_if_unsuitable)
|
|
124
|
+
if not self._pick_project:
|
|
125
|
+
self._remember_project()
|
|
126
|
+
if not self.agent:
|
|
127
|
+
self.call_after_refresh(self.action_connect)
|
|
128
|
+
elif self._pick_project:
|
|
129
|
+
self.call_after_refresh(self.action_projects)
|
|
130
|
+
|
|
131
|
+
def _apply_theme(self, name: str) -> None:
|
|
132
|
+
try:
|
|
133
|
+
if name in getattr(self, "available_themes", {}):
|
|
134
|
+
self.theme = name
|
|
135
|
+
except Exception:
|
|
136
|
+
pass
|
|
137
|
+
|
|
138
|
+
# -- agent wiring ----------------------------------------------------------------
|
|
139
|
+
def _build_agent(self) -> None:
|
|
140
|
+
old_mode = self.agent.mode if self.agent else self._agent_mode
|
|
141
|
+
if not self.settings.ready:
|
|
142
|
+
self.agent = None
|
|
143
|
+
return
|
|
144
|
+
p = providers.get(self.settings.provider, self.settings)
|
|
145
|
+
cred = self.auth.get(self.settings.provider, Credentials())
|
|
146
|
+
if self._llm_client is not None:
|
|
147
|
+
asyncio.create_task(self._llm_client.aclose())
|
|
148
|
+
self._llm_client = LLMClient(cred.base_url or p.base_url, cred.api_key)
|
|
149
|
+
self.agent = Agent(self._llm_client, self.settings.model, self.project_root, self.settings, ask=self._ask_permission,
|
|
150
|
+
reporter=AirpcReporter(self.settings.airpc), provider=self.settings.provider)
|
|
151
|
+
self.agent.mode = old_mode
|
|
152
|
+
|
|
153
|
+
async def _ask_permission(self, req: PermissionRequest) -> str:
|
|
154
|
+
"""Inline approval: a line above the prompt, Enter = yes, Esc = no."""
|
|
155
|
+
fut: asyncio.Future[str] = asyncio.get_running_loop().create_future()
|
|
156
|
+
self._pending = (req, fut)
|
|
157
|
+
card = self._cards.get(req.call_id)
|
|
158
|
+
if card is not None:
|
|
159
|
+
card.show_pending(req.preview, req.kind)
|
|
160
|
+
bar = self.query_one(PermissionBar)
|
|
161
|
+
bar.show(req)
|
|
162
|
+
prompt = self.query_one(PromptInput)
|
|
163
|
+
prompt.permission_handler = self._resolve_permission
|
|
164
|
+
prompt.focus()
|
|
165
|
+
indicator = self.query_one(ActivityIndicator)
|
|
166
|
+
indicator.set_phase(tr("Ждёт разрешения: Enter / Esc"), paused=True)
|
|
167
|
+
self._scroll()
|
|
168
|
+
try:
|
|
169
|
+
return await fut
|
|
170
|
+
finally:
|
|
171
|
+
self._pending = None
|
|
172
|
+
prompt.permission_handler = None
|
|
173
|
+
bar.hide()
|
|
174
|
+
indicator.set_phase(tr('Выполняет: {0}', req.title))
|
|
175
|
+
|
|
176
|
+
def _resolve_permission(self, decision: str, feedback: str = "") -> None:
|
|
177
|
+
if self._pending is None:
|
|
178
|
+
return
|
|
179
|
+
req, fut = self._pending
|
|
180
|
+
if decision == "full":
|
|
181
|
+
self._set_full_access(True)
|
|
182
|
+
decision = "once"
|
|
183
|
+
req.feedback = feedback
|
|
184
|
+
if not fut.done():
|
|
185
|
+
fut.set_result(decision)
|
|
186
|
+
|
|
187
|
+
def _set_full_access(self, value: bool) -> None:
|
|
188
|
+
self.settings.full_access = value
|
|
189
|
+
save_settings(self.settings, self.config_base)
|
|
190
|
+
self._refresh_bars()
|
|
191
|
+
self.notify(tr("🔓 Полный доступ: агент правит файлы и запускает команды без вопросов") if value
|
|
192
|
+
else tr("🔒 Агент снова спрашивает разрешение"), timeout=3)
|
|
193
|
+
|
|
194
|
+
def action_toggle_access(self) -> None:
|
|
195
|
+
self._set_full_access(not self.settings.full_access)
|
|
196
|
+
if self.settings.full_access and self._pending is not None:
|
|
197
|
+
self._resolve_permission("once")
|
|
198
|
+
|
|
199
|
+
def _refresh_bars(self) -> None:
|
|
200
|
+
self._pulse_brand(force=True)
|
|
201
|
+
mode = self.agent.mode if self.agent else self._agent_mode
|
|
202
|
+
badge = self.query_one("#mode", Static)
|
|
203
|
+
badge.update("PLAN" if mode == "plan" else "BUILD")
|
|
204
|
+
badge.set_class(mode == "plan", "plan")
|
|
205
|
+
if self.settings.ready:
|
|
206
|
+
model = Text(self.settings.model, style="bold")
|
|
207
|
+
else:
|
|
208
|
+
model = Text(tr("модель не подключена · ctrl+o"), style="dim")
|
|
209
|
+
s = self.session
|
|
210
|
+
usage = Text(f"↑{_tokens(s.tokens_in)} ↓{_tokens(s.tokens_out)}", style="dim")
|
|
211
|
+
if self.agent and s.messages:
|
|
212
|
+
pct = int(self.agent.context_usage(s) * 100)
|
|
213
|
+
usage.append(tr(" контекст "), style="dim")
|
|
214
|
+
usage.append(f"{pct}%", style="bold red" if pct >= 80 else "bold yellow" if pct >= 60 else "dim")
|
|
215
|
+
self.query_one("#status-model", Static).update(model)
|
|
216
|
+
self.query_one("#status-usage", Static).update(usage)
|
|
217
|
+
access = self.query_one("#status-access", Chip)
|
|
218
|
+
if self.settings.full_access:
|
|
219
|
+
access.update(Text(tr("🔓 полный доступ"), style="bold yellow"))
|
|
220
|
+
else:
|
|
221
|
+
access.update(Text(tr("🔒 спрашивать"), style="dim"))
|
|
222
|
+
|
|
223
|
+
def _pulse_brand(self, force: bool = False) -> None:
|
|
224
|
+
"""Header diamond: theme color at rest, flowing gradient while the agent works."""
|
|
225
|
+
if not (force or self._agent_busy):
|
|
226
|
+
return
|
|
227
|
+
if self._agent_busy and self.settings.animations:
|
|
228
|
+
color = Gradient(palette(self)).at(asyncio.get_running_loop().time() * 0.4).hex
|
|
229
|
+
else:
|
|
230
|
+
color = palette(self)[0]
|
|
231
|
+
brand = Text.assemble(("◆ ", f"bold {color}"), ("ANIX Code", "bold"), (" " + self._short_root(), "dim"))
|
|
232
|
+
self.query_one("#brand", Static).update(brand)
|
|
233
|
+
|
|
234
|
+
def _short_root(self) -> str:
|
|
235
|
+
home = Path.home()
|
|
236
|
+
try:
|
|
237
|
+
rel = self.project_root.relative_to(home).as_posix()
|
|
238
|
+
except ValueError:
|
|
239
|
+
return str(self.project_root)
|
|
240
|
+
return "~" if rel in ("", ".") else f"~/{rel}"
|
|
241
|
+
|
|
242
|
+
def _scroll(self) -> None:
|
|
243
|
+
self.query_one("#chat", VerticalScroll).scroll_end(animate=False)
|
|
244
|
+
|
|
245
|
+
# -- input -----------------------------------------------------------------------
|
|
246
|
+
# -- @file suggestions ------------------------------------------------------------
|
|
247
|
+
@on(TextArea.Changed, "#prompt")
|
|
248
|
+
@on(TextArea.SelectionChanged, "#prompt")
|
|
249
|
+
def _prompt_changed(self) -> None:
|
|
250
|
+
self._update_mentions()
|
|
251
|
+
|
|
252
|
+
def _commands(self) -> list[commands.Command]:
|
|
253
|
+
return commands.all_commands(self.project_root, self.config_base or config_dir())
|
|
254
|
+
|
|
255
|
+
def _update_mentions(self) -> None:
|
|
256
|
+
prompt, ml = self.query_one(PromptInput), self.query_one(MentionList)
|
|
257
|
+
query = prompt.suggestion_query()
|
|
258
|
+
if query is None:
|
|
259
|
+
ml.hide()
|
|
260
|
+
return
|
|
261
|
+
kind, prefix = query
|
|
262
|
+
if kind == "command":
|
|
263
|
+
found = commands.suggest(prefix, self._commands())
|
|
264
|
+
if not found:
|
|
265
|
+
ml.hide()
|
|
266
|
+
return
|
|
267
|
+
labels = []
|
|
268
|
+
for c in found:
|
|
269
|
+
label = Text.assemble((f"/{c.name}", "bold"), " ", (c.description, "dim"))
|
|
270
|
+
if c.args_hint:
|
|
271
|
+
label.append(f" {c.args_hint}", style="dim italic")
|
|
272
|
+
if c.source != "builtin":
|
|
273
|
+
label.append(tr(" · свой"), style="dim")
|
|
274
|
+
labels.append(label)
|
|
275
|
+
ml.show([c.name for c in found], labels, {c.name: c.takes_args for c in found})
|
|
276
|
+
return
|
|
277
|
+
if self._file_index is None or time.monotonic() - self._index_time > 30:
|
|
278
|
+
self._refresh_index()
|
|
279
|
+
if self._file_index is None:
|
|
280
|
+
return
|
|
281
|
+
items = rank_paths(self._file_index, prefix)
|
|
282
|
+
if items:
|
|
283
|
+
ml.show(items)
|
|
284
|
+
else:
|
|
285
|
+
ml.hide()
|
|
286
|
+
|
|
287
|
+
@work(exclusive=True, group="index")
|
|
288
|
+
async def _refresh_index(self) -> None:
|
|
289
|
+
if self._indexing:
|
|
290
|
+
return
|
|
291
|
+
self._indexing = True
|
|
292
|
+
try:
|
|
293
|
+
root = self.project_root
|
|
294
|
+
index = await asyncio.to_thread(index_files, root)
|
|
295
|
+
if root == self.project_root:
|
|
296
|
+
self._file_index, self._index_time = index, time.monotonic()
|
|
297
|
+
finally:
|
|
298
|
+
self._indexing = False
|
|
299
|
+
self._update_mentions()
|
|
300
|
+
|
|
301
|
+
@on(OptionList.OptionSelected, "#mentions")
|
|
302
|
+
def _mention_clicked(self, event: OptionList.OptionSelected) -> None:
|
|
303
|
+
ml = self.query_one(MentionList)
|
|
304
|
+
prompt = self.query_one(PromptInput)
|
|
305
|
+
prompt.accept_suggestion(ml.mention_items[event.option_index])
|
|
306
|
+
prompt.focus()
|
|
307
|
+
|
|
308
|
+
@on(PromptInput.Submitted)
|
|
309
|
+
def _submitted(self, event: PromptInput.Submitted) -> None:
|
|
310
|
+
self.query_one(MentionList).hide()
|
|
311
|
+
text = event.text
|
|
312
|
+
if text.startswith("/") and len(text) > 1 and not text.startswith("//"):
|
|
313
|
+
self._command(text)
|
|
314
|
+
return
|
|
315
|
+
if self._agent_busy:
|
|
316
|
+
self.notify(tr("Агент ещё работает. Esc — остановить."), severity="warning")
|
|
317
|
+
return
|
|
318
|
+
if text.startswith("!") and len(text) > 1:
|
|
319
|
+
self.run_shell(text[1:].strip()) # like Claude Code: run it yourself, the agent sees the output
|
|
320
|
+
return
|
|
321
|
+
if text.startswith("#") and not text.startswith("##") and len(text) > 1:
|
|
322
|
+
self._remember_note(text[1:].strip())
|
|
323
|
+
return
|
|
324
|
+
if not self.agent:
|
|
325
|
+
self.action_connect()
|
|
326
|
+
return
|
|
327
|
+
self.run_agent(text)
|
|
328
|
+
|
|
329
|
+
def _command(self, text: str) -> None:
|
|
330
|
+
name, args = commands.parse(text)
|
|
331
|
+
cmd = commands.find(name, self._commands())
|
|
332
|
+
if cmd is None:
|
|
333
|
+
self.notify(tr('Нет команды /{0}. Наберите / и посмотрите список.', name), severity="warning")
|
|
334
|
+
return
|
|
335
|
+
if cmd.template is not None:
|
|
336
|
+
if not self.agent:
|
|
337
|
+
self.action_connect()
|
|
338
|
+
return
|
|
339
|
+
if self._agent_busy:
|
|
340
|
+
self.notify(tr("Агент ещё работает. Esc — остановить."), severity="warning")
|
|
341
|
+
return
|
|
342
|
+
if cmd.takes_args and not args and "$ARGUMENTS" in cmd.template and cmd.args_hint.startswith("<"):
|
|
343
|
+
self.notify(f"/{name} {cmd.args_hint}", severity="warning")
|
|
344
|
+
return
|
|
345
|
+
if self.agent.mode == "plan" and name in ("init", "commit", "test", "fix"):
|
|
346
|
+
self.action_toggle_mode() # these need Build mode
|
|
347
|
+
display = f"/{name}" + (f" {args}" if args else "") + f" · {cmd.description}"
|
|
348
|
+
self.run_agent(commands.render(cmd.template, args), display=display)
|
|
349
|
+
return
|
|
350
|
+
actions = {
|
|
351
|
+
"help": self.action_help, "new": self.action_new_session, "sessions": self.action_sessions,
|
|
352
|
+
"undo": self.action_undo, "redo": self.action_redo, "compact": self.action_compact,
|
|
353
|
+
"connect": self.action_connect, "project": self.action_projects, "theme": self.action_cycle_theme,
|
|
354
|
+
"mode": self.action_toggle_mode, "permissions": self.action_toggle_access,
|
|
355
|
+
"status": self.action_status, "export": self.action_export, "doctor": self.action_doctor,
|
|
356
|
+
"language": self.action_language,
|
|
357
|
+
"exit": self.exit,
|
|
358
|
+
}
|
|
359
|
+
actions[cmd.action]()
|
|
360
|
+
|
|
361
|
+
def _remember_note(self, note: str) -> None:
|
|
362
|
+
async def go() -> None:
|
|
363
|
+
path = commands.append_memory(self.project_root, note)
|
|
364
|
+
await self.query_one("#chat", VerticalScroll).mount(
|
|
365
|
+
Notice(tr('📝 Записал в {0}: {1} (агент учтёт это в следующих ответах)', path.name, note)))
|
|
366
|
+
self._scroll()
|
|
367
|
+
|
|
368
|
+
self.run_worker(go())
|
|
369
|
+
|
|
370
|
+
@work(exclusive=True, group="agent")
|
|
371
|
+
async def run_shell(self, command: str) -> None:
|
|
372
|
+
chat = self.query_one("#chat", VerticalScroll)
|
|
373
|
+
for w in chat.query("#welcome"):
|
|
374
|
+
await w.remove()
|
|
375
|
+
await chat.mount(UserMessage(f"! {command}"))
|
|
376
|
+
risk = check_command(command, self.project_root)
|
|
377
|
+
card = ToolCard("bash", command, "exec", full_title=command, dangerous=risk.dangerous)
|
|
378
|
+
await chat.mount(card)
|
|
379
|
+
self._agent_busy = True
|
|
380
|
+
self._refresh_bars()
|
|
381
|
+
self._scroll()
|
|
382
|
+
try:
|
|
383
|
+
ctx = self.agent.ctx if self.agent else ToolContext(self.project_root)
|
|
384
|
+
result = await default_tools()["bash"].run({"command": command}, ctx)
|
|
385
|
+
card.finish(result)
|
|
386
|
+
card.add_class("open")
|
|
387
|
+
self.session.add({"role": "user", "content": (
|
|
388
|
+
f"[I ran a command myself in the project folder]\n$ {command}\n\n{result.output[:8000]}")})
|
|
389
|
+
finally:
|
|
390
|
+
self._agent_busy = False
|
|
391
|
+
self._refresh_bars()
|
|
392
|
+
self._scroll()
|
|
393
|
+
|
|
394
|
+
# -- the agent run -------------------------------------------------------------
|
|
395
|
+
@work(exclusive=True, group="agent")
|
|
396
|
+
async def run_agent(self, text: str, display: str | None = None) -> None:
|
|
397
|
+
assert self.agent is not None
|
|
398
|
+
chat = self.query_one("#chat", VerticalScroll)
|
|
399
|
+
for w in chat.query("#welcome"):
|
|
400
|
+
await w.remove()
|
|
401
|
+
await chat.mount(UserMessage(display or text))
|
|
402
|
+
self._agent_busy = True
|
|
403
|
+
self._refresh_bars()
|
|
404
|
+
self._scroll()
|
|
405
|
+
assistant: AssistantMessage | None = None
|
|
406
|
+
reasoning: ReasoningBlock | None = None
|
|
407
|
+
cards = self._cards
|
|
408
|
+
cards.clear()
|
|
409
|
+
indicator = self.query_one(ActivityIndicator)
|
|
410
|
+
indicator.motion = self.settings.animations
|
|
411
|
+
indicator.start()
|
|
412
|
+
try:
|
|
413
|
+
async for ev in self.agent.run(self.session, text):
|
|
414
|
+
if isinstance(ev, Attached):
|
|
415
|
+
await chat.mount(Notice(tr("📎 Прикреплено: ") + ", ".join(ev.paths)))
|
|
416
|
+
if isinstance(ev, (ReasoningDelta, TextDelta)):
|
|
417
|
+
indicator.chars += len(ev.text)
|
|
418
|
+
if isinstance(ev, ReasoningDelta):
|
|
419
|
+
if reasoning is None:
|
|
420
|
+
indicator.set_phase(tr("Размышляет"))
|
|
421
|
+
reasoning = ReasoningBlock()
|
|
422
|
+
await chat.mount(reasoning)
|
|
423
|
+
reasoning.append(ev.text)
|
|
424
|
+
elif isinstance(ev, TextDelta):
|
|
425
|
+
if reasoning is not None:
|
|
426
|
+
reasoning.finish()
|
|
427
|
+
reasoning = None
|
|
428
|
+
if assistant is None:
|
|
429
|
+
indicator.set_phase(tr("Пишет ответ"))
|
|
430
|
+
assistant = AssistantMessage()
|
|
431
|
+
await chat.mount(assistant)
|
|
432
|
+
assistant.append_text(ev.text)
|
|
433
|
+
elif isinstance(ev, ToolStarted):
|
|
434
|
+
if assistant is not None:
|
|
435
|
+
await assistant.finish()
|
|
436
|
+
assistant = None
|
|
437
|
+
if reasoning is not None:
|
|
438
|
+
reasoning.finish()
|
|
439
|
+
reasoning = None
|
|
440
|
+
indicator.set_phase(tr('Выполняет: {0}', ev.title))
|
|
441
|
+
full = str(self.agent.last_args.get("command", "")) if ev.tool == "bash" else ""
|
|
442
|
+
card = ToolCard(ev.tool, ev.title, ev.kind, full_title=full, dangerous=ev.dangerous)
|
|
443
|
+
cards[ev.call_id] = card
|
|
444
|
+
await chat.mount(card)
|
|
445
|
+
elif isinstance(ev, ToolFinished):
|
|
446
|
+
if ev.call_id in cards:
|
|
447
|
+
cards[ev.call_id].finish(ev.result)
|
|
448
|
+
indicator.set_phase(tr("Думает"))
|
|
449
|
+
elif isinstance(ev, StepFinished):
|
|
450
|
+
self._refresh_bars()
|
|
451
|
+
elif isinstance(ev, AgentError):
|
|
452
|
+
await chat.mount(ErrorMessage(ev.message))
|
|
453
|
+
elif isinstance(ev, Retrying):
|
|
454
|
+
indicator.set_phase(tr('Повтор {0}/{1} через {2:.0f}с: {3}', ev.attempt, ev.max_attempts, ev.delay, ev.reason))
|
|
455
|
+
elif isinstance(ev, Compacting):
|
|
456
|
+
if assistant is not None:
|
|
457
|
+
await assistant.finish()
|
|
458
|
+
assistant = None
|
|
459
|
+
indicator.set_phase(tr("Сжимает историю"))
|
|
460
|
+
elif isinstance(ev, Compacted):
|
|
461
|
+
await chat.mount(Notice(self._compacted_text(ev)))
|
|
462
|
+
indicator.set_phase(tr("Думает"))
|
|
463
|
+
self._refresh_bars()
|
|
464
|
+
self._scroll()
|
|
465
|
+
except asyncio.CancelledError:
|
|
466
|
+
await chat.mount(Notice(tr("⏹ Остановлено")))
|
|
467
|
+
finally:
|
|
468
|
+
indicator.stop()
|
|
469
|
+
if assistant is not None:
|
|
470
|
+
await assistant.finish()
|
|
471
|
+
if reasoning is not None:
|
|
472
|
+
reasoning.finish()
|
|
473
|
+
self._agent_busy = False
|
|
474
|
+
self._refresh_bars()
|
|
475
|
+
self._scroll()
|
|
476
|
+
|
|
477
|
+
# -- actions ---------------------------------------------------------------------
|
|
478
|
+
def _warn_if_unsuitable(self) -> None:
|
|
479
|
+
if not projects.is_unsuitable(self.project_root):
|
|
480
|
+
return
|
|
481
|
+
|
|
482
|
+
async def go() -> None:
|
|
483
|
+
await self.query_one("#chat", VerticalScroll).mount(Notice(Text(
|
|
484
|
+
tr('⚠ Агент сейчас работает в {0}: это не папка проекта, а весь профиль или диск. Поиск будет медленным, а правки могут задеть что угодно. Выберите проект: Ctrl+P.', self.project_root),
|
|
485
|
+
style="yellow")))
|
|
486
|
+
|
|
487
|
+
self.run_worker(go())
|
|
488
|
+
|
|
489
|
+
def _remember_project(self) -> None:
|
|
490
|
+
self.settings.recent_projects = projects.remember(self.settings.recent_projects, self.project_root)
|
|
491
|
+
save_settings(self.settings, self.config_base)
|
|
492
|
+
|
|
493
|
+
def action_projects(self) -> None:
|
|
494
|
+
if isinstance(self.screen, ProjectScreen):
|
|
495
|
+
return
|
|
496
|
+
if self._agent_busy:
|
|
497
|
+
self.notify(tr("Сначала остановите агента (Esc)."), severity="warning")
|
|
498
|
+
return
|
|
499
|
+
|
|
500
|
+
def done(path: str | None) -> None:
|
|
501
|
+
if path:
|
|
502
|
+
self.run_worker(self._switch_project(Path(path)))
|
|
503
|
+
else:
|
|
504
|
+
self.query_one(PromptInput).focus()
|
|
505
|
+
|
|
506
|
+
self.push_screen(ProjectScreen(self.project_root, self.settings.recent_projects), done)
|
|
507
|
+
|
|
508
|
+
async def _switch_project(self, path: Path) -> None:
|
|
509
|
+
await self._reset_chat()
|
|
510
|
+
self.project_root = path.resolve()
|
|
511
|
+
self._pick_project = False
|
|
512
|
+
self._file_index = None
|
|
513
|
+
self._remember_project()
|
|
514
|
+
self.session = self.store.create(str(self.project_root), self.settings.model)
|
|
515
|
+
self._build_agent()
|
|
516
|
+
await self.query_one("#chat", VerticalScroll).mount(self._welcome())
|
|
517
|
+
self._refresh_bars()
|
|
518
|
+
self._warn_if_unsuitable()
|
|
519
|
+
git = " (git)" if projects.is_git_repo(self.project_root) else ""
|
|
520
|
+
self.notify(tr('Проект: {0}{1}', self.project_root, git), timeout=3)
|
|
521
|
+
self.query_one(PromptInput).focus()
|
|
522
|
+
|
|
523
|
+
@staticmethod
|
|
524
|
+
def _compacted_text(ev: Compacted) -> str:
|
|
525
|
+
how = tr("старые шаги свёрнуты в сводку") if ev.summarized else tr("убраны старые выводы команд")
|
|
526
|
+
return tr('🗜 История сжата: ~{0} → ~{1} токенов ({2})', _tokens(ev.before), _tokens(ev.after), how)
|
|
527
|
+
|
|
528
|
+
def action_undo(self) -> None:
|
|
529
|
+
if self._agent_busy or not self.agent:
|
|
530
|
+
self.notify(tr("Сначала остановите агента (Esc)."), severity="warning")
|
|
531
|
+
return
|
|
532
|
+
|
|
533
|
+
async def go() -> None:
|
|
534
|
+
result = self.agent.undo(self.session)
|
|
535
|
+
chat = self.query_one("#chat", VerticalScroll)
|
|
536
|
+
if result is None:
|
|
537
|
+
await chat.mount(Notice(tr("↶ Откатывать нечего: агент не правил файлы в этой сессии (команды в терминале не откатываются).")))
|
|
538
|
+
else:
|
|
539
|
+
parts = [tr('восстановлено: {0}', ', '.join(result.restored)) if result.restored else "",
|
|
540
|
+
tr('удалены созданные: {0}', ', '.join(result.deleted)) if result.deleted else ""]
|
|
541
|
+
await chat.mount(Notice(tr("↶ Правки последнего ответа откачены, ") + "; ".join(p for p in parts if p)
|
|
542
|
+
+ tr(". Команды в терминале не откатываются.")))
|
|
543
|
+
self._scroll()
|
|
544
|
+
|
|
545
|
+
self.run_worker(go())
|
|
546
|
+
|
|
547
|
+
def action_redo(self) -> None:
|
|
548
|
+
if self._agent_busy or not self.agent:
|
|
549
|
+
self.notify(tr("Сначала остановите агента (Esc)."), severity="warning")
|
|
550
|
+
return
|
|
551
|
+
|
|
552
|
+
async def go() -> None:
|
|
553
|
+
result = self.agent.redo(self.session)
|
|
554
|
+
chat = self.query_one("#chat", VerticalScroll)
|
|
555
|
+
if result is None:
|
|
556
|
+
await chat.mount(Notice(tr("↷ Возвращать нечего: сначала /undo.")))
|
|
557
|
+
else:
|
|
558
|
+
await chat.mount(Notice(tr("↷ Откаченные правки возвращены: ") + ", ".join(result.restored + result.deleted)))
|
|
559
|
+
self._scroll()
|
|
560
|
+
|
|
561
|
+
self.run_worker(go())
|
|
562
|
+
|
|
563
|
+
def action_language(self) -> None:
|
|
564
|
+
from ..i18n import LANG, LANGUAGES
|
|
565
|
+
|
|
566
|
+
new = "en" if (self.settings.language or LANG) == "ru" else "ru"
|
|
567
|
+
self.settings.language = new
|
|
568
|
+
save_settings(self.settings, self.config_base)
|
|
569
|
+
self.notify(tr("Язык: {0}. Перезапустите ANIX Code, чтобы применить.", LANGUAGES[new]), timeout=6)
|
|
570
|
+
|
|
571
|
+
def action_status(self) -> None:
|
|
572
|
+
s = self.session
|
|
573
|
+
git = "git" if projects.is_git_repo(self.project_root) else tr("не git")
|
|
574
|
+
lines = Text()
|
|
575
|
+
lines.append(tr("ℹ Сводка\n"), style="bold")
|
|
576
|
+
rows = [
|
|
577
|
+
(tr("Проект"), f"{self.project_root} ({git})"),
|
|
578
|
+
(tr("Модель"), f"{providers.get(self.settings.provider, self.settings).name} · {self.settings.model}"
|
|
579
|
+
if self.settings.ready else tr("не подключена (/connect)")),
|
|
580
|
+
(tr("Режим"), ("PLAN" if self.agent and self.agent.mode == "plan" else "BUILD") + " · "
|
|
581
|
+
+ (tr("полный доступ") if self.settings.full_access else tr("спрашивать разрешение"))),
|
|
582
|
+
(tr("Токены"), f"↑{_tokens(s.tokens_in)} ↓{_tokens(s.tokens_out)}"),
|
|
583
|
+
]
|
|
584
|
+
if self.agent:
|
|
585
|
+
rows.append((tr("Контекст"), tr('{0}% из ~{1}', int(self.agent.context_usage(s) * 100), _tokens(self.agent.window))))
|
|
586
|
+
custom = [c for c in self._commands() if c.source != "builtin"]
|
|
587
|
+
rows += [(tr("Сессия"), tr('{0} · сообщений: {1}', s.title, len(s.messages))),
|
|
588
|
+
("AGENTS.md", tr("есть") if (self.project_root / "AGENTS.md").exists() else tr("нет (/init создаст)")),
|
|
589
|
+
(tr("Свои команды"), ", ".join("/" + c.name for c in custom) or tr("нет"))]
|
|
590
|
+
for k, v in rows:
|
|
591
|
+
lines.append(f" {k:<13}", style="dim")
|
|
592
|
+
lines.append(v + "\n")
|
|
593
|
+
|
|
594
|
+
async def go() -> None:
|
|
595
|
+
await self.query_one("#chat", VerticalScroll).mount(Notice(lines))
|
|
596
|
+
self._scroll()
|
|
597
|
+
|
|
598
|
+
self.run_worker(go())
|
|
599
|
+
|
|
600
|
+
def action_export(self) -> None:
|
|
601
|
+
from datetime import datetime
|
|
602
|
+
|
|
603
|
+
s = self.session
|
|
604
|
+
if not s.messages:
|
|
605
|
+
self.notify(tr("Сессия пока пустая."), severity="warning")
|
|
606
|
+
return
|
|
607
|
+
folder = (self.config_base or config_dir()) / "exports"
|
|
608
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
609
|
+
slug = "".join(ch if ch.isalnum() else "-" for ch in s.title.lower())[:40].strip("-") or "session"
|
|
610
|
+
path = folder / f"{datetime.now():%Y-%m-%d_%H-%M}_{slug}.md"
|
|
611
|
+
path.write_text(commands.session_markdown(s.title, self.settings.model, s.messages), encoding="utf-8")
|
|
612
|
+
|
|
613
|
+
async def go() -> None:
|
|
614
|
+
await self.query_one("#chat", VerticalScroll).mount(Notice(tr('💾 Сессия сохранена: {0}', path)))
|
|
615
|
+
self._scroll()
|
|
616
|
+
|
|
617
|
+
self.run_worker(go())
|
|
618
|
+
|
|
619
|
+
def action_doctor(self) -> None:
|
|
620
|
+
async def go() -> None:
|
|
621
|
+
import platform
|
|
622
|
+
import shutil
|
|
623
|
+
import subprocess
|
|
624
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
625
|
+
|
|
626
|
+
from ..airpc import AirpcReporter
|
|
627
|
+
|
|
628
|
+
out = Text(tr("🩺 Проверка\n"), style="bold")
|
|
629
|
+
|
|
630
|
+
def row(ok: bool | None, name: str, detail: str) -> None:
|
|
631
|
+
mark, style = ("✓", "green") if ok else ("✗", "red") if ok is False else ("–", "yellow")
|
|
632
|
+
out.append(f" {mark} ", style=style)
|
|
633
|
+
out.append(f"{name:<12}", style="bold")
|
|
634
|
+
out.append(detail + "\n", style="dim")
|
|
635
|
+
|
|
636
|
+
row(True, "Python", platform.python_version())
|
|
637
|
+
for pkg in ("textual", "httpx"):
|
|
638
|
+
try:
|
|
639
|
+
row(True, pkg, version(pkg))
|
|
640
|
+
except PackageNotFoundError:
|
|
641
|
+
row(False, pkg, tr("не установлен: pip install -e ."))
|
|
642
|
+
git = shutil.which("git")
|
|
643
|
+
if git:
|
|
644
|
+
ver = await asyncio.to_thread(subprocess.run, [git, "--version"], capture_output=True, text=True)
|
|
645
|
+
row(True, "git", ver.stdout.strip())
|
|
646
|
+
else:
|
|
647
|
+
row(False, "git", tr("не найден: https://git-scm.com (нужен для /commit, /review, клонирования)"))
|
|
648
|
+
row(True if shutil.which("rg") else None, "ripgrep",
|
|
649
|
+
tr("есть, поиск быстрый") if shutil.which("rg") else tr("нет (необязательно, ускоряет поиск)"))
|
|
650
|
+
row(projects.is_git_repo(self.project_root), tr("проект"),
|
|
651
|
+
f"{self.project_root}" + ("" if projects.is_git_repo(self.project_root) else tr(" — не git-репозиторий")))
|
|
652
|
+
row((self.project_root / "AGENTS.md").exists() or None, "AGENTS.md",
|
|
653
|
+
tr("есть") if (self.project_root / "AGENTS.md").exists() else tr("нет, создайте: /init"))
|
|
654
|
+
if self._llm_client is not None:
|
|
655
|
+
try:
|
|
656
|
+
models = await asyncio.wait_for(self._llm_client.list_models(), timeout=20)
|
|
657
|
+
row(True, tr("модель"), tr('{0} · сервер отвечает, моделей: {1}', self.settings.model, len(models)))
|
|
658
|
+
except (LLMError, asyncio.TimeoutError) as e:
|
|
659
|
+
row(False, tr("модель"), str(e).splitlines()[0] if str(e) else tr("нет ответа"))
|
|
660
|
+
else:
|
|
661
|
+
row(False, tr("модель"), tr("не подключена: /connect"))
|
|
662
|
+
row(True if AirpcReporter(self.settings.airpc).active else None, "AI-RPC",
|
|
663
|
+
tr("найден, статус уйдёт в Discord") if AirpcReporter(self.settings.airpc).active else tr("не запущен (необязательно)"))
|
|
664
|
+
await self.query_one("#chat", VerticalScroll).mount(Notice(out))
|
|
665
|
+
self._scroll()
|
|
666
|
+
|
|
667
|
+
self.run_worker(go())
|
|
668
|
+
|
|
669
|
+
def action_compact(self) -> None:
|
|
670
|
+
if self._agent_busy or not self.agent:
|
|
671
|
+
self.notify(tr("Сначала остановите агента (Esc)."), severity="warning")
|
|
672
|
+
return
|
|
673
|
+
|
|
674
|
+
async def go() -> None:
|
|
675
|
+
chat = self.query_one("#chat", VerticalScroll)
|
|
676
|
+
indicator = self.query_one(ActivityIndicator)
|
|
677
|
+
indicator.start()
|
|
678
|
+
indicator.set_phase(tr("Сжимает историю"))
|
|
679
|
+
try:
|
|
680
|
+
result = await self.agent.compact(self.session, force=True)
|
|
681
|
+
except LLMError as e:
|
|
682
|
+
await chat.mount(ErrorMessage(str(e)))
|
|
683
|
+
return
|
|
684
|
+
finally:
|
|
685
|
+
indicator.stop()
|
|
686
|
+
await chat.mount(Notice(self._compacted_text(result) if result else tr("🗜 Сжимать пока нечего.")))
|
|
687
|
+
self._refresh_bars()
|
|
688
|
+
self._scroll()
|
|
689
|
+
|
|
690
|
+
self.run_worker(go())
|
|
691
|
+
|
|
692
|
+
def action_interrupt(self) -> None:
|
|
693
|
+
if self._agent_busy:
|
|
694
|
+
self.workers.cancel_group(self, "agent")
|
|
695
|
+
|
|
696
|
+
def action_toggle_mode(self) -> None:
|
|
697
|
+
if isinstance(self.screen, ModalScreen):
|
|
698
|
+
self.screen.focus_next()
|
|
699
|
+
return
|
|
700
|
+
if self.query_one(MentionList).display:
|
|
701
|
+
self.query_one(PromptInput).accept_suggestion() # Tab completes the suggestion
|
|
702
|
+
return
|
|
703
|
+
self._agent_mode = "plan" if (self.agent.mode if self.agent else self._agent_mode) == "build" else "build"
|
|
704
|
+
if self.agent:
|
|
705
|
+
self.agent.mode = self._agent_mode # type: ignore[assignment]
|
|
706
|
+
self._refresh_bars()
|
|
707
|
+
self.notify(tr("Plan: агент только читает и планирует") if self._agent_mode == "plan"
|
|
708
|
+
else tr("Build: агент может править код"), timeout=2)
|
|
709
|
+
|
|
710
|
+
def action_connect(self) -> None:
|
|
711
|
+
if isinstance(self.screen, SetupScreen):
|
|
712
|
+
return
|
|
713
|
+
|
|
714
|
+
def done(saved: bool | None) -> None:
|
|
715
|
+
if saved:
|
|
716
|
+
self.auth = load_auth(self.config_base)
|
|
717
|
+
self._build_agent()
|
|
718
|
+
self.session.model = self.settings.model
|
|
719
|
+
self._refresh_bars()
|
|
720
|
+
self.notify(tr('Подключено: {0}', self.settings.model), timeout=3)
|
|
721
|
+
self.query_one(PromptInput).focus()
|
|
722
|
+
if self._pick_project:
|
|
723
|
+
self.call_after_refresh(self.action_projects)
|
|
724
|
+
|
|
725
|
+
self.push_screen(SetupScreen(self.settings, self.auth, self.config_base), done)
|
|
726
|
+
|
|
727
|
+
async def _reset_chat(self) -> None:
|
|
728
|
+
chat = self.query_one("#chat", VerticalScroll)
|
|
729
|
+
await chat.remove_children()
|
|
730
|
+
if self.agent:
|
|
731
|
+
self.agent.ctx.read_files.clear()
|
|
732
|
+
self.agent._always.clear()
|
|
733
|
+
|
|
734
|
+
def action_new_session(self) -> None:
|
|
735
|
+
if self._agent_busy:
|
|
736
|
+
self.notify(tr("Сначала остановите агента (Esc)."), severity="warning")
|
|
737
|
+
return
|
|
738
|
+
|
|
739
|
+
async def go() -> None:
|
|
740
|
+
await self._reset_chat()
|
|
741
|
+
await self.query_one("#chat", VerticalScroll).mount(self._welcome())
|
|
742
|
+
self.session = self.store.create(str(self.project_root), self.settings.model)
|
|
743
|
+
self._refresh_bars()
|
|
744
|
+
|
|
745
|
+
self.run_worker(go())
|
|
746
|
+
|
|
747
|
+
def action_sessions(self) -> None:
|
|
748
|
+
if self._agent_busy:
|
|
749
|
+
self.notify(tr("Сначала остановите агента (Esc)."), severity="warning")
|
|
750
|
+
return
|
|
751
|
+
sessions = [s for s in self.store.list(str(self.project_root)) if s.id != self.session.id]
|
|
752
|
+
|
|
753
|
+
def done(session_id: str | None) -> None:
|
|
754
|
+
if session_id:
|
|
755
|
+
self.run_worker(self._open_session(session_id))
|
|
756
|
+
|
|
757
|
+
self.push_screen(SessionsScreen(sessions), done)
|
|
758
|
+
|
|
759
|
+
async def _open_session(self, session_id: str) -> None:
|
|
760
|
+
loaded = self.store.load(session_id)
|
|
761
|
+
if not loaded:
|
|
762
|
+
return
|
|
763
|
+
await self._reset_chat()
|
|
764
|
+
self.session = loaded
|
|
765
|
+
chat = self.query_one("#chat", VerticalScroll)
|
|
766
|
+
results = {m.get("tool_call_id"): m.get("content", "") for m in loaded.messages if m.get("role") == "tool"}
|
|
767
|
+
tools = self.agent.tools if self.agent else {}
|
|
768
|
+
for m in loaded.messages:
|
|
769
|
+
role = m.get("role")
|
|
770
|
+
if role == "user":
|
|
771
|
+
await chat.mount(UserMessage(str(m.get("content", "")).split("\n\nAttached by the user:")[0]))
|
|
772
|
+
elif role == "assistant":
|
|
773
|
+
if m.get("content"):
|
|
774
|
+
await chat.mount(AssistantMessage(str(m["content"])))
|
|
775
|
+
for call in m.get("tool_calls") or []:
|
|
776
|
+
fn = call.get("function", {})
|
|
777
|
+
tool = tools.get(fn.get("name", ""))
|
|
778
|
+
try:
|
|
779
|
+
import json
|
|
780
|
+
args: dict[str, Any] = json.loads(fn.get("arguments") or "{}")
|
|
781
|
+
except ValueError:
|
|
782
|
+
args = {}
|
|
783
|
+
title = tool.title(args) if tool else fn.get("name", "?")
|
|
784
|
+
card = ToolCard(fn.get("name", "?"), title, tool.kind if tool else "read")
|
|
785
|
+
await chat.mount(card)
|
|
786
|
+
card.finish(ToolResult(str(results.get(call.get("id"), ""))))
|
|
787
|
+
await chat.mount(Notice(tr("↺ Сессия загружена. Продолжайте с того места, где остановились.")))
|
|
788
|
+
self._refresh_bars()
|
|
789
|
+
self._scroll()
|
|
790
|
+
|
|
791
|
+
def action_cycle_theme(self) -> None:
|
|
792
|
+
available = getattr(self, "available_themes", {})
|
|
793
|
+
themes = [(name, label) for name, label in THEME_LABELS.items() if name in available]
|
|
794
|
+
if not themes or isinstance(self.screen, ThemeScreen):
|
|
795
|
+
return
|
|
796
|
+
|
|
797
|
+
def done(name: str | None) -> None:
|
|
798
|
+
if name:
|
|
799
|
+
self.settings.theme = name
|
|
800
|
+
save_settings(self.settings, self.config_base)
|
|
801
|
+
self.notify(tr('Тема: {0}', THEME_LABELS.get(name, name)), timeout=2)
|
|
802
|
+
self._refresh_bars()
|
|
803
|
+
|
|
804
|
+
self.push_screen(ThemeScreen(themes, self.theme), done)
|
|
805
|
+
|
|
806
|
+
def action_help(self) -> None:
|
|
807
|
+
self.push_screen(HelpScreen(self._commands()))
|
|
808
|
+
|
|
809
|
+
async def on_unmount(self) -> None:
|
|
810
|
+
if self._llm_client is not None:
|
|
811
|
+
await self._llm_client.aclose()
|
|
812
|
+
self.store.close()
|