spiritcode 0.1.0__tar.gz → 0.1.2__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.
- spiritcode-0.1.2/PKG-INFO +103 -0
- spiritcode-0.1.2/README.md +79 -0
- {spiritcode-0.1.0 → spiritcode-0.1.2/docs}/SERVER_CONTRACT.md +8 -1
- spiritcode-0.1.2/images/icon.png +0 -0
- {spiritcode-0.1.0 → spiritcode-0.1.2}/pyproject.toml +3 -2
- {spiritcode-0.1.0 → spiritcode-0.1.2}/src/spiritcode/__init__.py +1 -1
- spiritcode-0.1.2/src/spiritcode/cli.py +310 -0
- spiritcode-0.1.2/src/spiritcode/commands/__init__.py +1 -0
- spiritcode-0.1.2/src/spiritcode/commands/account.py +53 -0
- spiritcode-0.1.2/src/spiritcode/commands/chat.py +26 -0
- spiritcode-0.1.2/src/spiritcode/commands/diagnostics.py +72 -0
- spiritcode-0.1.2/src/spiritcode/commands/files.py +19 -0
- spiritcode-0.1.2/src/spiritcode/commands/model.py +103 -0
- spiritcode-0.1.2/src/spiritcode/commands/sessions.py +44 -0
- spiritcode-0.1.2/src/spiritcode/constants.py +59 -0
- spiritcode-0.1.2/src/spiritcode/core/__init__.py +1 -0
- {spiritcode-0.1.0/src/spiritcode → spiritcode-0.1.2/src/spiritcode/core}/agent.py +49 -19
- {spiritcode-0.1.0/src/spiritcode → spiritcode-0.1.2/src/spiritcode/core}/api.py +21 -34
- spiritcode-0.1.2/src/spiritcode/core/config.py +120 -0
- {spiritcode-0.1.0/src/spiritcode → spiritcode-0.1.2/src/spiritcode/core}/context.py +10 -16
- spiritcode-0.1.2/src/spiritcode/core/models.py +37 -0
- spiritcode-0.1.2/src/spiritcode/core/permissions.py +161 -0
- {spiritcode-0.1.0/src/spiritcode → spiritcode-0.1.2/src/spiritcode/core}/store.py +6 -2
- spiritcode-0.1.2/src/spiritcode/prompts.py +21 -0
- spiritcode-0.1.2/src/spiritcode/sanitize.py +13 -0
- spiritcode-0.1.2/src/spiritcode/tools/__init__.py +1 -0
- spiritcode-0.1.0/src/spiritcode/tools.py → spiritcode-0.1.2/src/spiritcode/tools/executor.py +59 -156
- spiritcode-0.1.2/src/spiritcode/tools/files.py +73 -0
- spiritcode-0.1.2/src/spiritcode/tools/schemas.py +87 -0
- spiritcode-0.1.2/src/spiritcode/types.py +8 -0
- spiritcode-0.1.2/src/spiritcode/ui/__init__.py +1 -0
- {spiritcode-0.1.0/src/spiritcode → spiritcode-0.1.2/src/spiritcode/ui}/commands.py +1 -1
- {spiritcode-0.1.0/src/spiritcode → spiritcode-0.1.2/src/spiritcode/ui}/display.py +6 -1
- spiritcode-0.1.0/src/spiritcode/ui.py → spiritcode-0.1.2/src/spiritcode/ui/interface.py +181 -76
- {spiritcode-0.1.0/src/spiritcode → spiritcode-0.1.2/src/spiritcode/ui}/keyboard.py +64 -3
- {spiritcode-0.1.0 → spiritcode-0.1.2}/tests/test_agent.py +43 -9
- {spiritcode-0.1.0 → spiritcode-0.1.2}/tests/test_api.py +44 -4
- {spiritcode-0.1.0 → spiritcode-0.1.2}/tests/test_cli.py +75 -8
- spiritcode-0.1.2/tests/test_config_store.py +114 -0
- spiritcode-0.1.2/tests/test_keyboard.py +114 -0
- spiritcode-0.1.2/tests/test_permissions.py +125 -0
- {spiritcode-0.1.0 → spiritcode-0.1.2}/tests/test_tools.py +6 -3
- {spiritcode-0.1.0 → spiritcode-0.1.2}/tests/test_ui.py +63 -10
- spiritcode-0.1.0/PKG-INFO +0 -75
- spiritcode-0.1.0/README.md +0 -51
- spiritcode-0.1.0/src/spiritcode/cli.py +0 -456
- spiritcode-0.1.0/src/spiritcode/config.py +0 -112
- spiritcode-0.1.0/src/spiritcode/permissions.py +0 -40
- spiritcode-0.1.0/tests/test_config_store.py +0 -47
- {spiritcode-0.1.0 → spiritcode-0.1.2}/.gitignore +0 -0
- /spiritcode-0.1.0/image.png → /spiritcode-0.1.2/images/cli.png +0 -0
- {spiritcode-0.1.0 → spiritcode-0.1.2}/scripts/check_install.py +0 -0
- {spiritcode-0.1.0 → spiritcode-0.1.2}/scripts/publish.py +0 -0
- {spiritcode-0.1.0 → spiritcode-0.1.2}/src/spiritcode/__main__.py +0 -0
- {spiritcode-0.1.0/src/spiritcode → spiritcode-0.1.2/src/spiritcode/core}/credentials.py +0 -0
- {spiritcode-0.1.0 → spiritcode-0.1.2}/tests/__init__.py +0 -0
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: spiritcode
|
|
3
|
+
Version: 0.1.2
|
|
4
|
+
Summary: Терминальный кодинг-агент для SpiritLM
|
|
5
|
+
Keywords: ai,coding-agent,spiritlm,terminal
|
|
6
|
+
Classifier: Development Status :: 3 - Alpha
|
|
7
|
+
Classifier: Environment :: Console
|
|
8
|
+
Classifier: Intended Audience :: Developers
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
14
|
+
Classifier: Topic :: Software Development
|
|
15
|
+
Requires-Python: >=3.12
|
|
16
|
+
Requires-Dist: httpx<1,>=0.28
|
|
17
|
+
Requires-Dist: keyring<26,>=25
|
|
18
|
+
Requires-Dist: pathspec<1,>=0.12
|
|
19
|
+
Requires-Dist: platformdirs<5,>=4
|
|
20
|
+
Requires-Dist: prompt-toolkit<4,>=3.0.48
|
|
21
|
+
Requires-Dist: pydantic<3,>=2.10
|
|
22
|
+
Requires-Dist: rich<15,>=13.9
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# SpiritCode
|
|
26
|
+
|
|
27
|
+
Терминальный кодинг-агент для SpiritLM. Python 3.12+, Linux, macOS и Windows.
|
|
28
|
+
|
|
29
|
+

