spiritcode 0.1.1__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.1 → spiritcode-0.1.2}/PKG-INFO +2 -2
- {spiritcode-0.1.1 → spiritcode-0.1.2}/README.md +1 -1
- spiritcode-0.1.2/images/icon.png +0 -0
- {spiritcode-0.1.1 → spiritcode-0.1.2}/pyproject.toml +3 -2
- {spiritcode-0.1.1 → 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.1/src/spiritcode → spiritcode-0.1.2/src/spiritcode/core}/agent.py +38 -17
- {spiritcode-0.1.1/src/spiritcode → spiritcode-0.1.2/src/spiritcode/core}/api.py +7 -33
- {spiritcode-0.1.1/src/spiritcode → spiritcode-0.1.2/src/spiritcode/core}/config.py +9 -55
- {spiritcode-0.1.1/src/spiritcode → spiritcode-0.1.2/src/spiritcode/core}/context.py +10 -18
- spiritcode-0.1.2/src/spiritcode/core/models.py +37 -0
- {spiritcode-0.1.1/src/spiritcode → spiritcode-0.1.2/src/spiritcode/core}/permissions.py +20 -2
- {spiritcode-0.1.1/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.1/src/spiritcode/tools.py → spiritcode-0.1.2/src/spiritcode/tools/executor.py +42 -153
- 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.1/src/spiritcode → spiritcode-0.1.2/src/spiritcode/ui}/display.py +6 -1
- spiritcode-0.1.1/src/spiritcode/ui.py → spiritcode-0.1.2/src/spiritcode/ui/interface.py +89 -76
- {spiritcode-0.1.1/src/spiritcode → spiritcode-0.1.2/src/spiritcode/ui}/keyboard.py +14 -0
- {spiritcode-0.1.1 → spiritcode-0.1.2}/tests/test_agent.py +6 -5
- {spiritcode-0.1.1 → spiritcode-0.1.2}/tests/test_api.py +4 -4
- {spiritcode-0.1.1 → spiritcode-0.1.2}/tests/test_cli.py +16 -12
- {spiritcode-0.1.1 → spiritcode-0.1.2}/tests/test_config_store.py +8 -8
- {spiritcode-0.1.1 → spiritcode-0.1.2}/tests/test_keyboard.py +3 -3
- {spiritcode-0.1.1 → spiritcode-0.1.2}/tests/test_permissions.py +3 -3
- {spiritcode-0.1.1 → spiritcode-0.1.2}/tests/test_tools.py +5 -3
- {spiritcode-0.1.1 → spiritcode-0.1.2}/tests/test_ui.py +12 -12
- spiritcode-0.1.1/src/spiritcode/cli.py +0 -461
- {spiritcode-0.1.1 → spiritcode-0.1.2}/.gitignore +0 -0
- {spiritcode-0.1.1 → spiritcode-0.1.2/docs}/SERVER_CONTRACT.md +0 -0
- /spiritcode-0.1.1/image.png → /spiritcode-0.1.2/images/cli.png +0 -0
- {spiritcode-0.1.1 → spiritcode-0.1.2}/scripts/check_install.py +0 -0
- {spiritcode-0.1.1 → spiritcode-0.1.2}/scripts/publish.py +0 -0
- {spiritcode-0.1.1 → spiritcode-0.1.2}/src/spiritcode/__main__.py +0 -0
- {spiritcode-0.1.1/src/spiritcode → spiritcode-0.1.2/src/spiritcode/core}/credentials.py +0 -0
- {spiritcode-0.1.1/src/spiritcode → spiritcode-0.1.2/src/spiritcode/ui}/commands.py +0 -0
- {spiritcode-0.1.1 → spiritcode-0.1.2}/tests/__init__.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: spiritcode
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.2
|
|
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
|
-

