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/i18n_en.py ADDED
@@ -0,0 +1,293 @@
1
+ """English translations. Keys are the Russian source strings used in the code (tr("…")).
2
+
3
+ Generated from the code; when you add a tr() string, add its translation here.
4
+ """
5
+
6
+ EN: dict[str, str] = {
7
+ 'Не удалось сжать историю: модель вернула пустую сводку.': 'Could not compress the history: the model returned an empty summary.',
8
+ 'Агент сделал {0} шагов и остановился. Напишите «продолжай».': 'The agent made {0} steps and stopped. Type “continue”.',
9
+ 'Модель ничего не ответила.': 'The model returned nothing.',
10
+ 'Провайдеры:': 'Providers:',
11
+ 'Сохранено: {0} · {1}': 'Saved: {0} · {1}',
12
+ 'Нет такой папки: {0}': 'No such folder: {0}',
13
+ 'Ключ можно взять здесь: {0}': 'Get a key here: {0}',
14
+ 'Нужно указать модель. Список: anixcode models': 'A model is required. List: anixcode models',
15
+ 'Сначала: anixcode connect': 'First run: anixcode connect',
16
+ 'Сначала подключите модель: anixcode connect': 'Connect a model first: anixcode connect',
17
+ 'ИИ-агент для кода в терминале': 'AI coding agent for your terminal',
18
+ 'Не хватает библиотеки {0}. Установите: pip install -e .': 'Library {0} is missing. Install: pip install -e .',
19
+ 'Номер: ': 'Number: ',
20
+ 'Неверный номер.': 'Wrong number.',
21
+ 'API-ключ (Enter — оставить прежний): ': 'API key (Enter to keep the current one): ',
22
+ 'Команда /{0} работает только в интерфейсе или не существует.': 'Command /{0} works only in the interface or does not exist.',
23
+ 'выполнить задачу без интерфейса': 'run a task without the interface',
24
+ 'только читать и планировать': 'only read and plan',
25
+ 'разрешать все действия без вопросов': 'allow every action without asking',
26
+ 'показывать размышления модели': "show the model's reasoning",
27
+ 'папка проекта (по умолчанию текущая)': 'project folder (default: current)',
28
+ 'Адрес сервера [{0}]: ': 'Server address [{0}]: ',
29
+ 'Модель [{0}]: ': 'Model [{0}]: ',
30
+ 'подключить модель и API-ключ': 'connect a model and API key',
31
+ 'список моделей провайдера': "list the provider's models",
32
+ 'Разрешить? [y]es / [a]lways / [n]o: ': 'Allow? [y]es / [a]lways / [n]o: ',
33
+ '\n… повтор {0}/{1} через {2:.0f}с ({3})': '\n… retry {0}/{1} in {2:.0f}s ({3})',
34
+ '\n🗜 история сжата: ~{0} → ~{1} токенов': '\n🗜 history compressed: ~{0} → ~{1} tokens',
35
+ 'изучить проект и написать AGENTS.md': 'study the project and write AGENTS.md',
36
+ 'ревью незакоммиченных изменений: баги, риски': 'review uncommitted changes: bugs, risks',
37
+ 'закоммитить изменения с хорошим сообщением': 'commit changes with a good message',
38
+ 'найти и запустить тесты, починить падающие': 'find and run the tests, fix failing ones',
39
+ 'починить ошибку: вставьте текст ошибки или опишите баг': 'fix an error: paste the error text or describe the bug',
40
+ 'объяснить код: файл, функцию или весь проект': 'explain code: a file, a function or the whole project',
41
+ 'описание pull request для текущей ветки': 'pull request description for the current branch',
42
+ 'все команды и клавиши': 'all commands and keys',
43
+ 'новая сессия': 'new session',
44
+ 'новая сессия (то же, что /new)': 'new session (same as /new)',
45
+ 'прошлые сессии этого проекта': 'past sessions of this project',
46
+ 'продолжить прошлую сессию': 'resume a past session',
47
+ 'откатить правки файлов из последнего ответа': 'undo file changes from the last answer',
48
+ 'вернуть то, что откатили /undo': 'bring back what /undo reverted',
49
+ 'сжать историю, чтобы освободить контекст': 'compress the history to free up context',
50
+ 'модель, провайдер и API-ключ': 'model, provider and API key',
51
+ 'подключить провайдера': 'connect a provider',
52
+ 'выбрать проект или склонировать репозиторий': 'choose a project or clone a repository',
53
+ 'выбрать тему': 'choose a theme',
54
+ 'переключить Build / Plan': 'switch Build / Plan',
55
+ 'полный доступ вкл/выкл': 'full access on/off',
56
+ 'сводка: проект, модель, токены, контекст': 'summary: project, model, tokens, context',
57
+ 'сохранить сессию в Markdown': 'save the session as Markdown',
58
+ 'проверить git, ripgrep, подключение к модели': 'check git, ripgrep, connection to the model',
59
+ 'выход': 'exit',
60
+ '[аргументы]': '[arguments]',
61
+ '# Правила для агента\n\n## Заметки\n- {0}\n': '# Rules for the agent\n\n## Notes\n- {0}\n',
62
+ '_Модель: {0}_': '_Model: {0}_',
63
+ '[на что смотреть]': '[what to look at]',
64
+ '[уточнения]': '[details]',
65
+ '[что тестировать]': '[what to test]',
66
+ '<ошибка или описание>': '<error or description>',
67
+ '<@файл или что объяснить>': '<@file or what to explain>',
68
+ '## Заметки': '## Notes',
69
+ '\n\n## Заметки\n': '\n\n## Notes\n',
70
+ '## 🧑 Вы': '## 🧑 You',
71
+ '<details><summary>результат</summary>': '<details><summary>result</summary>',
72
+ 'Понял контекст, продолжаю с того же места.': 'Got the context, continuing from the same place.',
73
+ 'затрагивает файлы вне папки проекта ({0})': 'touches files outside the project folder ({0})',
74
+ 'удаление файлов без возврата (rm -r / -f)': 'deletes files permanently (rm -r / -f)',
75
+ 'удаление файлов (rm)': 'deletes files (rm)',
76
+ 'удаление папки со всем содержимым': 'deletes a folder with everything in it',
77
+ 'удаление файлов (del)': 'deletes files (del)',
78
+ 'удаление файлов (Remove-Item)': 'deletes files (Remove-Item)',
79
+ 'очистка содержимого файлов': 'clears file contents',
80
+ 'форматирование диска': 'formats a disk',
81
+ 'запись на диск напрямую (dd)': 'writes to a disk directly (dd)',
82
+ 'запись на диск напрямую': 'writes to a disk directly',
83
+ 'git reset --hard: несохранённые изменения пропадут': 'git reset --hard: uncommitted changes will be lost',
84
+ 'git clean: удаление неотслеживаемых файлов': 'git clean: deletes untracked files',
85
+ 'принудительный git push: можно затереть чужие коммиты': "force git push: can overwrite other people's commits",
86
+ 'откат всех незакоммиченных изменений': 'discards all uncommitted changes',
87
+ 'удаление ветки без проверки': 'deletes a branch without checks',
88
+ 'скачивание и запуск скрипта из интернета': 'downloads and runs a script from the internet',
89
+ 'выполнение произвольного кода (Invoke-Expression)': 'runs arbitrary code (Invoke-Expression)',
90
+ 'выключение или перезагрузка компьютера': 'shuts down or restarts the computer',
91
+ 'изменение реестра Windows': 'changes the Windows registry',
92
+ 'изменение политики запуска скриптов': 'changes the script execution policy',
93
+ 'системная утилита, опасная для данных': 'system tool that is dangerous for data',
94
+ 'массовая смена прав доступа': 'changes permissions in bulk',
95
+ 'запуск с правами администратора': 'runs with administrator rights',
96
+ 'удаление данных из базы': 'deletes data from a database',
97
+ 'публикация пакета': 'publishes a package',
98
+ 'fork-бомба': 'fork bomb',
99
+ 'принудительное завершение процессов': 'force-kills processes',
100
+ 'перемещение или переименование файлов': 'moves or renames files',
101
+ 'перезапись файла через >': 'overwrites a file with >',
102
+ 'установка или удаление пакетов': 'installs or removes packages',
103
+ 'изменение истории или отправка в удалённый репозиторий': 'rewrites history or pushes to a remote',
104
+ 'обращение в интернет': 'accesses the internet',
105
+ 'удаление файлов': 'deletes files',
106
+ 'Запрос отклонён (400). Возможно, модель не поддерживает инструменты.': 'Request rejected (400). The model may not support tools.',
107
+ 'API-ключ не подходит (401). Поменяйте его: /connect': 'The API key is not valid (401). Change it: /connect',
108
+ 'На балансе провайдера закончились деньги (402).': 'The provider balance has run out (402).',
109
+ 'Нет доступа (403). Проверьте ключ и права на модель.': 'Access denied (403). Check the key and your access to the model.',
110
+ 'Модель или адрес не найдены (404). Адрес: {0}': 'Model or address not found (404). Address: {0}',
111
+ 'Слишком много запросов или исчерпан лимит (429). Подождите немного.': 'Too many requests or quota exceeded (429). Wait a little.',
112
+ 'Сервер провайдера ответил ошибкой {0}.': "The provider's server returned error {0}.",
113
+ 'Ошибка {0}.': 'Error {0}.',
114
+ 'Провайдер вернул ошибку: {0}': 'The provider returned an error: {0}',
115
+ 'Не удаётся подключиться к {0}: {1}': 'Cannot connect to {0}: {1}',
116
+ 'Соединение оборвалось посреди ответа. Напишите «продолжай».': 'The connection dropped in the middle of the answer. Type “continue”.',
117
+ 'таймаут': 'timeout',
118
+ 'нет соединения': 'no connection',
119
+ 'Провайдер слишком долго не отвечает (таймаут).': 'The provider takes too long to respond (timeout).',
120
+ 'лимит запросов': 'rate limit',
121
+ 'ошибка сервера {0}': 'server error {0}',
122
+ 'Папка уже существует: {0}': 'Folder already exists: {0}',
123
+ 'Git не установлен. Скачайте: https://git-scm.com': 'Git is not installed. Download: https://git-scm.com',
124
+ 'Клонирование заняло больше 10 минут и было остановлено.': 'Cloning took more than 10 minutes and was stopped.',
125
+ 'git clone завершился с ошибкой': 'git clone failed',
126
+ 'ANIX Router (локально)': 'ANIX Router (local)',
127
+ 'Ollama (локально)': 'Ollama (local)',
128
+ 'LM Studio (локально)': 'LM Studio (local)',
129
+ 'Свой сервер (OpenAI-совместимый)': 'Custom server (OpenAI-compatible)',
130
+ 'Новая сессия': 'New session',
131
+ '{0} строк': '{0} lines',
132
+ '{0} элементов': '{0} entries',
133
+ '{0} файлов': '{0} files',
134
+ ' · стоп по времени': ' · stopped by time limit',
135
+ '{0}{1} совпадений': '{0}{1} matches',
136
+ 'нет совпадений': 'no matches',
137
+ 'ANIX · персиковая': 'ANIX · peach',
138
+ 'Noir · чёрно-белая': 'Noir · black & white',
139
+ 'Думает': 'Thinking',
140
+ ' esc — стоп': ' esc — stop',
141
+ ' · ≈{0:.1f}k токенов': ' · ≈{0:.1f}k tokens',
142
+ ' · ≈{0} токенов': ' · ≈{0} tokens',
143
+ '🗜 История сжата: ~{0} → ~{1} токенов ({2})': '🗜 History compressed: ~{0} → ~{1} tokens ({2})',
144
+ 'Стоп': 'Stop',
145
+ 'Модель': 'Model',
146
+ 'Полный доступ': 'Full access',
147
+ 'Проект': 'Project',
148
+ 'Новая': 'New',
149
+ 'Сессии': 'Sessions',
150
+ 'Тема': 'Theme',
151
+ 'Помощь': 'Help',
152
+ 'Выход': 'Exit',
153
+ 'Опишите задачу: агент сам прочитает код, внесёт правки и запустит команды.\n': 'Describe a task: the agent reads the code, makes the changes and runs the commands itself.\n',
154
+ 'Tab: Build/Plan · Ctrl+O: модель · F1: все клавиши': 'Tab: Build/Plan · Ctrl+O: model · F1: all keys',
155
+ 'Ждёт разрешения: Enter / Esc': 'Waiting for approval: Enter / Esc',
156
+ 'Проект: {0}{1}': 'Project: {0}{1}',
157
+ 'старые шаги свёрнуты в сводку': 'old steps folded into a summary',
158
+ 'убраны старые выводы команд': 'old command outputs removed',
159
+ 'не git': 'not git',
160
+ 'ℹ Сводка\n': 'ℹ Summary\n',
161
+ 'Выполняет: {0}': 'Running: {0}',
162
+ '🔓 Полный доступ: агент правит файлы и запускает команды без вопросов': '🔓 Full access: the agent edits files and runs commands without asking',
163
+ '🔒 Агент снова спрашивает разрешение': '🔒 The agent asks for approval again',
164
+ 'модель не подключена · ctrl+o': 'no model connected · ctrl+o',
165
+ ' контекст ': ' context ',
166
+ 'Агент ещё работает. Esc — остановить.': 'The agent is still working. Esc to stop.',
167
+ 'Нет команды /{0}. Наберите / и посмотрите список.': 'No command /{0}. Type / to see the list.',
168
+ 'Сначала остановите агента (Esc).': 'Stop the agent first (Esc).',
169
+ 'Режим': 'Mode',
170
+ 'Токены': 'Tokens',
171
+ 'Сессия': 'Session',
172
+ '{0} · сообщений: {1}': '{0} · messages: {1}',
173
+ 'Свои команды': 'Own commands',
174
+ 'Сессия пока пустая.': 'The session is empty so far.',
175
+ '🩺 Проверка\n': '🩺 Check\n',
176
+ 'проект': 'project',
177
+ 'Сжимает историю': 'Compressing history',
178
+ 'Plan: агент только читает и планирует': 'Plan: the agent only reads and plans',
179
+ 'Build: агент может править код': 'Build: the agent can edit code',
180
+ '🔓 полный доступ': '🔓 full access',
181
+ '🔒 спрашивать': '🔒 ask first',
182
+ 'не подключена (/connect)': 'not connected (/connect)',
183
+ 'Контекст': 'Context',
184
+ '{0}% из ~{1}': '{0}% of ~{1}',
185
+ 'есть': 'yes',
186
+ 'нет (/init создаст)': 'no (/init creates it)',
187
+ 'нет': 'no',
188
+ 'не найден: https://git-scm.com (нужен для /commit, /review, клонирования)': 'not found: https://git-scm.com (needed for /commit, /review, cloning)',
189
+ 'есть, поиск быстрый': 'found, search is fast',
190
+ 'нет (необязательно, ускоряет поиск)': 'no (optional, makes search faster)',
191
+ 'нет, создайте: /init': 'no, create it: /init',
192
+ 'модель': 'model',
193
+ 'не подключена: /connect': 'not connected: /connect',
194
+ 'найден, статус уйдёт в Discord': 'found, status goes to Discord',
195
+ 'не запущен (необязательно)': 'not running (optional)',
196
+ 'Подключено: {0}': 'Connected: {0}',
197
+ '↺ Сессия загружена. Продолжайте с того места, где остановились.': '↺ Session loaded. Continue where you left off.',
198
+ 'Тема: {0}': 'Theme: {0}',
199
+ ' · свой': ' · own',
200
+ '📝 Записал в {0}: {1} (агент учтёт это в следующих ответах)': '📝 Saved to {0}: {1} (the agent will follow it from now on)',
201
+ 'восстановлено: {0}': 'restored: {0}',
202
+ 'удалены созданные: {0}': 'removed created files: {0}',
203
+ 'полный доступ': 'full access',
204
+ 'спрашивать разрешение': 'ask for approval',
205
+ '💾 Сессия сохранена: {0}': '💾 Session saved: {0}',
206
+ ' — не git-репозиторий': ' — not a git repository',
207
+ '{0} · сервер отвечает, моделей: {1}': '{0} · server responds, models: {1}',
208
+ 'Размышляет': 'Reasoning',
209
+ '⏹ Остановлено': '⏹ Stopped',
210
+ '⚠ Агент сейчас работает в {0}: это не папка проекта, а весь профиль или диск. Поиск будет медленным, а правки могут задеть что угодно. Выберите проект: Ctrl+P.': '⚠ The agent is working in {0}: this is not a project folder but your whole profile or disk. Search will be slow and changes could touch anything. Choose a project: Ctrl+P.',
211
+ '↶ Откатывать нечего: агент не правил файлы в этой сессии (команды в терминале не откатываются).': '↶ Nothing to undo: the agent did not change files in this session (terminal commands cannot be undone).',
212
+ '↷ Возвращать нечего: сначала /undo.': '↷ Nothing to redo: use /undo first.',
213
+ 'не установлен: pip install -e .': 'not installed: pip install -e .',
214
+ '🗜 Сжимать пока нечего.': '🗜 Nothing to compress yet.',
215
+ 'Пишет ответ': 'Writing the answer',
216
+ '. Команды в терминале не откатываются.': '. Terminal commands are not undone.',
217
+ '↷ Откаченные правки возвращены: ': '↷ Undone changes are back: ',
218
+ 'нет ответа': 'no answer',
219
+ '📎 Прикреплено: ': '📎 Attached: ',
220
+ '↶ Правки последнего ответа откачены, ': '↶ Changes from the last answer are undone, ',
221
+ 'Повтор {0}/{1} через {2:.0f}с: {3}': 'Retry {0}/{1} in {2:.0f}s: {3}',
222
+ '# ANIX Code\n\n| Клавиши | Что делают |\n|---|---|\n| `Enter` | отправить |\n| `Ctrl+J` | новая строка |\n| `↑` / `↓` | история запросов |\n| `Tab` | режим **Build** (правит код) / **Plan** (только читает и планирует) |\n| `Esc` | остановить агента |\n| `Ctrl+P` | выбрать проект (папку / репозиторий), клонировать с GitHub |\n| `F2` | полный доступ вкл/выкл (агент не спрашивает разрешения) |\n| `Ctrl+O` | модель и API-ключ |\n| `Ctrl+N` | новая сессия |\n| `Ctrl+S` | прошлые сессии |\n| `Ctrl+T` | выбрать тему |\n| `Ctrl+Q` | выход |\n\nБыстрый ввод:\n- `/` — список команд с подсказками (↑↓, Tab — дописать, Enter — выполнить)\n- `!команда` — выполнить команду в терминале самому; агент увидит вывод\n- `# текст` — записать правило в `AGENTS.md` («# используй pnpm, а не npm»)\n- `Shift+Tab` или `Tab` — Build / Plan\n\nЕщё:\n- `/init` — агент изучит проект и напишет `AGENTS.md` с правилами для себя\n- `@путь` в запросе — прикрепить файл или папку (после `@` появятся подсказки: ↑↓, Enter/Tab)\n- `/undo` — откатить правки файлов из последнего ответа агента (можно несколько раз подряд)\n- `/compact` — сжать историю вручную (обычно это происходит само при заполнении контекста)\n- `/project` — выбрать проект; клик по пути в шапке делает то же самое\n- `/connect`, `/new`, `/sessions`, `/theme`, `/help`, `/exit`\n\nВнизу справа видно, на сколько заполнен контекст модели. При 80% история сжимается автоматически.\nПри сбоях сети и лимитах запросов агент сам повторяет запрос до 4 раз.\nКогда агент хочет изменить файл или выполнить команду, над полем ввода появляется строка:\n`Enter` — разрешить, `Esc` — отклонить, текст + `Enter` — отклонить и объяснить, как надо.\nОпасные команды (удаление, `git push --force`, форматирование…) подсвечиваются красным.\n**Полный доступ** (`F2` или клик внизу справа): агент работает без вопросов.\n\nКлик по карточке действия показывает diff или вывод команды.\nПравила проекта для агента можно написать в `AGENTS.md` в корне проекта.\n': "# ANIX Code\n\n| Keys | What they do |\n|---|---|\n| `Enter` | send |\n| `Ctrl+J` | new line |\n| `↑` / `↓` | prompt history |\n| `Tab` | **Build** mode (edits code) / **Plan** mode (only reads and plans) |\n| `Esc` | stop the agent |\n| `Ctrl+P` | choose a project (folder / repository), clone from GitHub |\n| `F2` | full access on/off (the agent does not ask for approval) |\n| `Ctrl+O` | model and API key |\n| `Ctrl+N` | new session |\n| `Ctrl+S` | past sessions |\n| `Ctrl+T` | choose a theme |\n| `Ctrl+Q` | exit |\n\nQuick input:\n- `/` — command list with hints (↑↓, Tab to complete, Enter to run)\n- `!command` — run a command in the terminal yourself; the agent sees the output\n- `# text` — save a rule to `AGENTS.md` (“# use pnpm, not npm”)\n- `Shift+Tab` or `Tab` — Build / Plan\n\nMore:\n- `/init` — the agent studies the project and writes `AGENTS.md` with rules for itself\n- `@path` in a prompt — attach a file or folder (hints appear after `@`: ↑↓, Enter/Tab)\n- `/undo` — undo file changes from the agent's last answer (works several times in a row)\n- `/compact` — compress the history manually (usually it happens automatically when the context fills up)\n- `/project` — choose a project; clicking the path in the header does the same\n- `/connect`, `/new`, `/sessions`, `/theme`, `/help`, `/exit`\n\nThe bottom right shows how full the model's context is. At 80% the history is compressed automatically.\nOn network failures and rate limits the agent retries the request up to 4 times.\nWhen the agent wants to change a file or run a command, a line appears above the input:\n`Enter` — allow, `Esc` — deny, text + `Enter` — deny and explain what to do instead.\nDangerous commands (deleting, `git push --force`, formatting…) are highlighted in red.\n**Full access** (`F2` or click at the bottom right): the agent works without asking.\n\nClicking an action card shows the diff or the command output.\nProject rules for the agent go into `AGENTS.md` in the project root.\n",
223
+ '## Свои команды\n\nПоложите Markdown-файл в `.anixcode/commands/имя.md` (для проекта) или в папку настроек\n`commands/имя.md` (для всех проектов). Текст файла станет запросом агенту, `$ARGUMENTS` заменится\nна всё, что написано после команды, `$1`, `$2` — на отдельные слова. Описание для подсказок:\n\n```markdown\n---\ndescription: прогнать линтер и всё починить\n---\nRun the linter for $ARGUMENTS and fix every warning.\n```\n': '## Own commands\n\nPut a Markdown file into `.anixcode/commands/name.md` (this project) or into the settings folder\n`commands/name.md` (all projects). The file text becomes a prompt for the agent, `$ARGUMENTS` is replaced\nwith everything typed after the command, `$1`, `$2` with single words. Description for the hints:\n\n```markdown\n---\ndescription: run the linter and fix everything\n---\nRun the linter for $ARGUMENTS and fix every warning.\n```\n\n',
224
+ 'Отмена': 'Cancel',
225
+ 'Проверяю…': 'Checking…',
226
+ 'сохранён: {0}': 'saved: {0}',
227
+ 'Где взять ключ: {0}': 'Get a key: {0}',
228
+ 'Загружаю список моделей…': 'Loading the model list…',
229
+ 'Моделей: {0}. Выберите стрелками и Enter.': 'Models: {0}. Pick with the arrows and Enter.',
230
+ 'Закрыть': 'Close',
231
+ 'Найдено: {0}': 'Found: {0}',
232
+ 'Клонирую в {0}…': 'Cloning into {0}…',
233
+ 'не обязателен': 'optional',
234
+ 'Ключ не нужен': 'No key needed',
235
+ 'Провайдер «{0}» добавлен. Выберите модель.': 'Provider “{0}” added. Choose a model.',
236
+ 'Сервер не вернул список. Впишите название модели вручную.': 'The server returned no list. Type the model name manually.',
237
+ 'Укажите адрес сервера, начиная с http:// или https://': 'Enter the server address starting with http:// or https://',
238
+ 'Вставьте API-ключ.': 'Paste the API key.',
239
+ 'Укажите модель или нажмите «Список моделей».': 'Enter a model or press “Model list”.',
240
+ ' *(свой)*': ' *(own)*',
241
+ '| Команда | Что делает |': '| Command | What it does |',
242
+ 'Не нашёл репозиториев в Desktop, Documents, Projects и похожих папках. Используйте «Обзор».': 'No repositories found in Desktop, Documents, Projects and similar folders. Use “Browse”.',
243
+ 'Свой провайдер': 'Own provider',
244
+ 'Подойдёт любой сервер с OpenAI-совместимым API: свой роутер, прокси, облако.': 'Any server with an OpenAI-compatible API works: your own router, a proxy, a cloud.',
245
+ 'Название': 'Name',
246
+ 'Адрес API (обычно заканчивается на /v1)': 'API address (usually ends with /v1)',
247
+ 'API-ключ (если нужен)': 'API key (if needed)',
248
+ 'Адрес должен начинаться с http:// или https://': 'The address must start with http:// or https://',
249
+ '✓ Работает, моделей: {0}': '✓ Works, models: {0}',
250
+ '✓ Сервер отвечает (список моделей пуст, название модели впишете вручную)': '✓ The server responds (the model list is empty, type the model name manually)',
251
+ 'Введите название.': 'Enter a name.',
252
+ 'Подключение модели': 'Connect a model',
253
+ 'Провайдер': 'Provider',
254
+ 'API-ключ': 'API key',
255
+ 'Адрес сервера': 'Server address',
256
+ '↑↓ — посмотреть · Enter — выбрать · Esc — отмена': '↑↓ — preview · Enter — choose · Esc — cancel',
257
+ 'Сессии в этой папке': 'Sessions in this folder',
258
+ 'Enter — открыть, Esc — закрыть': 'Enter — open, Esc — close',
259
+ 'Esc — закрыть': 'Esc — close',
260
+ 'Проект: в какой папке работать': 'Project: which folder to work in',
261
+ 'Кликните папку в дереве (она раскроется и подставится в строку) и нажмите «Открыть». Ссылка https://github.com/… — склонировать. Esc — отмена.': 'Click a folder in the tree (it expands and fills the line) and press “Open”. A https://github.com/… link is cloned. Esc to cancel.',
262
+ 'например: Мой ANIX': 'for example: My ANIX',
263
+ 'оставьте пустым, если ключ не нужен': 'leave empty if no key is needed',
264
+ 'Добавить': 'Add',
265
+ 'Проверить': 'Check',
266
+ '+ Свой': '+ Own',
267
+ 'Удалить': 'Delete',
268
+ 'Список моделей': 'Model list',
269
+ 'Сохранить': 'Save',
270
+ 'Пока пусто.': 'Empty so far.',
271
+ 'Открыть': 'Open',
272
+ 'Недавние': 'Recent',
273
+ 'Репозитории': 'Repositories',
274
+ 'Обзор': 'Browse',
275
+ 'название модели': 'model name',
276
+ 'Путь к папке или ссылка на git-репозиторий': 'Folder path or git repository link',
277
+ 'Ищу git-репозитории…': 'Looking for git repositories…',
278
+ 'Пока пусто: здесь появятся папки, которые вы открывали.': 'Empty so far: folders you open will appear here.',
279
+ '🏠 Домой': '🏠 Home',
280
+ '\n## Команды\n\n': '\n## Commands\n\n',
281
+ ' Разрешить ⏎ ': ' Allow ⏎ ',
282
+ ' Отклонить esc ': ' Deny esc ',
283
+ ' Полный доступ ': ' Full access ',
284
+ 'Изменить': 'Edit',
285
+ 'Выполнить': 'Run',
286
+ '\nEnter — разрешить · Esc — отклонить · напишите текст и Enter — отклонить с пояснением': '\nEnter — allow · Esc — deny · type text and Enter — deny with an explanation',
287
+ 'ждёт разрешения': 'waiting for approval',
288
+ '💭 Размышления (свернуть)\n{0}': '💭 Reasoning (collapse)\n{0}',
289
+ '💭 Размышления · {0} символов (клик, чтобы развернуть)': '💭 Reasoning · {0} characters (click to expand)',
290
+ '\n… ещё {0} строк': '\n… {0} more lines',
291
+ 'язык интерфейса: русский / English': 'interface language: Русский / English',
292
+ 'Язык: {0}. Перезапустите ANIX Code, чтобы применить.': 'Language: {0}. Restart ANIX Code to apply.',
293
+ }
anixcode/llm.py ADDED
@@ -0,0 +1,258 @@
1
+ """OpenAI-compatible chat client with streaming and tool calls."""
2
+ from __future__ import annotations
3
+ from .i18n import tr
4
+
5
+ import json
6
+ import uuid
7
+ from collections.abc import AsyncIterator
8
+ from dataclasses import dataclass, field
9
+ from typing import Any
10
+
11
+
12
+ class LLMError(Exception):
13
+ """A readable error for the user (bad key, no money, model not found, …)."""
14
+
15
+ def __init__(self, message: str, status: int | None = None, raw: str = "") -> None:
16
+ super().__init__(message)
17
+ self.status = status
18
+ self.raw = raw
19
+
20
+
21
+ RETRY_STATUSES = frozenset({408, 409, 425, 429, 500, 502, 503, 504, 520, 522, 524, 529})
22
+ MAX_ATTEMPTS = 5
23
+ _OVERFLOW_HINTS = ("context length", "context_length", "maximum context", "context window", "too many tokens",
24
+ "prompt is too long", "reduce the length", "token limit", "input is too long", "too long")
25
+
26
+
27
+ def retry_delay(attempt: int, retry_after: str | None = None) -> float:
28
+ """Seconds to wait before retry number ``attempt`` (0-based): honours Retry-After, else 1.5, 3, 6, 12 s."""
29
+ if retry_after:
30
+ try:
31
+ return min(30.0, max(0.5, float(retry_after)))
32
+ except ValueError:
33
+ pass
34
+ return min(30.0, 1.5 * 2 ** attempt)
35
+
36
+
37
+ def is_context_overflow(error: LLMError) -> bool:
38
+ text = f"{error} {error.raw}".lower()
39
+ return error.status in (400, 413, 422) and any(h in text for h in _OVERFLOW_HINTS)
40
+
41
+
42
+ @dataclass
43
+ class Usage:
44
+ prompt: int = 0
45
+ completion: int = 0
46
+
47
+
48
+ @dataclass
49
+ class TextDelta:
50
+ text: str
51
+
52
+
53
+ @dataclass
54
+ class ReasoningDelta:
55
+ text: str
56
+
57
+
58
+ @dataclass
59
+ class Retrying:
60
+ attempt: int
61
+ max_attempts: int
62
+ delay: float
63
+ reason: str
64
+
65
+
66
+ @dataclass
67
+ class ToolCall:
68
+ id: str
69
+ name: str
70
+ arguments: str # raw JSON text as the model wrote it
71
+
72
+ def parse_args(self) -> dict[str, Any]:
73
+ if not self.arguments.strip():
74
+ return {}
75
+ data = json.loads(self.arguments)
76
+ if not isinstance(data, dict):
77
+ raise ValueError("arguments must be a JSON object")
78
+ return data
79
+
80
+
81
+ @dataclass
82
+ class Completion:
83
+ text: str = ""
84
+ reasoning: str = ""
85
+ tool_calls: list[ToolCall] = field(default_factory=list)
86
+ finish_reason: str | None = None
87
+ usage: Usage | None = None
88
+
89
+
90
+ class ChatStreamParser:
91
+ """Accumulates an SSE chat stream (OpenAI format, DeepSeek reasoning, split tool calls)."""
92
+
93
+ def __init__(self) -> None:
94
+ self._text: list[str] = []
95
+ self._reasoning: list[str] = []
96
+ self._calls: dict[int, dict[str, str]] = {}
97
+ self._finish: str | None = None
98
+ self._usage: Usage | None = None
99
+
100
+ def feed_line(self, line: str) -> list[TextDelta | ReasoningDelta]:
101
+ line = line.strip()
102
+ if not line.startswith("data:"):
103
+ return []
104
+ payload = line[5:].strip()
105
+ if payload == "[DONE]":
106
+ return []
107
+ try:
108
+ obj = json.loads(payload)
109
+ except ValueError:
110
+ return []
111
+ if not isinstance(obj, dict):
112
+ return []
113
+ if obj.get("error"):
114
+ err = obj["error"]
115
+ msg = err.get("message", err) if isinstance(err, dict) else err
116
+ raise LLMError(tr('Провайдер вернул ошибку: {0}', msg), raw=str(msg))
117
+ usage = obj.get("usage")
118
+ if isinstance(usage, dict):
119
+ self._usage = Usage(int(usage.get("prompt_tokens") or 0), int(usage.get("completion_tokens") or 0))
120
+ events: list[TextDelta | ReasoningDelta] = []
121
+ for choice in obj.get("choices") or []:
122
+ if not isinstance(choice, dict):
123
+ continue
124
+ delta = choice.get("delta") or {}
125
+ reasoning = delta.get("reasoning_content") or delta.get("reasoning")
126
+ if isinstance(reasoning, str) and reasoning:
127
+ self._reasoning.append(reasoning)
128
+ events.append(ReasoningDelta(reasoning))
129
+ content = delta.get("content")
130
+ if isinstance(content, str) and content:
131
+ self._text.append(content)
132
+ events.append(TextDelta(content))
133
+ for tc in delta.get("tool_calls") or []:
134
+ slot = self._calls.setdefault(int(tc.get("index", len(self._calls))), {"id": "", "name": "", "args": ""})
135
+ if tc.get("id"):
136
+ slot["id"] = tc["id"]
137
+ fn = tc.get("function") or {}
138
+ if fn.get("name") and not slot["name"]:
139
+ slot["name"] = fn["name"]
140
+ args = fn.get("arguments")
141
+ if isinstance(args, dict):
142
+ slot["args"] = json.dumps(args)
143
+ elif isinstance(args, str):
144
+ slot["args"] += args
145
+ if choice.get("finish_reason"):
146
+ self._finish = choice["finish_reason"]
147
+ return events
148
+
149
+ def result(self) -> Completion:
150
+ calls = [
151
+ ToolCall(slot["id"] or f"call_{uuid.uuid4().hex[:12]}", slot["name"], slot["args"])
152
+ for _, slot in sorted(self._calls.items())
153
+ if slot["name"]
154
+ ]
155
+ return Completion("".join(self._text), "".join(self._reasoning), calls, self._finish, self._usage)
156
+
157
+
158
+ def friendly_error(status: int, body: str, base_url: str) -> str:
159
+ detail = body.strip()
160
+ try:
161
+ data = json.loads(body)
162
+ err = data.get("error", data) if isinstance(data, dict) else data
163
+ detail = err.get("message", str(err)) if isinstance(err, dict) else str(err)
164
+ except ValueError:
165
+ pass
166
+ detail = detail[:300]
167
+ hints = {
168
+ 400: tr("Запрос отклонён (400). Возможно, модель не поддерживает инструменты."),
169
+ 401: tr("API-ключ не подходит (401). Поменяйте его: /connect"),
170
+ 402: tr("На балансе провайдера закончились деньги (402)."),
171
+ 403: tr("Нет доступа (403). Проверьте ключ и права на модель."),
172
+ 404: tr('Модель или адрес не найдены (404). Адрес: {0}', base_url),
173
+ 429: tr("Слишком много запросов или исчерпан лимит (429). Подождите немного."),
174
+ }
175
+ head = hints.get(status) or (tr('Сервер провайдера ответил ошибкой {0}.', status) if status >= 500 else tr('Ошибка {0}.', status))
176
+ return f"{head}\n{detail}" if detail else head
177
+
178
+
179
+ class LLMClient:
180
+ """Talks to /chat/completions. Needs ``httpx``."""
181
+
182
+ def __init__(self, base_url: str, api_key: str = "", timeout: float = 300.0) -> None:
183
+ import httpx
184
+
185
+ self._httpx = httpx
186
+ self.base_url = base_url.rstrip("/") + "/"
187
+ headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}
188
+ headers["User-Agent"] = "anixcode"
189
+ self._http = httpx.AsyncClient(
190
+ base_url=self.base_url, headers=headers,
191
+ timeout=httpx.Timeout(connect=15.0, read=timeout, write=60.0, pool=15.0),
192
+ )
193
+
194
+ async def aclose(self) -> None:
195
+ await self._http.aclose()
196
+
197
+ async def list_models(self) -> list[str]:
198
+ try:
199
+ r = await self._http.get("models")
200
+ except self._httpx.HTTPError as e:
201
+ raise LLMError(tr('Не удаётся подключиться к {0}: {1}', self.base_url, e)) from e
202
+ if r.status_code >= 400:
203
+ raise LLMError(friendly_error(r.status_code, r.text, self.base_url))
204
+ try:
205
+ data = r.json().get("data", [])
206
+ except (ValueError, AttributeError):
207
+ return []
208
+ return sorted({m["id"] for m in data if isinstance(m, dict) and m.get("id")})
209
+
210
+ async def stream_chat(self, model: str, messages: list[dict[str, Any]],
211
+ tools: list[dict[str, Any]] | None = None
212
+ ) -> AsyncIterator[TextDelta | ReasoningDelta | Retrying | Completion]:
213
+ """Stream one completion. Retries (with backoff) on rate limits, server errors and network
214
+ failures, as long as nothing has been streamed yet."""
215
+ import asyncio
216
+
217
+ body: dict[str, Any] = {"model": model, "messages": messages, "stream": True,
218
+ "stream_options": {"include_usage": True}}
219
+ if tools:
220
+ body["tools"] = tools
221
+ attempt = 0
222
+ while True:
223
+ parser = ChatStreamParser()
224
+ started = False
225
+ retry: tuple[float, str] | None = None
226
+ try:
227
+ async with self._http.stream("POST", "chat/completions", json=body) as r:
228
+ if r.status_code >= 400:
229
+ text = (await r.aread()).decode("utf-8", errors="replace")
230
+ if r.status_code == 400 and "stream_options" in text and "stream_options" in body:
231
+ body.pop("stream_options") # some servers don't know this option
232
+ continue
233
+ if r.status_code in RETRY_STATUSES and attempt < MAX_ATTEMPTS - 1:
234
+ retry = (retry_delay(attempt, r.headers.get("retry-after")),
235
+ tr("лимит запросов") if r.status_code == 429 else tr('ошибка сервера {0}', r.status_code))
236
+ else:
237
+ raise LLMError(friendly_error(r.status_code, text, self.base_url), r.status_code, text)
238
+ else:
239
+ async for line in r.aiter_lines():
240
+ for event in parser.feed_line(line):
241
+ started = True
242
+ yield event
243
+ except self._httpx.HTTPError as e:
244
+ timeout = isinstance(e, self._httpx.TimeoutException)
245
+ if started:
246
+ raise LLMError(tr("Соединение оборвалось посреди ответа. Напишите «продолжай».")) from e
247
+ if attempt >= MAX_ATTEMPTS - 1:
248
+ raise LLMError(tr("Провайдер слишком долго не отвечает (таймаут).") if timeout
249
+ else tr('Не удаётся подключиться к {0}: {1}', self.base_url, e)) from e
250
+ retry = (retry_delay(attempt), tr("таймаут") if timeout else tr("нет соединения"))
251
+ if retry is not None:
252
+ delay, reason = retry
253
+ attempt += 1
254
+ yield Retrying(attempt, MAX_ATTEMPTS - 1, delay, reason)
255
+ await asyncio.sleep(delay)
256
+ continue
257
+ yield parser.result()
258
+ return