|
|
30
|
+
|
|
31
|
+
## Установка
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
pip install spiritcode
|
|
35
|
+
sprt
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
При первом запуске введите API-ключ SpiritLM, затем выберите модель через `/model`.
|
|
39
|
+
`spiritcode` и `python -m spiritcode` — альтернативные способы запуска.
|
|
40
|
+
|
|
41
|
+
По умолчанию используется `https://spiritlm.netlify.app`. Для локальной разработки
|
|
42
|
+
запускайте `NODE_ENV=development sprt` (также поддерживается `dev`) — API будет
|
|
43
|
+
доступен по `http://localhost:3000`. Явный адрес в `--base-url`, `SPIRITLM_BASE_URL`
|
|
44
|
+
или `config.toml` имеет приоритет над автоматическим выбором.
|
|
45
|
+
|
|
46
|
+
## Команды
|
|
47
|
+
|
|
48
|
+
| Команда | Описание |
|
|
49
|
+
| --- | --- |
|
|
50
|
+
| `sprt` | Открыть чат в текущем проекте |
|
|
51
|
+
| `sprt login` | Войти по API-ключу |
|
|
52
|
+
| `sprt logout` | Удалить сохранённый ключ |
|
|
53
|
+
| `sprt models` | Показать модели |
|
|
54
|
+
| `sprt account` | Показать аккаунт |
|
|
55
|
+
| `sprt sessions` | Показать сохранённые сессии |
|
|
56
|
+
| `sprt resume <id>` | Продолжить сессию |
|
|
57
|
+
| `sprt --base-url <url> --model <id>` | Указать сервер без `/v1` и модель |
|
|
58
|
+
| `sprt --help` | Справка |
|
|
59
|
+
| `sprt --version` | Версия |
|
|
60
|
+
|
|
61
|
+
В чате:
|
|
62
|
+
|
|
63
|
+
| Команда | Описание |
|
|
64
|
+
| --- | --- |
|
|
65
|
+
| `/help` | Команды и сочетания клавиш |
|
|
66
|
+
| `/model [id]` | Поиск и смена модели |
|
|
67
|
+
| `/context` | Контекст, токены и диагностика сессии |
|
|
68
|
+
| `/profile` | Профиль SpiritLM |
|
|
69
|
+
| `/balance` | Баланс аккаунта |
|
|
70
|
+
| `/subscription` | Подписка и доступные кредиты |
|
|
71
|
+
| `/usage [2d\|7d\|30d\|all]` | Статистика аккаунта |
|
|
72
|
+
| `/new` | Новая сессия |
|
|
73
|
+
| `/sessions` | Сохранённые сессии |
|
|
74
|
+
| `/resume <id>` | Продолжить сессию |
|
|
75
|
+
| `/compact` | Сжать контекст отдельным оплачиваемым запросом |
|
|
76
|
+
| `/diff` | Правки сессии |
|
|
77
|
+
| `/undo` | Отменить последнюю группу правок |
|
|
78
|
+
| `/permissions` | Выбрать режим разрешений |
|
|
79
|
+
| `/exit` | Выход |
|
|
80
|
+
| `@путь` или `@"путь с пробелами"` | Прикрепить файл |
|
|
81
|
+
|
|
82
|
+
## Разрешения
|
|
83
|
+
|
|
84
|
+
`/permissions` открывает меню: стрелки выбирают режим, Space переключает чекбокс,
|
|
85
|
+
Enter сохраняет, Esc отменяет. Настройки сохраняются для всех проектов.
|
|
86
|
+
|
|
87
|
+
- **Стандартная защита** (по умолчанию): чтение, поиск и известные проверки проекта
|
|
88
|
+
выполняются автоматически. Git, удаление, перезапись, системные изменения,
|
|
89
|
+
составные и непрозрачные команды требуют разрешения.
|
|
90
|
+
- **Без защиты**: команды выполняются автоматически. Чекбокс «Спрашивать перед
|
|
91
|
+
удалением» включён по умолчанию; он также требует разрешения для непрозрачного
|
|
92
|
+
кода, который может удалять файлы. Снимите его для выполнения любых команд без вопросов.
|
|
93
|
+
- **Полная защита**: каждая shell-команда требует разрешения. Чтение и точечные
|
|
94
|
+
правки внутри проекта остаются автоматическими.
|
|
95
|
+
|
|
96
|
+
Запросы доступа файловых инструментов к секретам и файлам вне проекта сохраняются
|
|
97
|
+
во всех режимах. Отказ не запускает команду; без интерактивного терминала действия,
|
|
98
|
+
требующие подтверждения, отклоняются. Классификация команд не является системной
|
|
99
|
+
песочницей: shell работает с правами пользователя. `/undo` не откатывает команды.
|
|
100
|
+
|
|
101
|
+
Если поддержка инструментов модели неизвестна, SpiritCode пробует отправить их.
|
|
102
|
+
При отказе сервера выберите другую модель через `/model`; оплачиваемые запросы
|
|
103
|
+
автоматически не повторяются. При явно отключённой поддержке доступен режим чата.
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# SpiritCode
|
|
2
|
+
|
|
3
|
+
Терминальный кодинг-агент для SpiritLM. Python 3.12+, Linux, macOS и Windows.
|
|
4
|
+
|
|
5
|
+