|
|
30
30
|
|
|
31
31
|
## Установка
|
|
32
32
|
|
|
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
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Context, token budget, and request diagnostics."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from spiritcode.constants import DEFAULT_OUTPUT_TOKENS
|
|
7
|
+
from spiritcode.core.agent import Agent
|
|
8
|
+
from spiritcode.core.context import estimate_tokens, input_budget, system_context
|
|
9
|
+
from spiritcode.ui.interface import UI
|
|
10
|
+
|
|
11
|
+
DIAGNOSTIC_STATUSES = {"completed": "завершён", "error": "ошибка", "cancelled": "прерван"}
|
|
12
|
+
|
|
13
|
+
DIAGNOSTIC_KINDS = {"generation": "генерация", "compaction": "сжатие"}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
async def show_context(session: dict[str, Any], agent: Agent | None, ui: UI) -> None:
|
|
17
|
+
rows = [("Сессия", session["id"]), ("Модель", agent.model.id if agent else "не выбрана")]
|
|
18
|
+
|
|
19
|
+
if agent:
|
|
20
|
+
context = {
|
|
21
|
+
"role": "system",
|
|
22
|
+
"content": await asyncio.to_thread(system_context, agent.tools.root),
|
|
23
|
+
}
|
|
24
|
+
output = min(DEFAULT_OUTPUT_TOKENS, agent.model.max_output_tokens or DEFAULT_OUTPUT_TOKENS)
|
|
25
|
+
budget = input_budget(agent.model.context_window, output)
|
|
26
|
+
estimated = estimate_tokens([context, *agent.messages]) + estimate_tokens(
|
|
27
|
+
agent.payload([]).get("tools", [])
|
|
28
|
+
)
|
|
29
|
+
rows.extend(
|
|
30
|
+
[
|
|
31
|
+
(
|
|
32
|
+
"Контекст (оценка)",
|
|
33
|
+
f"≈ {estimated} / {budget} токенов · {estimated / budget:.0%}",
|
|
34
|
+
),
|
|
35
|
+
(
|
|
36
|
+
"Окно модели",
|
|
37
|
+
str(agent.model.context_window)
|
|
38
|
+
if agent.model.context_window
|
|
39
|
+
else "неизвестно · бюджет рассчитан из резервного окна",
|
|
40
|
+
),
|
|
41
|
+
("Резерв ответа", f"{output} токенов"),
|
|
42
|
+
]
|
|
43
|
+
)
|
|
44
|
+
else:
|
|
45
|
+
rows.append(("Контекст", "Выберите /model для оценки бюджета"))
|
|
46
|
+
|
|
47
|
+
diagnostics = session.get("diagnostics", [])
|
|
48
|
+
rows.append(("Запросов в сессии", str(len(diagnostics))))
|
|
49
|
+
|
|
50
|
+
if diagnostics:
|
|
51
|
+
latest = diagnostics[-1]
|
|
52
|
+
usage = latest.get("usage") or {}
|
|
53
|
+
rows.extend(
|
|
54
|
+
[
|
|
55
|
+
("Последний запрос", DIAGNOSTIC_KINDS.get(latest["kind"], latest["kind"])),
|
|
56
|
+
("Статус", DIAGNOSTIC_STATUSES.get(latest["status"], latest["status"])),
|
|
57
|
+
("Время UTC", latest["at"]),
|
|
58
|
+
("Модель запроса", latest.get("model") or "нет данных"),
|
|
59
|
+
("Request ID", latest.get("request_id") or "нет данных"),
|
|
60
|
+
]
|
|
61
|
+
)
|
|
62
|
+
for key, label in (
|
|
63
|
+
("prompt_tokens", "Входные токены (сервер)"),
|
|
64
|
+
("completion_tokens", "Выходные токены (сервер)"),
|
|
65
|
+
("total_tokens", "Всего токенов (сервер)"),
|
|
66
|
+
):
|
|
67
|
+
value = usage.get(key)
|
|
68
|
+
rows.append((label, str(value) if value is not None else "нет данных"))
|
|
69
|
+
else:
|
|
70
|
+
rows.extend([("Request ID", "нет данных"), ("Токены (сервер)", "нет данных")])
|
|
71
|
+
|
|
72
|
+
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"]))
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Model catalog, selection, and switching."""
|
|
2
|
+
|
|
3
|
+
from decimal import Decimal
|
|
4
|
+
|
|
5
|
+
from prompt_toolkit.completion import FuzzyWordCompleter
|
|
6
|
+
|
|
7
|
+
from spiritcode.commands.chat import Chat
|
|
8
|
+
from spiritcode.core.agent import Agent
|
|
9
|
+
from spiritcode.core.api import ApiError, Client
|
|
10
|
+
from spiritcode.core.config import Settings
|
|
11
|
+
from spiritcode.core.models import Model
|
|
12
|
+
from spiritcode.sanitize import clean
|
|
13
|
+
from spiritcode.ui.interface import UI
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def model_rows(models: list[Model]) -> list[tuple[str, str]]:
|
|
17
|
+
return [
|
|
18
|
+
(
|
|
19
|
+
model.id,
|
|
20
|
+
(
|
|
21
|
+
f"{Decimal(model.price_per_million_tokens):.2f}"
|
|
22
|
+
if model.price_per_million_tokens is not None
|
|
23
|
+
else "неизвестно"
|
|
24
|
+
)
|
|
25
|
+
+ " RUB / 1 MTok",
|
|
26
|
+
)
|
|
27
|
+
for model in models
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def set_model_label(ui: UI, model: Model | None) -> None:
|
|
32
|
+
ui.model_label = clean(model.id) if model else "модель не выбрана · /model"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
async def resolve_model(client: Client, ui: UI, requested: str | None) -> Model | None:
|
|
36
|
+
if not requested:
|
|
37
|
+
return None
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
models = await client.models()
|
|
41
|
+
except ApiError as exc:
|
|
42
|
+
ui.notice(
|
|
43
|
+
"Не удалось загрузить модель", str(exc) + " Выберите модель через /model.", "warning"
|
|
44
|
+
)
|
|
45
|
+
return None
|
|
46
|
+
|
|
47
|
+
ui.completer.models = [model.id for model in models]
|
|
48
|
+
selected = next((model for model in models if model.id == requested), None)
|
|
49
|
+
if selected is None:
|
|
50
|
+
ui.notice("Модель недоступна", "Выберите доступную модель через /model.", "warning")
|
|
51
|
+
elif selected.tool_calling is False:
|
|
52
|
+
ui.muted("Режим чата · модель не поддерживает инструменты. Выберите другую через /model.")
|
|
53
|
+
set_model_label(ui, selected)
|
|
54
|
+
return selected
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
async def choose_model(
|
|
58
|
+
client: Client, settings: Settings, ui: UI, requested: str | None = None
|
|
59
|
+
) -> Model | None:
|
|
60
|
+
models = await client.models()
|
|
61
|
+
ui.completer.models = [model.id for model in models]
|
|
62
|
+
if not models:
|
|
63
|
+
raise ApiError("В каталоге SpiritLM нет доступных моделей.")
|
|
64
|
+
|
|
65
|
+
if requested is None:
|
|
66
|
+
ui.table(model_rows(models), "Модели SpiritLM")
|
|
67
|
+
requested = (
|
|
68
|
+
await ui.ask(
|
|
69
|
+
"Модель (пустая строка — назад): ",
|
|
70
|
+
completer=FuzzyWordCompleter([model.id for model in models]),
|
|
71
|
+
)
|
|
72
|
+
).strip()
|
|
73
|
+
if not requested:
|
|
74
|
+
return None
|
|
75
|
+
|
|
76
|
+
selected = next((model for model in models if model.id == requested), None)
|
|
77
|
+
if selected is None:
|
|
78
|
+
raise ValueError("Выберите точный ID модели из /model.")
|
|
79
|
+
|
|
80
|
+
settings.save_model(selected.id)
|
|
81
|
+
set_model_label(ui, selected)
|
|
82
|
+
return selected
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
async def apply_model(chat: Chat, model: Model) -> None:
|
|
86
|
+
chat.session["model"] = model.id
|
|
87
|
+
|
|
88
|
+
if chat.agent:
|
|
89
|
+
chat.agent.model = model
|
|
90
|
+
chat.agent.save()
|
|
91
|
+
else:
|
|
92
|
+
chat.agent = Agent(chat.client, model, chat.session, chat.store, chat.tools, chat.ui)
|
|
93
|
+
|
|
94
|
+
chat.model = model
|
|
95
|
+
chat.store.save(chat.session)
|
|
96
|
+
chat.ui.reset(model.id, chat.root)
|
|
97
|
+
|
|
98
|
+
if model.tool_calling is False:
|
|
99
|
+
chat.ui.notice(
|
|
100
|
+
"Режим чата",
|
|
101
|
+
"Модель не поддерживает инструменты. Выберите другую через /model.",
|
|
102
|
+
"warning",
|
|
103
|
+
)
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Session switching and listing."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from spiritcode.commands.chat import Chat
|
|
8
|
+
from spiritcode.commands.model import resolve_model
|
|
9
|
+
from spiritcode.core.agent import Agent
|
|
10
|
+
from spiritcode.core.store import Store, new_session
|
|
11
|
+
from spiritcode.tools.executor import Tools
|
|
12
|
+
from spiritcode.ui.interface import UI
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
async def replace_session(chat: Chat, command: str, argument: str) -> None:
|
|
16
|
+
replacement = (
|
|
17
|
+
chat.store.load(argument)
|
|
18
|
+
if command == "/resume"
|
|
19
|
+
else new_session(chat.root, chat.model.id if chat.model else "")
|
|
20
|
+
)
|
|
21
|
+
replacement_root = await asyncio.to_thread(Path(replacement["root"]).resolve)
|
|
22
|
+
if not replacement_root.is_dir():
|
|
23
|
+
raise ValueError("Каталог сессии не существует.")
|
|
24
|
+
|
|
25
|
+
if command == "/resume":
|
|
26
|
+
chat.model = await resolve_model(chat.client, chat.ui, replacement["model"])
|
|
27
|
+
|
|
28
|
+
chat.root, chat.session = replacement_root, replacement
|
|
29
|
+
chat.tools = Tools(chat.root, chat.ui, chat.session["snapshots"], chat.settings)
|
|
30
|
+
chat.agent = (
|
|
31
|
+
Agent(chat.client, chat.model, chat.session, chat.store, chat.tools, chat.ui)
|
|
32
|
+
if chat.model
|
|
33
|
+
else None
|
|
34
|
+
)
|
|
35
|
+
chat.store.save(chat.session)
|
|
36
|
+
os.chdir(chat.root)
|
|
37
|
+
chat.ui.reset(chat.model.id if chat.model else None, chat.root)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def show_sessions(store: Store, ui: UI) -> None:
|
|
41
|
+
ui.table(
|
|
42
|
+
[(row[0], f"{row[1] or 'без модели'} · {row[2]} · {row[3]} UTC") for row in store.list()],
|
|
43
|
+
"Сессии",
|
|
44
|
+
)
|