spiritcode 0.1.1__tar.gz → 0.2.0__tar.gz

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.
Files changed (53) hide show
  1. {spiritcode-0.1.1 → spiritcode-0.2.0}/PKG-INFO +21 -3
  2. {spiritcode-0.1.1 → spiritcode-0.2.0}/README.md +20 -2
  3. spiritcode-0.2.0/images/icon.png +0 -0
  4. {spiritcode-0.1.1 → spiritcode-0.2.0}/pyproject.toml +3 -2
  5. {spiritcode-0.1.1 → spiritcode-0.2.0}/src/spiritcode/__init__.py +1 -1
  6. spiritcode-0.2.0/src/spiritcode/cli.py +330 -0
  7. spiritcode-0.2.0/src/spiritcode/commands/__init__.py +1 -0
  8. spiritcode-0.2.0/src/spiritcode/commands/account.py +53 -0
  9. spiritcode-0.2.0/src/spiritcode/commands/chat.py +26 -0
  10. spiritcode-0.2.0/src/spiritcode/commands/diagnostics.py +68 -0
  11. spiritcode-0.2.0/src/spiritcode/commands/files.py +19 -0
  12. spiritcode-0.2.0/src/spiritcode/commands/model.py +102 -0
  13. spiritcode-0.2.0/src/spiritcode/commands/sessions.py +44 -0
  14. spiritcode-0.2.0/src/spiritcode/constants.py +62 -0
  15. spiritcode-0.2.0/src/spiritcode/core/__init__.py +1 -0
  16. {spiritcode-0.1.1/src/spiritcode → spiritcode-0.2.0/src/spiritcode/core}/agent.py +47 -21
  17. {spiritcode-0.1.1/src/spiritcode → spiritcode-0.2.0/src/spiritcode/core}/api.py +7 -33
  18. {spiritcode-0.1.1/src/spiritcode → spiritcode-0.2.0/src/spiritcode/core}/config.py +21 -56
  19. spiritcode-0.2.0/src/spiritcode/core/context.py +73 -0
  20. spiritcode-0.2.0/src/spiritcode/core/models.py +37 -0
  21. {spiritcode-0.1.1/src/spiritcode → spiritcode-0.2.0/src/spiritcode/core}/permissions.py +25 -3
  22. {spiritcode-0.1.1/src/spiritcode → spiritcode-0.2.0/src/spiritcode/core}/store.py +6 -2
  23. spiritcode-0.2.0/src/spiritcode/prompts.py +24 -0
  24. spiritcode-0.2.0/src/spiritcode/sanitize.py +13 -0
  25. spiritcode-0.2.0/src/spiritcode/tools/__init__.py +1 -0
  26. spiritcode-0.1.1/src/spiritcode/tools.py → spiritcode-0.2.0/src/spiritcode/tools/executor.py +210 -183
  27. spiritcode-0.2.0/src/spiritcode/tools/files.py +73 -0
  28. spiritcode-0.2.0/src/spiritcode/tools/replacements.py +117 -0
  29. spiritcode-0.2.0/src/spiritcode/tools/schemas.py +97 -0
  30. spiritcode-0.2.0/src/spiritcode/types.py +8 -0
  31. spiritcode-0.2.0/src/spiritcode/ui/__init__.py +1 -0
  32. {spiritcode-0.1.1/src/spiritcode → spiritcode-0.2.0/src/spiritcode/ui}/commands.py +2 -0
  33. {spiritcode-0.1.1/src/spiritcode → spiritcode-0.2.0/src/spiritcode/ui}/display.py +6 -1
  34. spiritcode-0.1.1/src/spiritcode/ui.py → spiritcode-0.2.0/src/spiritcode/ui/interface.py +371 -91
  35. {spiritcode-0.1.1/src/spiritcode → spiritcode-0.2.0/src/spiritcode/ui}/keyboard.py +14 -0
  36. {spiritcode-0.1.1 → spiritcode-0.2.0}/tests/test_agent.py +66 -5
  37. {spiritcode-0.1.1 → spiritcode-0.2.0}/tests/test_api.py +4 -4
  38. {spiritcode-0.1.1 → spiritcode-0.2.0}/tests/test_cli.py +70 -16
  39. {spiritcode-0.1.1 → spiritcode-0.2.0}/tests/test_config_store.py +13 -13
  40. {spiritcode-0.1.1 → spiritcode-0.2.0}/tests/test_keyboard.py +3 -3
  41. {spiritcode-0.1.1 → spiritcode-0.2.0}/tests/test_permissions.py +3 -3
  42. {spiritcode-0.1.1 → spiritcode-0.2.0}/tests/test_tools.py +118 -4
  43. {spiritcode-0.1.1 → spiritcode-0.2.0}/tests/test_ui.py +153 -12
  44. spiritcode-0.1.1/src/spiritcode/cli.py +0 -461
  45. spiritcode-0.1.1/src/spiritcode/context.py +0 -87
  46. {spiritcode-0.1.1 → spiritcode-0.2.0}/.gitignore +0 -0
  47. {spiritcode-0.1.1 → spiritcode-0.2.0/docs}/SERVER_CONTRACT.md +0 -0
  48. /spiritcode-0.1.1/image.png → /spiritcode-0.2.0/images/cli.png +0 -0
  49. {spiritcode-0.1.1 → spiritcode-0.2.0}/scripts/check_install.py +0 -0
  50. {spiritcode-0.1.1 → spiritcode-0.2.0}/scripts/publish.py +0 -0
  51. {spiritcode-0.1.1 → spiritcode-0.2.0}/src/spiritcode/__main__.py +0 -0
  52. {spiritcode-0.1.1/src/spiritcode → spiritcode-0.2.0/src/spiritcode/core}/credentials.py +0 -0
  53. {spiritcode-0.1.1 → spiritcode-0.2.0}/tests/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: spiritcode