|
|
6
|
+
|
|
7
|
+
## Установка
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pip install spiritcode
|
|
11
|
+
sprt
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
При первом запуске введите API-ключ SpiritLM, затем выберите модель через `/model`.
|
|
15
|
+
`spiritcode` и `python -m spiritcode` — альтернативные способы запуска.
|
|
16
|
+
|
|
17
|
+
По умолчанию используется `https://spiritlm.netlify.app`. Для локальной разработки
|
|
18
|
+
запускайте `NODE_ENV=development sprt` (также поддерживается `dev`) — API будет
|
|
19
|
+
доступен по `http://localhost:3000`. Явный адрес в `--base-url`, `SPIRITLM_BASE_URL`
|
|
20
|
+
или `config.toml` имеет приоритет над автоматическим выбором.
|
|
21
|
+
|
|
22
|
+
## Команды
|
|
23
|
+
|
|
24
|
+
| Команда | Описание |
|
|
25
|
+
| --- | --- |
|
|
26
|
+
| `sprt` | Открыть чат в текущем проекте |
|
|
27
|
+
| `sprt login` | Войти по API-ключу |
|
|
28
|
+
| `sprt logout` | Удалить сохранённый ключ |
|
|
29
|
+
| `sprt models` | Показать модели |
|
|
30
|
+
| `sprt account` | Показать аккаунт |
|
|
31
|
+
| `sprt sessions` | Показать сохранённые сессии |
|
|
32
|
+
| `sprt resume <id>` | Продолжить сессию |
|
|
33
|
+
| `sprt --base-url <url> --model <id>` | Указать сервер без `/v1` и модель |
|
|
34
|
+
| `sprt --help` | Справка |
|
|
35
|
+
| `sprt --version` | Версия |
|
|
36
|
+
|
|
37
|
+
В чате:
|
|
38
|
+
|
|
39
|
+
| Команда | Описание |
|
|
40
|
+
| --- | --- |
|
|
41
|
+
| `/help` | Команды и сочетания клавиш |
|
|
42
|
+
| `/model [id]` | Поиск и смена модели |
|
|
43
|
+
| `/context` | Контекст, токены и диагностика сессии |
|
|
44
|
+
| `/profile` | Профиль SpiritLM |
|
|
45
|
+
| `/balance` | Баланс аккаунта |
|
|
46
|
+
| `/subscription` | Подписка и доступные кредиты |
|
|
47
|
+
| `/usage [2d\|7d\|30d\|all]` | Статистика аккаунта |
|
|
48
|
+
| `/new` | Новая сессия |
|
|
49
|
+
| `/sessions` | Сохранённые сессии |
|
|
50
|
+
| `/resume <id>` | Продолжить сессию |
|
|
51
|
+
| `/compact` | Сжать контекст отдельным оплачиваемым запросом |
|
|
52
|
+
| `/diff` | Правки сессии |
|
|
53
|
+
| `/undo` | Отменить последнюю группу правок |
|
|
54
|
+
| `/permissions` | Выбрать режим разрешений |
|
|
55
|
+
| `/exit` | Выход |
|
|
56
|
+
| `@путь` или `@"путь с пробелами"` | Прикрепить файл |
|
|
57
|
+
|
|
58
|
+
## Разрешения
|
|
59
|
+
|
|
60
|
+
`/permissions` открывает меню: стрелки выбирают режим, Space переключает чекбокс,
|
|
61
|
+
Enter сохраняет, Esc отменяет. Настройки сохраняются для всех проектов.
|
|
62
|
+
|
|
63
|
+
- **Стандартная защита** (по умолчанию): чтение, поиск и известные проверки проекта
|
|
64
|
+
выполняются автоматически. Git, удаление, перезапись, системные изменения,
|
|
65
|
+
составные и непрозрачные команды требуют разрешения.
|
|
66
|
+
- **Без защиты**: команды выполняются автоматически. Чекбокс «Спрашивать перед
|
|
67
|
+
удалением» включён по умолчанию; он также требует разрешения для непрозрачного
|
|
68
|
+
кода, который может удалять файлы. Снимите его для выполнения любых команд без вопросов.
|
|
69
|
+
- **Полная защита**: каждая shell-команда требует разрешения. Чтение и точечные
|
|
70
|
+
правки внутри проекта остаются автоматическими.
|
|
71
|
+
|
|
72
|
+
Запросы доступа файловых инструментов к секретам и файлам вне проекта сохраняются
|
|
73
|
+
во всех режимах. Отказ не запускает команду; без интерактивного терминала действия,
|
|
74
|
+
требующие подтверждения, отклоняются. Классификация команд не является системной
|
|
75
|
+
песочницей: shell работает с правами пользователя. `/undo` не откатывает команды.
|
|
76
|
+
|
|
77
|
+
Если поддержка инструментов модели неизвестна, SpiritCode пробует отправить их.
|
|
78
|
+
При отказе сервера выберите другую модель через `/model`; оплачиваемые запросы
|
|
79
|
+
автоматически не повторяются. При явно отключённой поддержке доступен режим чата.
|
|
@@ -54,4 +54,11 @@ Clerk и upstream credentials клиенту не передаются. Фина
|
|
|
54
54
|
```
|
|
55
55
|
|
|
56
56
|
Клиент не выводит приватный текст HTTP-ошибок. Ответы 404/501 метаданных означают
|
|
57
|
-
старый сервер: доступен
|
|
57
|
+
старый сервер: доступен каталог, а поддержка инструментов остаётся неизвестной. Редиректы не выполняются.
|
|
58
|
+
|
|
59
|
+
### Неизвестная поддержка инструментов
|
|
60
|
+
|
|
61
|
+
Клиент передаёт инструменты при `tool_calling: true` и `null` (либо отсутствии
|
|
62
|
+
значения). `false` явно включает режим чата. Неизвестная поддержка не превращается
|
|
63
|
+
в подтверждённую: при отказе API клиент сообщает об ошибке без автоматического
|
|
64
|
+
повтора и предлагает выбрать другую модель через `/model`.
|
|
Binary file
|
|
@@ -0,0 +1,310 @@
|
|
|
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
|
+
signal.signal(signal.SIGINT, lambda *_: loop.call_soon_threadsafe(task.cancel))
|
|
49
|
+
try:
|
|
50
|
+
return await task
|
|
51
|
+
except asyncio.CancelledError:
|
|
52
|
+
ui.notice("Операция прервана")
|
|
53
|
+
return None
|
|
54
|
+
finally:
|
|
55
|
+
signal.signal(signal.SIGINT, previous)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
async def interactive(
|
|
59
|
+
client: Client,
|
|
60
|
+
settings: Settings,
|
|
61
|
+
ui: UI,
|
|
62
|
+
store: Store,
|
|
63
|
+
session: dict[str, Any] | None = None,
|
|
64
|
+
*,
|
|
65
|
+
header_shown: bool = False,
|
|
66
|
+
) -> None:
|
|
67
|
+
root = Path(session["root"]) if session else project_root(Path.cwd())
|
|
68
|
+
if not root.is_dir():
|
|
69
|
+
raise ValueError("Каталог сохранённого проекта больше не существует.")
|
|
70
|
+
|
|
71
|
+
requested = session["model"] if session else settings.model
|
|
72
|
+
if not header_shown:
|
|
73
|
+
ui.header(requested, root)
|
|
74
|
+
if settings.permissions_warning:
|
|
75
|
+
ui.notice("Настройки разрешений сброшены", "Включена стандартная защита.", "warning")
|
|
76
|
+
|
|
77
|
+
model = await resolve_model(client, ui, requested)
|
|
78
|
+
set_model_label(ui, model)
|
|
79
|
+
|
|
80
|
+
session = session or new_session(root, model.id if model else "")
|
|
81
|
+
tools = Tools(root, ui, session["snapshots"], settings)
|
|
82
|
+
chat = Chat(
|
|
83
|
+
client=client,
|
|
84
|
+
settings=settings,
|
|
85
|
+
ui=ui,
|
|
86
|
+
store=store,
|
|
87
|
+
root=root,
|
|
88
|
+
session=session,
|
|
89
|
+
model=model,
|
|
90
|
+
tools=tools,
|
|
91
|
+
agent=Agent(client, model, session, store, tools, ui) if model else None,
|
|
92
|
+
)
|
|
93
|
+
store.save(session)
|
|
94
|
+
os.chdir(root)
|
|
95
|
+
|
|
96
|
+
if chat.model is None:
|
|
97
|
+
ui.muted("Выберите /model, чтобы отправить первое сообщение.")
|
|
98
|
+
|
|
99
|
+
interrupted = False
|
|
100
|
+
while True:
|
|
101
|
+
ui.completer.sessions = [
|
|
102
|
+
(row[0], f"{row[1] or 'без модели'} · {row[2]}") for row in store.list()
|
|
103
|
+
]
|
|
104
|
+
|
|
105
|
+
try:
|
|
106
|
+
text = (await ui.ask(chat=True)).strip()
|
|
107
|
+
except EOFError:
|
|
108
|
+
break
|
|
109
|
+
except KeyboardInterrupt:
|
|
110
|
+
if not ui.interrupted_empty:
|
|
111
|
+
interrupted = False
|
|
112
|
+
ui.muted("Ввод очищен.")
|
|
113
|
+
continue
|
|
114
|
+
if interrupted:
|
|
115
|
+
break
|
|
116
|
+
interrupted = True
|
|
117
|
+
ui.muted("Нажмите Ctrl+C ещё раз для выхода.")
|
|
118
|
+
continue
|
|
119
|
+
|
|
120
|
+
interrupted = False
|
|
121
|
+
if not text:
|
|
122
|
+
continue
|
|
123
|
+
|
|
124
|
+
try:
|
|
125
|
+
if not text.startswith("/"):
|
|
126
|
+
if chat.agent is None:
|
|
127
|
+
ui.notice(
|
|
128
|
+
"Модель не выбрана",
|
|
129
|
+
"Используйте /model, затем отправьте сообщение.",
|
|
130
|
+
"warning",
|
|
131
|
+
)
|
|
132
|
+
continue
|
|
133
|
+
await cancellable(chat.agent.turn(text), ui)
|
|
134
|
+
continue
|
|
135
|
+
|
|
136
|
+
command, *parts = text.split(maxsplit=1)
|
|
137
|
+
argument = parts[0].strip() if parts else ""
|
|
138
|
+
client.request_id = None
|
|
139
|
+
|
|
140
|
+
if command == "/exit":
|
|
141
|
+
break
|
|
142
|
+
|
|
143
|
+
if command == "/help":
|
|
144
|
+
ui.say(help_text())
|
|
145
|
+
|
|
146
|
+
elif command == "/permissions":
|
|
147
|
+
choice = await ui.choose_permissions(settings)
|
|
148
|
+
if choice is not None:
|
|
149
|
+
settings.save_permissions(*choice)
|
|
150
|
+
ui.notice("Разрешения сохранены", "Настройки действуют для всех проектов.")
|
|
151
|
+
|
|
152
|
+
elif command == "/context":
|
|
153
|
+
await cancellable(show_context(chat.session, chat.agent, ui), ui)
|
|
154
|
+
|
|
155
|
+
elif command == "/model":
|
|
156
|
+
chosen = await cancellable(choose_model(client, settings, ui, argument or None), ui)
|
|
157
|
+
if chosen is not None:
|
|
158
|
+
await apply_model(chat, chosen)
|
|
159
|
+
|
|
160
|
+
elif command in {"/profile", "/balance", "/subscription", "/usage"}:
|
|
161
|
+
await cancellable(account(client, ui, command[1:], argument or "2d"), ui)
|
|
162
|
+
|
|
163
|
+
elif command == "/sessions":
|
|
164
|
+
show_sessions(store, ui)
|
|
165
|
+
|
|
166
|
+
elif command in {"/new", "/resume"}:
|
|
167
|
+
await replace_session(chat, command, argument)
|
|
168
|
+
|
|
169
|
+
elif command == "/compact":
|
|
170
|
+
if chat.agent:
|
|
171
|
+
await cancellable(chat.agent.compact(), ui)
|
|
172
|
+
else:
|
|
173
|
+
ui.notice(
|
|
174
|
+
"Модель не выбрана", "Используйте /model для сжатия контекста.", "warning"
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
elif command == "/undo":
|
|
178
|
+
await undo(chat)
|
|
179
|
+
|
|
180
|
+
elif command == "/diff":
|
|
181
|
+
show_diff(chat)
|
|
182
|
+
|
|
183
|
+
else:
|
|
184
|
+
ui.notice(
|
|
185
|
+
"Неизвестная команда",
|
|
186
|
+
"Введите / для выбора команды или /help для справки.",
|
|
187
|
+
"warning",
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
except (ApiError, ValueError, OSError) as exc:
|
|
191
|
+
if isinstance(exc, ApiError) and text.startswith("/") and command != "/compact":
|
|
192
|
+
chat.session.setdefault("diagnostics", []).append(
|
|
193
|
+
{
|
|
194
|
+
"at": datetime.now(UTC).isoformat(),
|
|
195
|
+
"kind": command,
|
|
196
|
+
"status": "error",
|
|
197
|
+
"request_id": exc.request_id or client.request_id,
|
|
198
|
+
"usage": None,
|
|
199
|
+
}
|
|
200
|
+
)
|
|
201
|
+
store.save(chat.session)
|
|
202
|
+
ui.notice("Ошибка", str(exc), "error")
|
|
203
|
+
except EOFError:
|
|
204
|
+
break
|
|
205
|
+
except KeyboardInterrupt:
|
|
206
|
+
ui.notice("Операция прервана")
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
async def run(args: argparse.Namespace) -> None:
|
|
210
|
+
settings = Settings.load(args.base_url, args.model)
|
|
211
|
+
ui = UI(settings.color)
|
|
212
|
+
credentials = Credentials(settings.base_url)
|
|
213
|
+
store = Store()
|
|
214
|
+
client: Client | None = None
|
|
215
|
+
|
|
216
|
+
try:
|
|
217
|
+
session = store.load(args.id) if args.command == "resume" else None
|
|
218
|
+
if session and (args.model or os.getenv("SPIRITLM_MODEL")):
|
|
219
|
+
session["model"] = args.model or os.environ["SPIRITLM_MODEL"]
|
|
220
|
+
|
|
221
|
+
chat = args.command in {None, "resume"}
|
|
222
|
+
if chat:
|
|
223
|
+
root = Path(session["root"]) if session else project_root(Path.cwd())
|
|
224
|
+
ui.header(session["model"] if session else settings.model, root)
|
|
225
|
+
|
|
226
|
+
if args.command == "sessions":
|
|
227
|
+
show_sessions(store, ui)
|
|
228
|
+
return
|
|
229
|
+
|
|
230
|
+
if args.command == "logout":
|
|
231
|
+
ui.say("Ключ удалён." if credentials.delete() else "Системное хранилище недоступно.")
|
|
232
|
+
if os.getenv("SPIRITLM_API_KEY"):
|
|
233
|
+
ui.say("Ключ окружения активен до удаления SPIRITLM_API_KEY из оболочки.")
|
|
234
|
+
return
|
|
235
|
+
|
|
236
|
+
key = credentials.get()
|
|
237
|
+
if args.command == "login" or not key:
|
|
238
|
+
key = (await ui.ask("API-ключ SpiritLM: ", secret=True)).strip()
|
|
239
|
+
if not key:
|
|
240
|
+
raise ValueError("API-ключ не указан.")
|
|
241
|
+
|
|
242
|
+
client = Client(settings, key)
|
|
243
|
+
await client.get("models")
|
|
244
|
+
|
|
245
|
+
if credentials.save(key):
|
|
246
|
+
ui.notice("Вход выполнен", "API-ключ сохранён в системном хранилище.", "success")
|
|
247
|
+
else:
|
|
248
|
+
ui.notice(
|
|
249
|
+
"Keyring недоступен", "Ключ хранится только в памяти этого процесса.", "warning"
|
|
250
|
+
)
|
|
251
|
+
if args.command == "login":
|
|
252
|
+
ui.say("Для следующего запуска задайте SPIRITLM_API_KEY или настройте keyring.")
|
|
253
|
+
if args.command == "login":
|
|
254
|
+
return
|
|
255
|
+
|
|
256
|
+
client = client or Client(settings, key)
|
|
257
|
+
|
|
258
|
+
if args.command == "models":
|
|
259
|
+
models = await client.models()
|
|
260
|
+
ui.table(model_rows(models), "Модели SpiritLM")
|
|
261
|
+
|
|
262
|
+
elif args.command == "account":
|
|
263
|
+
for name in ("profile", "balance", "subscription", "usage"):
|
|
264
|
+
try:
|
|
265
|
+
await account(client, ui, name)
|
|
266
|
+
except ApiError as exc:
|
|
267
|
+
ui.notice("Ошибка", str(exc), "error")
|
|
268
|
+
|
|
269
|
+
else:
|
|
270
|
+
await load_account_label(client, ui)
|
|
271
|
+
root = Path(session["root"]) if session else project_root(Path.cwd())
|
|
272
|
+
ui.reset(session["model"] if session else settings.model, root)
|
|
273
|
+
await interactive(client, settings, ui, store, session, header_shown=True)
|
|
274
|
+
finally:
|
|
275
|
+
if client:
|
|
276
|
+
await client.close()
|
|
277
|
+
store.close()
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def main() -> None:
|
|
281
|
+
parser = RussianParser(prog="sprt", description="SpiritCode — кодинг-агент для SpiritLM")
|
|
282
|
+
parser.add_argument(
|
|
283
|
+
"--version",
|
|
284
|
+
action="version",
|
|
285
|
+
version=__version__,
|
|
286
|
+
help="Показать версию и выйти",
|
|
287
|
+
)
|
|
288
|
+
parser.add_argument("--base-url", help="Адрес SpiritLM без /v1")
|
|
289
|
+
parser.add_argument("--model", help="ID модели SpiritLM")
|
|
290
|
+
|
|
291
|
+
commands = parser.add_subparsers(dest="command")
|
|
292
|
+
for command, description in {
|
|
293
|
+
"login": "Войти",
|
|
294
|
+
"logout": "Удалить ключ",
|
|
295
|
+
"models": "Каталог моделей",
|
|
296
|
+
"account": "Аккаунт SpiritLM",
|
|
297
|
+
"sessions": "Сохранённые сессии",
|
|
298
|
+
}.items():
|
|
299
|
+
commands.add_parser(command, help=description)
|
|
300
|
+
resume = commands.add_parser("resume", help="Продолжить сессию")
|
|
301
|
+
resume.add_argument("id")
|
|
302
|
+
|
|
303
|
+
args = parser.parse_args()
|
|
304
|
+
try:
|
|
305
|
+
asyncio.run(run(args))
|
|
306
|
+
except (EOFError, KeyboardInterrupt):
|
|
307
|
+
pass
|
|
308
|
+
except (ApiError, ValueError, OSError) as exc:
|
|
309
|
+
UI().notice("Ошибка", str(exc), "error")
|
|
310
|
+
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
|