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/screens.py
ADDED
|
@@ -0,0 +1,556 @@
|
|
|
1
|
+
"""Dialogs: permission, model setup, sessions, help."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from ..i18n import tr
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import sys
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from rich.syntax import Syntax
|
|
11
|
+
from rich.text import Text
|
|
12
|
+
from textual import on, work
|
|
13
|
+
from textual.app import ComposeResult
|
|
14
|
+
from textual.containers import Horizontal, Vertical, VerticalScroll
|
|
15
|
+
from textual.screen import ModalScreen
|
|
16
|
+
from textual.widgets import (
|
|
17
|
+
Button, DirectoryTree, Input, Label, Markdown, OptionList, Select, Static, TabbedContent, TabPane,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
from .. import projects, providers
|
|
21
|
+
from ..llm import LLMClient, LLMError
|
|
22
|
+
from ..settings import Credentials, Settings, mask, save_auth, save_settings
|
|
23
|
+
from ..tools.base import IGNORE_DIRS
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ProviderEditScreen(ModalScreen[dict | None]):
|
|
27
|
+
"""Add your own OpenAI-compatible provider."""
|
|
28
|
+
|
|
29
|
+
BINDINGS = [("escape", "cancel", tr("Отмена"))]
|
|
30
|
+
|
|
31
|
+
def compose(self) -> ComposeResult:
|
|
32
|
+
with Vertical(id="dialog"):
|
|
33
|
+
yield Label(tr("Свой провайдер"), classes="dialog-title")
|
|
34
|
+
yield Label(tr("Подойдёт любой сервер с OpenAI-совместимым API: свой роутер, прокси, облако."),
|
|
35
|
+
classes="hint")
|
|
36
|
+
yield Label(tr("Название"))
|
|
37
|
+
yield Input(placeholder=tr("например: Мой ANIX"), id="p-name")
|
|
38
|
+
yield Label(tr("Адрес API (обычно заканчивается на /v1)"))
|
|
39
|
+
yield Input(placeholder="http://localhost:3001/v1", id="p-url")
|
|
40
|
+
yield Label(tr("API-ключ (если нужен)"))
|
|
41
|
+
yield Input(password=True, placeholder=tr("оставьте пустым, если ключ не нужен"), id="p-key")
|
|
42
|
+
yield Static(id="p-status", classes="hint")
|
|
43
|
+
with Horizontal(classes="buttons"):
|
|
44
|
+
yield Button(tr("Добавить"), id="p-save", variant="primary")
|
|
45
|
+
yield Button(tr("Проверить"), id="p-test")
|
|
46
|
+
yield Button(tr("Отмена"), id="p-cancel")
|
|
47
|
+
|
|
48
|
+
def on_mount(self) -> None:
|
|
49
|
+
self.query_one("#p-name", Input).focus()
|
|
50
|
+
|
|
51
|
+
def _values(self) -> tuple[str, str, str]:
|
|
52
|
+
return (self.query_one("#p-name", Input).value.strip(), self.query_one("#p-url", Input).value.strip(),
|
|
53
|
+
self.query_one("#p-key", Input).value.strip())
|
|
54
|
+
|
|
55
|
+
@on(Button.Pressed, "#p-test")
|
|
56
|
+
def _test_pressed(self) -> None:
|
|
57
|
+
self.test_connection()
|
|
58
|
+
|
|
59
|
+
@work(exclusive=True)
|
|
60
|
+
async def test_connection(self) -> None:
|
|
61
|
+
status = self.query_one("#p-status", Static)
|
|
62
|
+
_name, url, key = self._values()
|
|
63
|
+
if not url.startswith(("http://", "https://")):
|
|
64
|
+
status.update(Text(tr("Адрес должен начинаться с http:// или https://"), style="red"))
|
|
65
|
+
return
|
|
66
|
+
status.update(tr("Проверяю…"))
|
|
67
|
+
client = LLMClient(url, key, timeout=20)
|
|
68
|
+
try:
|
|
69
|
+
models = await client.list_models()
|
|
70
|
+
except LLMError as e:
|
|
71
|
+
status.update(Text(str(e), style="red"))
|
|
72
|
+
return
|
|
73
|
+
finally:
|
|
74
|
+
await client.aclose()
|
|
75
|
+
status.update(Text(tr('✓ Работает, моделей: {0}', len(models)) if models else
|
|
76
|
+
tr("✓ Сервер отвечает (список моделей пуст, название модели впишете вручную)"),
|
|
77
|
+
style="green"))
|
|
78
|
+
|
|
79
|
+
@on(Button.Pressed, "#p-save")
|
|
80
|
+
def _save(self) -> None:
|
|
81
|
+
name, url, key = self._values()
|
|
82
|
+
status = self.query_one("#p-status", Static)
|
|
83
|
+
if not name:
|
|
84
|
+
status.update(Text(tr("Введите название."), style="red"))
|
|
85
|
+
return
|
|
86
|
+
if not url.startswith(("http://", "https://")):
|
|
87
|
+
status.update(Text(tr("Адрес должен начинаться с http:// или https://"), style="red"))
|
|
88
|
+
return
|
|
89
|
+
self.dismiss({"name": name, "base_url": url, "api_key": key})
|
|
90
|
+
|
|
91
|
+
@on(Button.Pressed, "#p-cancel")
|
|
92
|
+
def action_cancel(self) -> None:
|
|
93
|
+
self.dismiss(None)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class SetupScreen(ModalScreen[bool]):
|
|
97
|
+
"""Pick a provider, paste a key, choose a model."""
|
|
98
|
+
|
|
99
|
+
BINDINGS = [("escape", "cancel", tr("Отмена"))]
|
|
100
|
+
|
|
101
|
+
def __init__(self, settings: Settings, auth: dict[str, Credentials], base: Path | None = None) -> None:
|
|
102
|
+
super().__init__()
|
|
103
|
+
self.settings = settings
|
|
104
|
+
self.auth = auth
|
|
105
|
+
self.base = base
|
|
106
|
+
self._model_ids: list[str] = []
|
|
107
|
+
|
|
108
|
+
def _options(self) -> list[tuple[str, str]]:
|
|
109
|
+
return [(("★ " if p.is_user else "") + p.name, p.id) for p in providers.all_providers(self.settings)]
|
|
110
|
+
|
|
111
|
+
def compose(self) -> ComposeResult:
|
|
112
|
+
ids = {p.id for p in providers.all_providers(self.settings)}
|
|
113
|
+
current = self.settings.provider if self.settings.provider in ids else "deepseek"
|
|
114
|
+
with Vertical(id="dialog"):
|
|
115
|
+
yield Label(tr("Подключение модели"), classes="dialog-title")
|
|
116
|
+
yield Label(tr("Провайдер"))
|
|
117
|
+
with Horizontal(id="provider-row"):
|
|
118
|
+
yield Select(self._options(), value=current, allow_blank=False, id="provider")
|
|
119
|
+
yield Button(tr("+ Свой"), id="add-provider")
|
|
120
|
+
yield Button(tr("Удалить"), id="del-provider", variant="error")
|
|
121
|
+
yield Label(tr("API-ключ"))
|
|
122
|
+
yield Input(password=True, id="key")
|
|
123
|
+
yield Static(id="key-hint", classes="hint")
|
|
124
|
+
yield Label(tr("Адрес сервера"))
|
|
125
|
+
yield Input(id="base-url")
|
|
126
|
+
yield Label(tr("Модель"))
|
|
127
|
+
with Horizontal(id="model-row"):
|
|
128
|
+
yield Input(id="model", placeholder=tr("название модели"))
|
|
129
|
+
yield Button(tr("Список моделей"), id="fetch")
|
|
130
|
+
yield OptionList(id="models")
|
|
131
|
+
yield Static(id="setup-error", classes="error")
|
|
132
|
+
with Horizontal(classes="buttons"):
|
|
133
|
+
yield Button(tr("Сохранить"), id="save", variant="primary")
|
|
134
|
+
yield Button(tr("Отмена"), id="cancel")
|
|
135
|
+
|
|
136
|
+
def on_mount(self) -> None:
|
|
137
|
+
self._fill(self.provider_id)
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def provider_id(self) -> str:
|
|
141
|
+
return str(self.query_one("#provider", Select).value)
|
|
142
|
+
|
|
143
|
+
@on(Select.Changed, "#provider")
|
|
144
|
+
def _provider_changed(self, event: Select.Changed) -> None:
|
|
145
|
+
self._fill(str(event.value))
|
|
146
|
+
|
|
147
|
+
def _fill(self, pid: str) -> None:
|
|
148
|
+
p = providers.get(pid, self.settings)
|
|
149
|
+
cred = self.auth.get(pid, Credentials())
|
|
150
|
+
key = self.query_one("#key", Input)
|
|
151
|
+
key.value = ""
|
|
152
|
+
key.placeholder = tr('сохранён: {0}', mask(cred.api_key)) if cred.api_key else ("sk-…" if p.needs_key else tr("не обязателен"))
|
|
153
|
+
hint = tr('Где взять ключ: {0}', p.key_url) if p.key_url else (tr("Ключ не нужен") if not p.needs_key else "")
|
|
154
|
+
self.query_one("#key-hint", Static).update(hint)
|
|
155
|
+
self.query_one("#base-url", Input).value = cred.base_url or p.base_url
|
|
156
|
+
model = self.settings.model if self.settings.provider == pid else p.default_model
|
|
157
|
+
self.query_one("#model", Input).value = model
|
|
158
|
+
self.query_one("#models", OptionList).remove_class("visible")
|
|
159
|
+
self.query_one("#setup-error", Static).update("")
|
|
160
|
+
self.query_one("#del-provider", Button).display = p.is_user
|
|
161
|
+
|
|
162
|
+
def _reload_options(self, select_id: str) -> None:
|
|
163
|
+
select = self.query_one("#provider", Select)
|
|
164
|
+
select.set_options(self._options())
|
|
165
|
+
select.value = select_id
|
|
166
|
+
self._fill(select_id)
|
|
167
|
+
|
|
168
|
+
@on(Button.Pressed, "#add-provider")
|
|
169
|
+
def _add_provider(self) -> None:
|
|
170
|
+
def done(result: dict | None) -> None:
|
|
171
|
+
if not result:
|
|
172
|
+
return
|
|
173
|
+
existing = {d["id"] for d in self.settings.custom_providers}
|
|
174
|
+
pid = providers.make_id(result["name"], existing)
|
|
175
|
+
self.settings.custom_providers.append({"id": pid, "name": result["name"], "base_url": result["base_url"]})
|
|
176
|
+
if result["api_key"]:
|
|
177
|
+
self.auth[pid] = Credentials(api_key=result["api_key"])
|
|
178
|
+
save_auth(self.auth, self.base)
|
|
179
|
+
save_settings(self.settings, self.base)
|
|
180
|
+
self._reload_options(pid)
|
|
181
|
+
self.notify(tr('Провайдер «{0}» добавлен. Выберите модель.', result['name']), timeout=3)
|
|
182
|
+
|
|
183
|
+
self.app.push_screen(ProviderEditScreen(), done)
|
|
184
|
+
|
|
185
|
+
@on(Button.Pressed, "#del-provider")
|
|
186
|
+
def _delete_provider(self) -> None:
|
|
187
|
+
pid = self.provider_id
|
|
188
|
+
if not pid.startswith("user:"):
|
|
189
|
+
return
|
|
190
|
+
self.settings.custom_providers = [d for d in self.settings.custom_providers if d["id"] != pid]
|
|
191
|
+
self.auth.pop(pid, None)
|
|
192
|
+
if self.settings.provider == pid:
|
|
193
|
+
self.settings.provider, self.settings.model = "", ""
|
|
194
|
+
save_auth(self.auth, self.base)
|
|
195
|
+
save_settings(self.settings, self.base)
|
|
196
|
+
self._reload_options("deepseek")
|
|
197
|
+
|
|
198
|
+
def _current_key(self) -> str:
|
|
199
|
+
typed = self.query_one("#key", Input).value.strip()
|
|
200
|
+
return typed or self.auth.get(self.provider_id, Credentials()).api_key
|
|
201
|
+
|
|
202
|
+
@on(Button.Pressed, "#fetch")
|
|
203
|
+
def _fetch_pressed(self) -> None:
|
|
204
|
+
self.fetch_models()
|
|
205
|
+
|
|
206
|
+
@work(exclusive=True)
|
|
207
|
+
async def fetch_models(self) -> None:
|
|
208
|
+
error = self.query_one("#setup-error", Static)
|
|
209
|
+
error.update(tr("Загружаю список моделей…"))
|
|
210
|
+
base_url = self.query_one("#base-url", Input).value.strip()
|
|
211
|
+
client = LLMClient(base_url, self._current_key(), timeout=30)
|
|
212
|
+
try:
|
|
213
|
+
models = await client.list_models()
|
|
214
|
+
except LLMError as e:
|
|
215
|
+
error.update(str(e))
|
|
216
|
+
return
|
|
217
|
+
finally:
|
|
218
|
+
await client.aclose()
|
|
219
|
+
if not models:
|
|
220
|
+
error.update(tr("Сервер не вернул список. Впишите название модели вручную."))
|
|
221
|
+
return
|
|
222
|
+
self._model_ids = models
|
|
223
|
+
box = self.query_one("#models", OptionList)
|
|
224
|
+
box.clear_options()
|
|
225
|
+
box.add_options(models)
|
|
226
|
+
box.add_class("visible")
|
|
227
|
+
error.update(tr('Моделей: {0}. Выберите стрелками и Enter.', len(models)))
|
|
228
|
+
box.focus()
|
|
229
|
+
|
|
230
|
+
@on(OptionList.OptionSelected, "#models")
|
|
231
|
+
def _model_picked(self, event: OptionList.OptionSelected) -> None:
|
|
232
|
+
self.query_one("#model", Input).value = self._model_ids[event.option_index]
|
|
233
|
+
self.query_one("#models", OptionList).remove_class("visible")
|
|
234
|
+
|
|
235
|
+
@on(Button.Pressed, "#save")
|
|
236
|
+
def _save(self) -> None:
|
|
237
|
+
pid = self.provider_id
|
|
238
|
+
p = providers.get(pid, self.settings)
|
|
239
|
+
base_url = self.query_one("#base-url", Input).value.strip()
|
|
240
|
+
model = self.query_one("#model", Input).value.strip()
|
|
241
|
+
typed_key = self.query_one("#key", Input).value.strip()
|
|
242
|
+
error = self.query_one("#setup-error", Static)
|
|
243
|
+
if not base_url.startswith(("http://", "https://")):
|
|
244
|
+
error.update(tr("Укажите адрес сервера, начиная с http:// или https://"))
|
|
245
|
+
return
|
|
246
|
+
if p.needs_key and not self._current_key():
|
|
247
|
+
error.update(tr("Вставьте API-ключ."))
|
|
248
|
+
return
|
|
249
|
+
if not model:
|
|
250
|
+
error.update(tr("Укажите модель или нажмите «Список моделей»."))
|
|
251
|
+
return
|
|
252
|
+
cred = self.auth.get(pid, Credentials())
|
|
253
|
+
if typed_key:
|
|
254
|
+
cred.api_key = typed_key
|
|
255
|
+
if p.is_user: # the address belongs to the provider entry itself
|
|
256
|
+
for d in self.settings.custom_providers:
|
|
257
|
+
if d["id"] == pid:
|
|
258
|
+
d["base_url"] = base_url
|
|
259
|
+
cred.base_url = ""
|
|
260
|
+
else:
|
|
261
|
+
cred.base_url = "" if base_url == p.base_url else base_url
|
|
262
|
+
self.auth[pid] = cred
|
|
263
|
+
self.settings.provider, self.settings.model = pid, model
|
|
264
|
+
save_auth(self.auth, self.base)
|
|
265
|
+
save_settings(self.settings, self.base)
|
|
266
|
+
self.dismiss(True)
|
|
267
|
+
|
|
268
|
+
@on(Button.Pressed, "#cancel")
|
|
269
|
+
def action_cancel(self) -> None:
|
|
270
|
+
self.dismiss(False)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
class ThemeScreen(ModalScreen[str | None]):
|
|
274
|
+
"""Theme picker with live preview."""
|
|
275
|
+
|
|
276
|
+
BINDINGS = [("escape", "cancel", tr("Отмена"))]
|
|
277
|
+
|
|
278
|
+
def __init__(self, themes: list[tuple[str, str]], current: str) -> None:
|
|
279
|
+
super().__init__()
|
|
280
|
+
self.themes = themes
|
|
281
|
+
self.original = current
|
|
282
|
+
|
|
283
|
+
def compose(self) -> ComposeResult:
|
|
284
|
+
with Vertical(id="dialog"):
|
|
285
|
+
yield Label(tr("Тема"), classes="dialog-title")
|
|
286
|
+
yield OptionList(*[label for _name, label in self.themes], id="theme-list")
|
|
287
|
+
yield Label(tr("↑↓ — посмотреть · Enter — выбрать · Esc — отмена"), classes="hint")
|
|
288
|
+
|
|
289
|
+
def on_mount(self) -> None:
|
|
290
|
+
box = self.query_one("#theme-list", OptionList)
|
|
291
|
+
names = [n for n, _ in self.themes]
|
|
292
|
+
if self.original in names:
|
|
293
|
+
box.highlighted = names.index(self.original)
|
|
294
|
+
box.focus()
|
|
295
|
+
|
|
296
|
+
@on(OptionList.OptionHighlighted, "#theme-list")
|
|
297
|
+
def _preview(self, event: OptionList.OptionHighlighted) -> None:
|
|
298
|
+
try:
|
|
299
|
+
self.app.theme = self.themes[event.option_index][0]
|
|
300
|
+
except Exception:
|
|
301
|
+
pass
|
|
302
|
+
|
|
303
|
+
@on(OptionList.OptionSelected, "#theme-list")
|
|
304
|
+
def _picked(self, event: OptionList.OptionSelected) -> None:
|
|
305
|
+
self.dismiss(self.themes[event.option_index][0])
|
|
306
|
+
|
|
307
|
+
def action_cancel(self) -> None:
|
|
308
|
+
try:
|
|
309
|
+
self.app.theme = self.original
|
|
310
|
+
except Exception:
|
|
311
|
+
pass
|
|
312
|
+
self.dismiss(None)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
class SessionsScreen(ModalScreen[str | None]):
|
|
316
|
+
BINDINGS = [("escape", "close", tr("Закрыть"))]
|
|
317
|
+
|
|
318
|
+
def __init__(self, sessions: list) -> None:
|
|
319
|
+
super().__init__()
|
|
320
|
+
self.sessions = sessions
|
|
321
|
+
|
|
322
|
+
def compose(self) -> ComposeResult:
|
|
323
|
+
with Vertical(id="dialog"):
|
|
324
|
+
yield Label(tr("Сессии в этой папке"), classes="dialog-title")
|
|
325
|
+
if not self.sessions:
|
|
326
|
+
yield Label(tr("Пока пусто."), classes="hint")
|
|
327
|
+
else:
|
|
328
|
+
yield OptionList(*[
|
|
329
|
+
f"{datetime.fromtimestamp(s.updated):%d.%m %H:%M} {s.title}" for s in self.sessions
|
|
330
|
+
], id="session-list")
|
|
331
|
+
yield Label(tr("Enter — открыть, Esc — закрыть"), classes="hint")
|
|
332
|
+
|
|
333
|
+
@on(OptionList.OptionSelected)
|
|
334
|
+
def _picked(self, event: OptionList.OptionSelected) -> None:
|
|
335
|
+
self.dismiss(self.sessions[event.option_index].id)
|
|
336
|
+
|
|
337
|
+
def action_close(self) -> None:
|
|
338
|
+
self.dismiss(None)
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
HELP = tr("""\
|
|
342
|
+
# ANIX Code
|
|
343
|
+
|
|
344
|
+
| Клавиши | Что делают |
|
|
345
|
+
|---|---|
|
|
346
|
+
| `Enter` | отправить |
|
|
347
|
+
| `Ctrl+J` | новая строка |
|
|
348
|
+
| `↑` / `↓` | история запросов |
|
|
349
|
+
| `Tab` | режим **Build** (правит код) / **Plan** (только читает и планирует) |
|
|
350
|
+
| `Esc` | остановить агента |
|
|
351
|
+
| `Ctrl+P` | выбрать проект (папку / репозиторий), клонировать с GitHub |
|
|
352
|
+
| `F2` | полный доступ вкл/выкл (агент не спрашивает разрешения) |
|
|
353
|
+
| `Ctrl+O` | модель и API-ключ |
|
|
354
|
+
| `Ctrl+N` | новая сессия |
|
|
355
|
+
| `Ctrl+S` | прошлые сессии |
|
|
356
|
+
| `Ctrl+T` | выбрать тему |
|
|
357
|
+
| `Ctrl+Q` | выход |
|
|
358
|
+
|
|
359
|
+
Быстрый ввод:
|
|
360
|
+
- `/` — список команд с подсказками (↑↓, Tab — дописать, Enter — выполнить)
|
|
361
|
+
- `!команда` — выполнить команду в терминале самому; агент увидит вывод
|
|
362
|
+
- `# текст` — записать правило в `AGENTS.md` («# используй pnpm, а не npm»)
|
|
363
|
+
- `Shift+Tab` или `Tab` — Build / Plan
|
|
364
|
+
|
|
365
|
+
Ещё:
|
|
366
|
+
- `/init` — агент изучит проект и напишет `AGENTS.md` с правилами для себя
|
|
367
|
+
- `@путь` в запросе — прикрепить файл или папку (после `@` появятся подсказки: ↑↓, Enter/Tab)
|
|
368
|
+
- `/undo` — откатить правки файлов из последнего ответа агента (можно несколько раз подряд)
|
|
369
|
+
- `/compact` — сжать историю вручную (обычно это происходит само при заполнении контекста)
|
|
370
|
+
- `/project` — выбрать проект; клик по пути в шапке делает то же самое
|
|
371
|
+
- `/connect`, `/new`, `/sessions`, `/theme`, `/help`, `/exit`
|
|
372
|
+
|
|
373
|
+
Внизу справа видно, на сколько заполнен контекст модели. При 80% история сжимается автоматически.
|
|
374
|
+
При сбоях сети и лимитах запросов агент сам повторяет запрос до 4 раз.
|
|
375
|
+
Когда агент хочет изменить файл или выполнить команду, над полем ввода появляется строка:
|
|
376
|
+
`Enter` — разрешить, `Esc` — отклонить, текст + `Enter` — отклонить и объяснить, как надо.
|
|
377
|
+
Опасные команды (удаление, `git push --force`, форматирование…) подсвечиваются красным.
|
|
378
|
+
**Полный доступ** (`F2` или клик внизу справа): агент работает без вопросов.
|
|
379
|
+
|
|
380
|
+
Клик по карточке действия показывает diff или вывод команды.
|
|
381
|
+
Правила проекта для агента можно написать в `AGENTS.md` в корне проекта.
|
|
382
|
+
""")
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
class HelpScreen(ModalScreen[None]):
|
|
386
|
+
BINDINGS = [("escape", "close", tr("Закрыть")), ("f1", "close", tr("Закрыть")), ("q", "close", tr("Закрыть"))]
|
|
387
|
+
|
|
388
|
+
def __init__(self, commands_list: list | None = None) -> None:
|
|
389
|
+
super().__init__()
|
|
390
|
+
self.commands_list = commands_list or []
|
|
391
|
+
|
|
392
|
+
def compose(self) -> ComposeResult:
|
|
393
|
+
seen, rows = set(), []
|
|
394
|
+
for c in self.commands_list:
|
|
395
|
+
if c.description in seen and c.action:
|
|
396
|
+
continue # aliases (/clear, /models…) once
|
|
397
|
+
seen.add(c.description)
|
|
398
|
+
src = tr(" *(свой)*") if c.source != "builtin" else ""
|
|
399
|
+
rows.append(f"| `/{c.name}` {c.args_hint} | {c.description}{src} |")
|
|
400
|
+
table = "\n".join([tr("| Команда | Что делает |"), "|---|---|", *rows])
|
|
401
|
+
with VerticalScroll(id="dialog"):
|
|
402
|
+
yield Markdown(HELP + tr("\n## Команды\n\n") + table + "\n\n" + CUSTOM_HELP)
|
|
403
|
+
yield Label(tr("Esc — закрыть"), classes="hint")
|
|
404
|
+
|
|
405
|
+
def action_close(self) -> None:
|
|
406
|
+
self.dismiss(None)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
CUSTOM_HELP = tr("""\
|
|
410
|
+
## Свои команды
|
|
411
|
+
|
|
412
|
+
Положите Markdown-файл в `.anixcode/commands/имя.md` (для проекта) или в папку настроек
|
|
413
|
+
`commands/имя.md` (для всех проектов). Текст файла станет запросом агенту, `$ARGUMENTS` заменится
|
|
414
|
+
на всё, что написано после команды, `$1`, `$2` — на отдельные слова. Описание для подсказок:
|
|
415
|
+
|
|
416
|
+
```markdown
|
|
417
|
+
---
|
|
418
|
+
description: прогнать линтер и всё починить
|
|
419
|
+
---
|
|
420
|
+
Run the linter for $ARGUMENTS and fix every warning.
|
|
421
|
+
```
|
|
422
|
+
""")
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
class FolderTree(DirectoryTree):
|
|
426
|
+
"""Folders only, no hidden or junk folders."""
|
|
427
|
+
|
|
428
|
+
def filter_paths(self, paths):
|
|
429
|
+
out = []
|
|
430
|
+
for p in paths:
|
|
431
|
+
try:
|
|
432
|
+
if p.is_dir() and not p.name.startswith(".") and p.name not in IGNORE_DIRS:
|
|
433
|
+
out.append(p)
|
|
434
|
+
except OSError:
|
|
435
|
+
continue
|
|
436
|
+
return out
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
class ProjectScreen(ModalScreen[str | None]):
|
|
440
|
+
"""Pick the folder (repository) the agent works in: recent, found repos, browse, or git clone."""
|
|
441
|
+
|
|
442
|
+
BINDINGS = [("escape", "cancel", tr("Отмена"))]
|
|
443
|
+
|
|
444
|
+
def __init__(self, current: Path, recent: list[str]) -> None:
|
|
445
|
+
super().__init__()
|
|
446
|
+
self.current = current
|
|
447
|
+
self.recent = [r for r in recent if Path(r).is_dir()]
|
|
448
|
+
self._repos: list[Path] = []
|
|
449
|
+
self.drive_list = projects.drives()
|
|
450
|
+
|
|
451
|
+
def compose(self) -> ComposeResult:
|
|
452
|
+
with Vertical(id="dialog", classes="wide"):
|
|
453
|
+
yield Label(tr("Проект: в какой папке работать"), classes="dialog-title")
|
|
454
|
+
with Horizontal(id="proj-row"):
|
|
455
|
+
yield Input(value=str(self.current), placeholder=tr("Путь к папке или ссылка на git-репозиторий"),
|
|
456
|
+
id="proj-path")
|
|
457
|
+
yield Button(tr("Открыть"), id="proj-open", variant="primary")
|
|
458
|
+
yield Static(id="proj-status", classes="hint")
|
|
459
|
+
with TabbedContent(id="proj-tabs"):
|
|
460
|
+
with TabPane(tr("Недавние"), id="tab-recent"):
|
|
461
|
+
if self.recent:
|
|
462
|
+
yield OptionList(*[self._label(Path(r)) for r in self.recent], id="recent-list")
|
|
463
|
+
else:
|
|
464
|
+
yield Label(tr("Пока пусто: здесь появятся папки, которые вы открывали."), classes="hint")
|
|
465
|
+
with TabPane(tr("Репозитории"), id="tab-repos"):
|
|
466
|
+
yield Label(tr("Ищу git-репозитории…"), id="repos-hint", classes="hint")
|
|
467
|
+
yield OptionList(id="repos-list")
|
|
468
|
+
with TabPane(tr("Обзор"), id="tab-browse"):
|
|
469
|
+
with Horizontal(id="drive-row"):
|
|
470
|
+
yield Button(tr("🏠 Домой"), id="drive-home", classes="drive")
|
|
471
|
+
for i, d in enumerate(self.drive_list):
|
|
472
|
+
yield Button(str(d).rstrip("\\/") or "/", id=f"drive-{i}", classes="drive")
|
|
473
|
+
yield FolderTree(str(Path.home()), id="folder-tree")
|
|
474
|
+
yield Label(tr("Кликните папку в дереве (она раскроется и подставится в строку) и нажмите «Открыть». "
|
|
475
|
+
"Ссылка https://github.com/… — склонировать. Esc — отмена."), classes="hint")
|
|
476
|
+
|
|
477
|
+
@staticmethod
|
|
478
|
+
def _label(p: Path) -> Text:
|
|
479
|
+
mark = "● " if projects.is_git_repo(p) else " "
|
|
480
|
+
text = Text(mark, style="green")
|
|
481
|
+
text.append(p.name or str(p), style="bold")
|
|
482
|
+
text.append(f" {p}", style="dim")
|
|
483
|
+
return text
|
|
484
|
+
|
|
485
|
+
def on_mount(self) -> None:
|
|
486
|
+
self.query_one("#proj-path", Input).focus()
|
|
487
|
+
self.query_one(FolderTree).root.expand()
|
|
488
|
+
self.scan_repos()
|
|
489
|
+
|
|
490
|
+
@on(Button.Pressed, ".drive")
|
|
491
|
+
def _drive_pressed(self, event: Button.Pressed) -> None:
|
|
492
|
+
bid = event.button.id or ""
|
|
493
|
+
target = Path.home() if bid == "drive-home" else self.drive_list[int(bid.split("-")[1])]
|
|
494
|
+
tree = self.query_one(FolderTree)
|
|
495
|
+
tree.path = target
|
|
496
|
+
self._set_path(target)
|
|
497
|
+
self.call_after_refresh(tree.root.expand)
|
|
498
|
+
|
|
499
|
+
@work(exclusive=True, group="scan")
|
|
500
|
+
async def scan_repos(self) -> None:
|
|
501
|
+
repos = await asyncio.to_thread(projects.find_repos, projects.search_roots())
|
|
502
|
+
self._repos = repos
|
|
503
|
+
hint = self.query_one("#repos-hint", Label)
|
|
504
|
+
box = self.query_one("#repos-list", OptionList)
|
|
505
|
+
if not repos:
|
|
506
|
+
hint.update(tr("Не нашёл репозиториев в Desktop, Documents, Projects и похожих папках. Используйте «Обзор»."))
|
|
507
|
+
return
|
|
508
|
+
hint.update(tr('Найдено: {0}', len(repos)))
|
|
509
|
+
box.add_options([self._label(p) for p in repos])
|
|
510
|
+
|
|
511
|
+
def _set_path(self, p: Path) -> None:
|
|
512
|
+
self.query_one("#proj-path", Input).value = str(p)
|
|
513
|
+
|
|
514
|
+
@on(OptionList.OptionSelected, "#recent-list")
|
|
515
|
+
def _recent_picked(self, event: OptionList.OptionSelected) -> None:
|
|
516
|
+
self._open(Path(self.recent[event.option_index]))
|
|
517
|
+
|
|
518
|
+
@on(OptionList.OptionSelected, "#repos-list")
|
|
519
|
+
def _repo_picked(self, event: OptionList.OptionSelected) -> None:
|
|
520
|
+
self._open(self._repos[event.option_index])
|
|
521
|
+
|
|
522
|
+
@on(DirectoryTree.DirectorySelected, "#folder-tree")
|
|
523
|
+
def _folder_picked(self, event: DirectoryTree.DirectorySelected) -> None:
|
|
524
|
+
self._set_path(Path(event.path))
|
|
525
|
+
|
|
526
|
+
@on(Input.Submitted, "#proj-path")
|
|
527
|
+
@on(Button.Pressed, "#proj-open")
|
|
528
|
+
def _open_pressed(self) -> None:
|
|
529
|
+
value = self.query_one("#proj-path", Input).value.strip().strip('"')
|
|
530
|
+
if projects.GIT_URL.match(value) and not Path(value).exists():
|
|
531
|
+
self.clone_repo(value)
|
|
532
|
+
return
|
|
533
|
+
self._open(Path(value).expanduser())
|
|
534
|
+
|
|
535
|
+
def _open(self, p: Path) -> None:
|
|
536
|
+
status = self.query_one("#proj-status", Static)
|
|
537
|
+
if not p.is_dir():
|
|
538
|
+
status.update(Text(tr('Нет такой папки: {0}', p), style="red"))
|
|
539
|
+
return
|
|
540
|
+
self.dismiss(str(p.resolve()))
|
|
541
|
+
|
|
542
|
+
@work(exclusive=True, group="clone")
|
|
543
|
+
async def clone_repo(self, url: str) -> None:
|
|
544
|
+
status = self.query_one("#proj-status", Static)
|
|
545
|
+
parent = self.current if not projects.is_unsuitable(self.current) and not projects.is_git_repo(self.current) \
|
|
546
|
+
else Path.home() / "Projects"
|
|
547
|
+
status.update(tr('Клонирую в {0}…', parent))
|
|
548
|
+
try:
|
|
549
|
+
target = await asyncio.to_thread(projects.clone, url, parent)
|
|
550
|
+
except RuntimeError as e:
|
|
551
|
+
status.update(Text(str(e), style="red"))
|
|
552
|
+
return
|
|
553
|
+
self.dismiss(str(target))
|
|
554
|
+
|
|
555
|
+
def action_cancel(self) -> None:
|
|
556
|
+
self.dismiss(None)
|