3
- Version: 0.1.1
3
+ Version: 0.2.0
4
4
  Summary: Терминальный кодинг-агент для SpiritLM
5
5
  Keywords: ai,coding-agent,spiritlm,terminal
6
6
  Classifier: Development Status :: 3 - Alpha
@@ -26,7 +26,7 @@ Description-Content-Type: text/markdown
26
26
 
27
27
  Терминальный кодинг-агент для SpiritLM. Python 3.12+, Linux, macOS и Windows.
28
28
 
29
- ![Интерфейс SpiritCode в терминале](image.png)
29
+ ![Интерфейс SpiritCode в терминале](images/cli.png)
30
30
 
31
31
  ## Установка
32
32
 
@@ -38,7 +38,7 @@ sprt
38
38
  При первом запуске введите API-ключ SpiritLM, затем выберите модель через `/model`.
39
39
  `spiritcode` и `python -m spiritcode` — альтернативные способы запуска.
40
40
 
41
- По умолчанию используется `https://spiritlm.netlify.app`. Для локальной разработки
41
+ По умолчанию используется `https://spiritlm.ru`. Для локальной разработки
42
42
  запускайте `NODE_ENV=development sprt` (также поддерживается `dev`) — API будет
43
43
  доступен по `http://localhost:3000`. Явный адрес в `--base-url`, `SPIRITLM_BASE_URL`
44
44
  или `config.toml` имеет приоритет над автоматическим выбором.
@@ -64,6 +64,9 @@ sprt
64
64
  | --- | --- |
65
65
  | `/help` | Команды и сочетания клавиш |
66
66
  | `/model [id]` | Поиск и смена модели |
67
+ | `/system` | Показать дополнительный системный промпт |
68
+ | `/system <текст>` | Задать дополнительный системный промпт |
69
+ | `/system --reset` | Сбросить дополнительный системный промпт |
67
70
  | `/context` | Контекст, токены и диагностика сессии |
68
71
  | `/profile` | Профиль SpiritLM |
69
72
  | `/balance` | Баланс аккаунта |
@@ -79,11 +82,26 @@ sprt
79
82
  | `/exit` | Выход |
80
83
  | `@путь` или `@"путь с пробелами"` | Прикрепить файл |
81
84
 
85
+ Настройка `/system` сохраняется для всех проектов. Указанный текст дополняет
86
+ встроенные инструкции SpiritCode и применяется со следующего сообщения.
87
+
88
+ Корневой `AGENTS.md` входит в системный контекст. Вложенные инструкции загружаются
89
+ по целевому пути перед записью файлов. Связанные точечные замены агент может
90
+ применить одним пакетом, который `/undo` отменяет как отдельную группу.
91
+
92
+ Во время ответа можно продолжать ввод. Enter ставит сообщение в очередь, и
93
+ SpiritCode обрабатывает очередь по порядку. Ожидающие сообщения видны в чате
94
+ серым цветом. Жёлтая точка отмечает начало обработки. Ctrl+C очищает черновик,
95
+ а при пустой строке прерывает активную операцию.
96
+
82
97
  ## Разрешения
83
98
 
84
99
  `/permissions` открывает меню: стрелки выбирают режим, Space переключает чекбокс,
85
100
  Enter сохраняет, Esc отменяет. Настройки сохраняются для всех проектов.
86
101
 
102
+ В запросе разрешения выберите «Да» или «Нет» мышью либо стрелками или Tab.
103
+ Enter подтверждает выбор, Esc отклоняет действие. По умолчанию выбрано «Нет».
104
+
87
105
  - **Стандартная защита** (по умолчанию): чтение, поиск и известные проверки проекта
88
106
  выполняются автоматически. Git, удаление, перезапись, системные изменения,
89
107
  составные и непрозрачные команды требуют разрешения.
@@ -2,7 +2,7 @@
2
2
 
3
3
  Терминальный кодинг-агент для SpiritLM. Python 3.12+, Linux, macOS и Windows.
4
4
 
5
- ![Интерфейс SpiritCode в терминале](image.png)
5
+ ![Интерфейс SpiritCode в терминале](images/cli.png)
6
6
 
7
7
  ## Установка
8
8
 
@@ -14,7 +14,7 @@ sprt
14
14
  При первом запуске введите API-ключ SpiritLM, затем выберите модель через `/model`.
15
15
  `spiritcode` и `python -m spiritcode` — альтернативные способы запуска.
16
16
 
17
- По умолчанию используется `https://spiritlm.netlify.app`. Для локальной разработки
17
+ По умолчанию используется `https://spiritlm.ru`. Для локальной разработки
18
18
  запускайте `NODE_ENV=development sprt` (также поддерживается `dev`) — API будет
19
19
  доступен по `http://localhost:3000`. Явный адрес в `--base-url`, `SPIRITLM_BASE_URL`
20
20
  или `config.toml` имеет приоритет над автоматическим выбором.
@@ -40,6 +40,9 @@ sprt
40
40
  | --- | --- |
41
41
  | `/help` | Команды и сочетания клавиш |
42
42
  | `/model [id]` | Поиск и смена модели |
43
+ | `/system` | Показать дополнительный системный промпт |
44
+ | `/system <текст>` | Задать дополнительный системный промпт |
45
+ | `/system --reset` | Сбросить дополнительный системный промпт |
43
46
  | `/context` | Контекст, токены и диагностика сессии |
44
47
  | `/profile` | Профиль SpiritLM |
45
48
  | `/balance` | Баланс аккаунта |
@@ -55,11 +58,26 @@ sprt
55
58
  | `/exit` | Выход |
56
59
  | `@путь` или `@"путь с пробелами"` | Прикрепить файл |
57
60
 
61
+ Настройка `/system` сохраняется для всех проектов. Указанный текст дополняет
62
+ встроенные инструкции SpiritCode и применяется со следующего сообщения.
63
+
64
+ Корневой `AGENTS.md` входит в системный контекст. Вложенные инструкции загружаются
65
+ по целевому пути перед записью файлов. Связанные точечные замены агент может
66
+ применить одним пакетом, который `/undo` отменяет как отдельную группу.
67
+
68
+ Во время ответа можно продолжать ввод. Enter ставит сообщение в очередь, и
69
+ SpiritCode обрабатывает очередь по порядку. Ожидающие сообщения видны в чате
70
+ серым цветом. Жёлтая точка отмечает начало обработки. Ctrl+C очищает черновик,
71
+ а при пустой строке прерывает активную операцию.
72
+
58
73
  ## Разрешения
59
74
 
60
75
  `/permissions` открывает меню: стрелки выбирают режим, Space переключает чекбокс,
61
76
  Enter сохраняет, Esc отменяет. Настройки сохраняются для всех проектов.
62
77
 
78
+ В запросе разрешения выберите «Да» или «Нет» мышью либо стрелками или Tab.
79
+ Enter подтверждает выбор, Esc отклоняет действие. По умолчанию выбрано «Нет».
80
+
63
81
  - **Стандартная защита** (по умолчанию): чтение, поиск и известные проверки проекта
64
82
  выполняются автоматически. Git, удаление, перезапись, системные изменения,
65
83
  составные и непрозрачные команды требуют разрешения.
Binary file
@@ -50,8 +50,9 @@ include = [
50
50
  "/scripts/check_install.py",
51
51
  "/scripts/publish.py",
52
52
  "/README.md",
53
- "/image.png",
54
- "/SERVER_CONTRACT.md",
53
+ "/images/cli.png",
54
+ "/images/icon.png",
55
+ "/docs/SERVER_CONTRACT.md",
55
56
  "/pyproject.toml",
56
57
  ]
57
58
 
@@ -1,3 +1,3 @@
1
1
  """SpiritCode: coding agent for SpiritLM."""
2
2
 
3
- __version__ = "0.1.1"
3
+ __version__ = "0.2.0"
@@ -0,0 +1,330 @@
1
+ import argparse
2
+ import asyncio
3
+ import os
4
+ import signal
5
+ from collections.abc import Coroutine
6
+ from datetime import UTC, datetime
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from spiritcode import __version__
11
+ from spiritcode.commands.account import account, load_account_label
12
+ from spiritcode.commands.chat import Chat
13
+ from spiritcode.commands.diagnostics import show_context
14
+ from spiritcode.commands.files import show_diff, undo
15
+ from spiritcode.commands.model import (
16
+ apply_model,
17
+ choose_model,
18
+ model_rows,
19
+ resolve_model,
20
+ set_model_label,
21
+ )
22
+ from spiritcode.commands.sessions import replace_session, show_sessions
23
+ from spiritcode.core.agent import Agent
24
+ from spiritcode.core.api import ApiError, Client
25
+ from spiritcode.core.config import Settings
26
+ from spiritcode.core.context import project_root
27
+ from spiritcode.core.credentials import Credentials
28
+ from spiritcode.core.store import Store, new_session
29
+ from spiritcode.tools.executor import Tools
30
+ from spiritcode.ui.commands import help_text
31
+ from spiritcode.ui.interface import UI
32
+
33
+
34
+ class RussianParser(argparse.ArgumentParser):
35
+ def __init__(self, **kwargs: Any) -> None:
36
+ kwargs["add_help"] = False
37
+ super().__init__(**kwargs)
38
+ self._positionals.title = "Команды"
39
+ self._optionals.title = "Параметры"
40
+ self.add_argument("-h", "--help", action="help", help="Показать справку и выйти")
41
+
42
+
43
+ async def cancellable[T](operation: Coroutine[Any, Any, T], ui: UI) -> T | None:
44
+ task = asyncio.create_task(operation)
45
+ loop = asyncio.get_running_loop()
46
+ # signal.signal works on Windows as well; event-loop signal handlers do not.
47
+ previous = signal.getsignal(signal.SIGINT)
48
+ previous_cancel = ui.cancel_active
49
+ ui.cancel_active = task.cancel
50
+ signal.signal(signal.SIGINT, lambda *_: loop.call_soon_threadsafe(task.cancel))
51
+ try:
52
+ return await task
53
+ except asyncio.CancelledError:
54
+ ui.notice("Операция прервана")
55
+ return None
56
+ finally:
57
+ ui.cancel_active = previous_cancel
58
+ signal.signal(signal.SIGINT, previous)
59
+
60
+
61
+ async def interactive(
62
+ client: Client,
63
+ settings: Settings,
64
+ ui: UI,
65
+ store: Store,
66
+ session: dict[str, Any] | None = None,
67
+ *,
68
+ header_shown: bool = False,
69
+ ) -> None:
70
+ root = Path(session["root"]) if session else project_root(Path.cwd())
71
+ if not root.is_dir():
72
+ raise ValueError("Каталог сохранённого проекта больше не существует.")
73
+
74
+ requested = session["model"] if session else settings.model
75
+ if not header_shown:
76
+ ui.header(requested, root)
77
+ if settings.permissions_warning:
78
+ ui.notice("Настройки разрешений сброшены", "Включена стандартная защита.", "warning")
79
+
80
+ model = await resolve_model(client, ui, requested)
81
+ set_model_label(ui, model)
82
+
83
+ session = session or new_session(root, model.id if model else "")
84
+ tools = Tools(root, ui, session["snapshots"], settings)
85
+ chat = Chat(
86
+ client=client,
87
+ settings=settings,
88
+ ui=ui,
89
+ store=store,
90
+ root=root,
91
+ session=session,
92
+ model=model,
93
+ tools=tools,
94
+ agent=Agent(client, model, session, store, tools, ui) if model else None,
95
+ )
96
+ store.save(session)
97
+ os.chdir(root)
98
+
99
+ if chat.model is None:
100
+ ui.muted("Выберите /model, чтобы отправить первое сообщение.")
101
+
102
+ async with ui.chat_session():
103
+ await chat_loop(chat)
104
+
105
+
106
+ async def chat_loop(chat: Chat) -> None:
107
+ client, store, settings, ui = chat.client, chat.store, chat.settings, chat.ui
108
+ interrupted = False
109
+ while True:
110
+ ui.completer.sessions = [
111
+ (row[0], f"{row[1] or 'без модели'} · {row[2]}") for row in store.list()
112
+ ]
113
+
114
+ try:
115
+ text = (await ui.next_chat_input()).strip()
116
+ except EOFError:
117
+ break
118
+ except KeyboardInterrupt:
119
+ if not ui.interrupted_empty:
120
+ interrupted = False
121
+ ui.muted("Ввод очищен.")
122
+ continue
123
+ if interrupted:
124
+ break
125
+ interrupted = True
126
+ ui.muted("Нажмите Ctrl+C ещё раз для выхода.")
127
+ continue
128
+
129
+ interrupted = False
130
+ if not text:
131
+ continue
132
+
133
+ try:
134
+ if not text.startswith("/"):
135
+ if chat.agent is None:
136
+ ui.notice(
137
+ "Модель не выбрана",
138
+ "Используйте /model, затем отправьте сообщение.",
139
+ "warning",
140
+ )
141
+ continue
142
+ await cancellable(chat.agent.turn(text), ui)
143
+ continue
144
+
145
+ command, *parts = text.split(maxsplit=1)
146
+ argument = parts[0].strip() if parts else ""
147
+ client.request_id = None
148
+
149
+ if command == "/exit":
150
+ break
151
+
152
+ if command == "/help":
153
+ ui.say(help_text())
154
+
155
+ elif command == "/permissions":
156
+ choice = await ui.choose_permissions(settings)
157
+ if choice is not None:
158
+ settings.save_permissions(*choice)
159
+ ui.notice("Разрешения сохранены", "Настройки действуют для всех проектов.")
160
+
161
+ elif command == "/context":
162
+ await cancellable(show_context(chat.session, chat.agent, ui), ui)
163
+
164
+ elif command == "/system":
165
+ if not argument:
166
+ ui.say(settings.system_prompt or "Дополнительный системный промпт не задан.")
167
+ ui.muted("/system <текст> — сохранить · /system --reset — сбросить")
168
+ elif argument == "--reset":
169
+ settings.save_system_prompt("")
170
+ ui.notice("Системный промпт сброшен")
171
+ else:
172
+ settings.save_system_prompt(argument)
173
+ ui.notice("Системный промпт сохранён", "Настройка действует для всех проектов.")
174
+
175
+ elif command == "/model":
176
+ chosen = await cancellable(choose_model(client, settings, ui, argument or None), ui)
177
+ if chosen is not None:
178
+ await apply_model(chat, chosen)
179
+
180
+ elif command in {"/profile", "/balance", "/subscription", "/usage"}:
181
+ await cancellable(account(client, ui, command[1:], argument or "2d"), ui)
182
+
183
+ elif command == "/sessions":
184
+ show_sessions(store, ui)
185
+
186
+ elif command in {"/new", "/resume"}:
187
+ await replace_session(chat, command, argument)
188
+
189
+ elif command == "/compact":
190
+ if chat.agent:
191
+ await cancellable(chat.agent.compact(), ui)
192
+ else:
193
+ ui.notice(
194
+ "Модель не выбрана", "Используйте /model для сжатия контекста.", "warning"
195
+ )
196
+
197
+ elif command == "/undo":
198
+ await undo(chat)
199
+
200
+ elif command == "/diff":
201
+ show_diff(chat)
202
+
203
+ else:
204
+ ui.notice(
205
+ "Неизвестная команда",
206
+ "Введите / для выбора команды или /help для справки.",
207
+ "warning",
208
+ )
209
+
210
+ except (ApiError, ValueError, OSError) as exc:
211
+ if isinstance(exc, ApiError) and text.startswith("/") and command != "/compact":
212
+ chat.session.setdefault("diagnostics", []).append(
213
+ {
214
+ "at": datetime.now(UTC).isoformat(),
215
+ "kind": command,
216
+ "status": "error",
217
+ "request_id": exc.request_id or client.request_id,
218
+ "usage": None,
219
+ }
220
+ )
221
+ store.save(chat.session)
222
+ ui.notice("Ошибка", str(exc), "error")
223
+ except EOFError:
224
+ break
225
+ except KeyboardInterrupt:
226
+ ui.notice("Операция прервана")
227
+
228
+
229
+ async def run(args: argparse.Namespace) -> None:
230
+ settings = Settings.load(args.base_url, args.model)
231
+ ui = UI(settings.color)
232
+ credentials = Credentials(settings.base_url)
233
+ store = Store()
234
+ client: Client | None = None
235
+
236
+ try:
237
+ session = store.load(args.id) if args.command == "resume" else None
238
+ if session and (args.model or os.getenv("SPIRITLM_MODEL")):
239
+ session["model"] = args.model or os.environ["SPIRITLM_MODEL"]
240
+
241
+ chat = args.command in {None, "resume"}
242
+ if chat:
243
+ root = Path(session["root"]) if session else project_root(Path.cwd())
244
+ ui.header(session["model"] if session else settings.model, root)
245
+
246
+ if args.command == "sessions":
247
+ show_sessions(store, ui)
248
+ return
249
+
250
+ if args.command == "logout":
251
+ ui.say("Ключ удалён." if credentials.delete() else "Системное хранилище недоступно.")
252
+ if os.getenv("SPIRITLM_API_KEY"):
253
+ ui.say("Ключ окружения активен до удаления SPIRITLM_API_KEY из оболочки.")
254
+ return
255
+
256
+ key = credentials.get()
257
+ if args.command == "login" or not key:
258
+ key = (await ui.ask("API-ключ SpiritLM: ", secret=True)).strip()
259
+ if not key:
260
+ raise ValueError("API-ключ не указан.")
261
+
262
+ client = Client(settings, key)
263
+ await client.get("models")
264
+
265
+ if credentials.save(key):
266
+ ui.notice("Вход выполнен", "API-ключ сохранён в системном хранилище.", "success")
267
+ else:
268
+ ui.notice(
269
+ "Keyring недоступен", "Ключ хранится только в памяти этого процесса.", "warning"
270
+ )
271
+ if args.command == "login":
272
+ ui.say("Для следующего запуска задайте SPIRITLM_API_KEY или настройте keyring.")
273
+ if args.command == "login":
274
+ return
275
+
276
+ client = client or Client(settings, key)
277
+
278
+ if args.command == "models":
279
+ models = await client.models()
280
+ ui.table(model_rows(models), "Модели SpiritLM")
281
+
282
+ elif args.command == "account":
283
+ for name in ("profile", "balance", "subscription", "usage"):
284
+ try:
285
+ await account(client, ui, name)
286
+ except ApiError as exc:
287
+ ui.notice("Ошибка", str(exc), "error")
288
+
289
+ else:
290
+ await load_account_label(client, ui)
291
+ root = Path(session["root"]) if session else project_root(Path.cwd())
292
+ ui.reset(session["model"] if session else settings.model, root)
293
+ await interactive(client, settings, ui, store, session, header_shown=True)
294
+ finally:
295
+ if client:
296
+ await client.close()
297
+ store.close()
298
+
299
+
300
+ def main() -> None:
301
+ parser = RussianParser(prog="sprt", description="SpiritCode — кодинг-агент для SpiritLM")
302
+ parser.add_argument(
303
+ "--version",
304
+ action="version",
305
+ version=__version__,
306
+ help="Показать версию и выйти",
307
+ )
308
+ parser.add_argument("--base-url", help="Адрес SpiritLM без /v1")
309
+ parser.add_argument("--model", help="ID модели SpiritLM")
310
+
311
+ commands = parser.add_subparsers(dest="command")
312
+ for command, description in {
313
+ "login": "Войти",
314
+ "logout": "Удалить ключ",
315
+ "models": "Каталог моделей",
316
+ "account": "Аккаунт SpiritLM",
317
+ "sessions": "Сохранённые сессии",
318
+ }.items():
319
+ commands.add_parser(command, help=description)
320
+ resume = commands.add_parser("resume", help="Продолжить сессию")
321
+ resume.add_argument("id")
322
+
323
+ args = parser.parse_args()
324
+ try:
325
+ asyncio.run(run(args))
326
+ except (EOFError, KeyboardInterrupt):
327
+ pass
328
+ except (ApiError, ValueError, OSError) as exc:
329
+ UI().notice("Ошибка", str(exc), "error")
330
+ raise SystemExit(1) from None
@@ -0,0 +1 @@
1
+ """Slash-command handlers for the interactive chat."""
@@ -0,0 +1,53 @@
1
+ """SpiritLM account and plan display."""
2
+
3
+ import asyncio
4
+ from typing import Any
5
+
6
+ from spiritcode.constants import ACCOUNT_TIMEOUT
7
+ from spiritcode.core.api import ApiError, Client
8
+ from spiritcode.sanitize import clean
9
+ from spiritcode.ui.display import account_rows
10
+ from spiritcode.ui.interface import UI
11
+
12
+
13
+ async def account(client: Client, ui: UI, name: str = "profile", period: str = "2d") -> None:
14
+ if name == "usage" and period not in {"2d", "7d", "30d", "all"}:
15
+ raise ValueError("Период: 2d, 7d, 30d или all.")
16
+
17
+ value = await client.get(name, **({"period": period} if name == "usage" else {}))
18
+ ui.table(account_rows(value), "Аккаунт SpiritLM")
19
+
20
+
21
+ async def load_account_label(client: Client, ui: UI) -> None:
22
+ async def optional_account(name: str) -> dict[str, Any] | None:
23
+ try:
24
+ async with asyncio.timeout(ACCOUNT_TIMEOUT):
25
+ value = await client.get(name)
26
+ return value if isinstance(value, dict) else None
27
+ except (ApiError, TimeoutError):
28
+ return None
29
+
30
+ profile, subscription = await asyncio.gather(
31
+ optional_account("profile"), optional_account("subscription")
32
+ )
33
+
34
+ identity = "Пользователь"
35
+ if profile:
36
+ username = profile.get("username")
37
+ name = profile.get("name")
38
+ if isinstance(username, str) and username.strip():
39
+ identity = "@" + username.strip().lstrip("@")
40
+ elif isinstance(name, str) and name.strip():
41
+ identity = name.strip()
42
+
43
+ plan = "тариф недоступен"
44
+ if subscription is not None and "current" in subscription:
45
+ current = subscription["current"]
46
+ if current is None:
47
+ plan = "Free"
48
+ elif isinstance(current, dict):
49
+ plan_name = current.get("planName")
50
+ if isinstance(plan_name, str) and plan_name.strip():
51
+ plan = plan_name.strip()
52
+
53
+ ui.account_label = clean(f"{identity} | {plan}")
@@ -0,0 +1,26 @@
1
+ """State shared by the interactive chat command handlers."""
2
+
3
+ from dataclasses import dataclass
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ from spiritcode.core.agent import Agent
8
+ from spiritcode.core.api import Client
9
+ from spiritcode.core.config import Settings
10
+ from spiritcode.core.models import Model
11
+ from spiritcode.core.store import Store
12
+ from spiritcode.tools.executor import Tools
13
+ from spiritcode.ui.interface import UI
14
+
15
+
16
+ @dataclass
17
+ class Chat:
18
+ client: Client
19
+ settings: Settings
20
+ ui: UI
21
+ store: Store
22
+ root: Path
23
+ session: dict[str, Any]
24
+ model: Model | None
25
+ tools: Tools
26
+ agent: Agent | None
@@ -0,0 +1,68 @@
1
+ """Context, token budget, and request diagnostics."""
2
+
3
+ from typing import Any
4
+
5
+ from spiritcode.constants import DEFAULT_OUTPUT_TOKENS
6
+ from spiritcode.core.agent import Agent
7
+ from spiritcode.core.context import estimate_tokens, input_budget
8
+ from spiritcode.ui.interface import UI
9
+
10
+ DIAGNOSTIC_STATUSES = {"completed": "завершён", "error": "ошибка", "cancelled": "прерван"}
11
+
12
+ DIAGNOSTIC_KINDS = {"generation": "генерация", "compaction": "сжатие"}
13
+
14
+
15
+ async def show_context(session: dict[str, Any], agent: Agent | None, ui: UI) -> None:
16
+ rows = [("Сессия", session["id"]), ("Модель", agent.model.id if agent else "не выбрана")]
17
+
18
+ if agent:
19
+ context = await agent.system_message()
20
+ output = min(DEFAULT_OUTPUT_TOKENS, agent.model.max_output_tokens or DEFAULT_OUTPUT_TOKENS)
21
+ budget = input_budget(agent.model.context_window, output)
22
+ estimated = estimate_tokens([context, *agent.messages]) + estimate_tokens(
23
+ agent.payload([]).get("tools", [])
24
+ )
25
+ rows.extend(
26
+ [
27
+ (
28
+ "Контекст (оценка)",
29
+ f"≈ {estimated} / {budget} токенов · {estimated / budget:.0%}",
30
+ ),
31
+ (
32
+ "Окно модели",
33
+ str(agent.model.context_window)
34
+ if agent.model.context_window
35
+ else "неизвестно · бюджет рассчитан из резервного окна",
36
+ ),
37
+ ("Резерв ответа", f"{output} токенов"),
38
+ ]
39
+ )
40
+ else:
41
+ rows.append(("Контекст", "Выберите /model для оценки бюджета"))
42
+
43
+ diagnostics = session.get("diagnostics", [])
44
+ rows.append(("Запросов в сессии", str(len(diagnostics))))
45
+
46
+ if diagnostics:
47
+ latest = diagnostics[-1]
48
+ usage = latest.get("usage") or {}
49
+ rows.extend(
50
+ [
51
+ ("Последний запрос", DIAGNOSTIC_KINDS.get(latest["kind"], latest["kind"])),
52
+ ("Статус", DIAGNOSTIC_STATUSES.get(latest["status"], latest["status"])),
53
+ ("Время UTC", latest["at"]),
54
+ ("Модель запроса", latest.get("model") or "нет данных"),
55
+ ("Request ID", latest.get("request_id") or "нет данных"),
56
+ ]
57
+ )
58
+ for key, label in (
59
+ ("prompt_tokens", "Входные токены (сервер)"),
60
+ ("completion_tokens", "Выходные токены (сервер)"),
61
+ ("total_tokens", "Всего токенов (сервер)"),
62
+ ):
63
+ value = usage.get(key)
64
+ rows.append((label, str(value) if value is not None else "нет данных"))
65
+ else:
66
+ rows.extend([("Request ID", "нет данных"), ("Токены (сервер)", "нет данных")])
67
+
68
+ ui.table(rows, "Контекст и диагностика")
@@ -0,0 +1,19 @@
1
+ """Workspace edit commands."""
2
+
3
+ from spiritcode.commands.chat import Chat
4
+ from spiritcode.tools.files import unified
5
+
6
+
7
+ async def undo(chat: Chat) -> None:
8
+ result = await chat.tools.undo()
9
+ chat.session["messages"].append({"role": "user", "content": "Результат /undo: " + result})
10
+ chat.store.save(chat.session)
11
+ chat.ui.notice("Отмена правок", result)
12
+
13
+
14
+ def show_diff(chat: Chat) -> None:
15
+ if not chat.tools.snapshots:
16
+ chat.ui.muted("В этой сессии пока нет правок.")
17
+ for group in chat.tools.snapshots:
18
+ for change in group:
19
+ chat.ui.diff(unified(change["path"], change["before"], change["after"]))