spiritcode 0.1.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.
- spiritcode/__init__.py +3 -0
- spiritcode/__main__.py +3 -0
- spiritcode/agent.py +244 -0
- spiritcode/api.py +138 -0
- spiritcode/cli.py +456 -0
- spiritcode/commands.py +43 -0
- spiritcode/config.py +112 -0
- spiritcode/context.py +85 -0
- spiritcode/credentials.py +35 -0
- spiritcode/display.py +116 -0
- spiritcode/keyboard.py +99 -0
- spiritcode/permissions.py +40 -0
- spiritcode/store.py +81 -0
- spiritcode/tools.py +366 -0
- spiritcode/ui.py +409 -0
- spiritcode-0.1.0.dist-info/METADATA +75 -0
- spiritcode-0.1.0.dist-info/RECORD +19 -0
- spiritcode-0.1.0.dist-info/WHEEL +4 -0
- spiritcode-0.1.0.dist-info/entry_points.txt +3 -0
spiritcode/cli.py
ADDED
|
@@ -0,0 +1,456 @@
|
|
|
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 decimal import Decimal
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from prompt_toolkit.completion import FuzzyWordCompleter
|
|
12
|
+
|
|
13
|
+
from spiritcode import __version__
|
|
14
|
+
from spiritcode.agent import Agent
|
|
15
|
+
from spiritcode.api import ApiError, Client, Model
|
|
16
|
+
from spiritcode.commands import help_text
|
|
17
|
+
from spiritcode.config import ACCOUNT_TIMEOUT, DEFAULT_OUTPUT_TOKENS, Settings
|
|
18
|
+
from spiritcode.context import estimate_tokens, input_budget, project_root, system_context
|
|
19
|
+
from spiritcode.credentials import Credentials
|
|
20
|
+
from spiritcode.display import account_rows
|
|
21
|
+
from spiritcode.store import Store, new_session
|
|
22
|
+
from spiritcode.tools import Tools, unified
|
|
23
|
+
from spiritcode.ui import UI, clean
|
|
24
|
+
|
|
25
|
+
PERMISSIONS = """Чтение и правки в проекте разрешены автоматически.
|
|
26
|
+
Каждая команда и каждый доступ вне проекта требуют отдельного разрешения.
|
|
27
|
+
Секреты читаются только после разрешения и не редактируются инструментами.
|
|
28
|
+
Симлинки проверяются по фактическому пути. Команды имеют права пользователя:
|
|
29
|
+
подтверждение не является системной песочницей. /undo не отменяет команды."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class RussianParser(argparse.ArgumentParser):
|
|
33
|
+
def __init__(self, **kwargs: Any) -> None:
|
|
34
|
+
kwargs["add_help"] = False
|
|
35
|
+
super().__init__(**kwargs)
|
|
36
|
+
self._positionals.title = "Команды"
|
|
37
|
+
self._optionals.title = "Параметры"
|
|
38
|
+
self.add_argument("-h", "--help", action="help", help="Показать справку и выйти")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def model_rows(models: list[Model]) -> list[tuple[str, str]]:
|
|
42
|
+
return [
|
|
43
|
+
(
|
|
44
|
+
model.id,
|
|
45
|
+
(
|
|
46
|
+
f"{Decimal(model.price_per_million_tokens):.2f}"
|
|
47
|
+
if model.price_per_million_tokens is not None
|
|
48
|
+
else "неизвестно"
|
|
49
|
+
)
|
|
50
|
+
+ " RUB / 1 MTok",
|
|
51
|
+
)
|
|
52
|
+
for model in models
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def set_model_label(ui: UI, model: Model | None) -> None:
|
|
57
|
+
ui.model_label = clean(model.id) if model else "модель не выбрана · /model"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
async def resolve_model(client: Client, ui: UI, requested: str | None) -> Model | None:
|
|
61
|
+
if not requested:
|
|
62
|
+
return None
|
|
63
|
+
try:
|
|
64
|
+
models = await client.models()
|
|
65
|
+
except ApiError as exc:
|
|
66
|
+
ui.notice(
|
|
67
|
+
"Не удалось загрузить модель", str(exc) + " Выберите модель через /model.", "warning"
|
|
68
|
+
)
|
|
69
|
+
return None
|
|
70
|
+
ui.completer.models = [model.id for model in models]
|
|
71
|
+
selected = next((model for model in models if model.id == requested), None)
|
|
72
|
+
if selected is None:
|
|
73
|
+
ui.notice("Модель недоступна", "Выберите доступную модель через /model.", "warning")
|
|
74
|
+
elif selected.tool_calling is not True:
|
|
75
|
+
ui.muted("Режим чата · поддержка инструментов не подтверждена сервером.")
|
|
76
|
+
set_model_label(ui, selected)
|
|
77
|
+
return selected
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
async def choose_model(
|
|
81
|
+
client: Client, settings: Settings, ui: UI, requested: str | None = None
|
|
82
|
+
) -> Model | None:
|
|
83
|
+
models = await client.models()
|
|
84
|
+
ui.completer.models = [model.id for model in models]
|
|
85
|
+
if not models:
|
|
86
|
+
raise ApiError("В каталоге SpiritLM нет доступных моделей.")
|
|
87
|
+
if requested is None:
|
|
88
|
+
ui.table(model_rows(models), "Модели SpiritLM")
|
|
89
|
+
requested = (
|
|
90
|
+
await ui.ask(
|
|
91
|
+
"Модель (пустая строка — назад): ",
|
|
92
|
+
completer=FuzzyWordCompleter([model.id for model in models]),
|
|
93
|
+
)
|
|
94
|
+
).strip()
|
|
95
|
+
if not requested:
|
|
96
|
+
return None
|
|
97
|
+
selected = next((model for model in models if model.id == requested), None)
|
|
98
|
+
if selected is None:
|
|
99
|
+
raise ValueError("Выберите точный ID модели из /model.")
|
|
100
|
+
settings.save_model(selected.id)
|
|
101
|
+
set_model_label(ui, selected)
|
|
102
|
+
return selected
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
async def show_context(session: dict[str, Any], agent: Agent | None, ui: UI) -> None:
|
|
106
|
+
rows = [("Сессия", session["id"]), ("Модель", agent.model.id if agent else "не выбрана")]
|
|
107
|
+
if agent:
|
|
108
|
+
context = {
|
|
109
|
+
"role": "system",
|
|
110
|
+
"content": await asyncio.to_thread(system_context, agent.tools.root),
|
|
111
|
+
}
|
|
112
|
+
output = min(DEFAULT_OUTPUT_TOKENS, agent.model.max_output_tokens or DEFAULT_OUTPUT_TOKENS)
|
|
113
|
+
budget = input_budget(agent.model.context_window, output)
|
|
114
|
+
estimated = estimate_tokens([context, *agent.messages]) + estimate_tokens(
|
|
115
|
+
agent.payload([]).get("tools", [])
|
|
116
|
+
)
|
|
117
|
+
rows.extend(
|
|
118
|
+
[
|
|
119
|
+
(
|
|
120
|
+
"Контекст (оценка)",
|
|
121
|
+
f"≈ {estimated} / {budget} токенов · {estimated / budget:.0%}",
|
|
122
|
+
),
|
|
123
|
+
(
|
|
124
|
+
"Окно модели",
|
|
125
|
+
str(agent.model.context_window)
|
|
126
|
+
if agent.model.context_window
|
|
127
|
+
else "неизвестно · бюджет рассчитан из резервного окна",
|
|
128
|
+
),
|
|
129
|
+
("Резерв ответа", f"{output} токенов"),
|
|
130
|
+
]
|
|
131
|
+
)
|
|
132
|
+
else:
|
|
133
|
+
rows.append(("Контекст", "Выберите /model для оценки бюджета"))
|
|
134
|
+
diagnostics = session.get("diagnostics", [])
|
|
135
|
+
rows.append(("Запросов в сессии", str(len(diagnostics))))
|
|
136
|
+
if diagnostics:
|
|
137
|
+
latest = diagnostics[-1]
|
|
138
|
+
statuses = {"completed": "завершён", "error": "ошибка", "cancelled": "прерван"}
|
|
139
|
+
kinds = {"generation": "генерация", "compaction": "сжатие"}
|
|
140
|
+
usage = latest.get("usage") or {}
|
|
141
|
+
rows.extend(
|
|
142
|
+
[
|
|
143
|
+
("Последний запрос", kinds.get(latest["kind"], latest["kind"])),
|
|
144
|
+
("Статус", statuses.get(latest["status"], latest["status"])),
|
|
145
|
+
("Время UTC", latest["at"]),
|
|
146
|
+
("Модель запроса", latest.get("model") or "нет данных"),
|
|
147
|
+
("Request ID", latest.get("request_id") or "нет данных"),
|
|
148
|
+
]
|
|
149
|
+
)
|
|
150
|
+
for key, label in (
|
|
151
|
+
("prompt_tokens", "Входные токены (сервер)"),
|
|
152
|
+
("completion_tokens", "Выходные токены (сервер)"),
|
|
153
|
+
("total_tokens", "Всего токенов (сервер)"),
|
|
154
|
+
):
|
|
155
|
+
value = usage.get(key)
|
|
156
|
+
rows.append((label, str(value) if value is not None else "нет данных"))
|
|
157
|
+
else:
|
|
158
|
+
rows.extend([("Request ID", "нет данных"), ("Токены (сервер)", "нет данных")])
|
|
159
|
+
ui.table(rows, "Контекст и диагностика")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
async def account(client: Client, ui: UI, name: str = "profile", period: str = "2d") -> None:
|
|
163
|
+
if name == "usage" and period not in {"2d", "7d", "30d", "all"}:
|
|
164
|
+
raise ValueError("Период: 2d, 7d, 30d или all.")
|
|
165
|
+
value = await client.get(name, **({"period": period} if name == "usage" else {}))
|
|
166
|
+
ui.table(account_rows(value), "Аккаунт SpiritLM")
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
async def load_account_label(client: Client, ui: UI) -> None:
|
|
170
|
+
async def optional_account(name: str) -> dict[str, Any] | None:
|
|
171
|
+
try:
|
|
172
|
+
async with asyncio.timeout(ACCOUNT_TIMEOUT):
|
|
173
|
+
value = await client.get(name)
|
|
174
|
+
return value if isinstance(value, dict) else None
|
|
175
|
+
except (ApiError, TimeoutError):
|
|
176
|
+
return None
|
|
177
|
+
|
|
178
|
+
profile, subscription = await asyncio.gather(
|
|
179
|
+
optional_account("profile"), optional_account("subscription")
|
|
180
|
+
)
|
|
181
|
+
identity = "Пользователь"
|
|
182
|
+
if profile:
|
|
183
|
+
username = profile.get("username")
|
|
184
|
+
name = profile.get("name")
|
|
185
|
+
if isinstance(username, str) and username.strip():
|
|
186
|
+
identity = "@" + username.strip().lstrip("@")
|
|
187
|
+
elif isinstance(name, str) and name.strip():
|
|
188
|
+
identity = name.strip()
|
|
189
|
+
plan = "тариф недоступен"
|
|
190
|
+
if subscription is not None and "current" in subscription:
|
|
191
|
+
current = subscription["current"]
|
|
192
|
+
if current is None:
|
|
193
|
+
plan = "Free"
|
|
194
|
+
elif isinstance(current, dict):
|
|
195
|
+
plan_name = current.get("planName")
|
|
196
|
+
if isinstance(plan_name, str) and plan_name.strip():
|
|
197
|
+
plan = plan_name.strip()
|
|
198
|
+
ui.account_label = clean(f"{identity} | {plan}")
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
async def cancellable[T](operation: Coroutine[Any, Any, T], ui: UI) -> T | None:
|
|
202
|
+
task = asyncio.create_task(operation)
|
|
203
|
+
loop = asyncio.get_running_loop()
|
|
204
|
+
# signal.signal works on Windows as well; event-loop signal handlers do not.
|
|
205
|
+
previous = signal.getsignal(signal.SIGINT)
|
|
206
|
+
signal.signal(signal.SIGINT, lambda *_: loop.call_soon_threadsafe(task.cancel))
|
|
207
|
+
try:
|
|
208
|
+
return await task
|
|
209
|
+
except asyncio.CancelledError:
|
|
210
|
+
ui.notice("Операция прервана")
|
|
211
|
+
return None
|
|
212
|
+
finally:
|
|
213
|
+
signal.signal(signal.SIGINT, previous)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
async def interactive(
|
|
217
|
+
client: Client,
|
|
218
|
+
settings: Settings,
|
|
219
|
+
ui: UI,
|
|
220
|
+
store: Store,
|
|
221
|
+
session: dict[str, Any] | None = None,
|
|
222
|
+
*,
|
|
223
|
+
header_shown: bool = False,
|
|
224
|
+
) -> None:
|
|
225
|
+
root = Path(session["root"]) if session else project_root(Path.cwd())
|
|
226
|
+
if not root.is_dir():
|
|
227
|
+
raise ValueError("Каталог сохранённого проекта больше не существует.")
|
|
228
|
+
requested = session["model"] if session else settings.model
|
|
229
|
+
if not header_shown:
|
|
230
|
+
ui.header(requested, root)
|
|
231
|
+
model = await resolve_model(client, ui, requested)
|
|
232
|
+
set_model_label(ui, model)
|
|
233
|
+
session = session or new_session(root, model.id if model else "")
|
|
234
|
+
tools = Tools(root, ui, session["snapshots"])
|
|
235
|
+
agent = Agent(client, model, session, store, tools, ui) if model else None
|
|
236
|
+
store.save(session)
|
|
237
|
+
os.chdir(root)
|
|
238
|
+
if model is None:
|
|
239
|
+
ui.muted("Выберите /model, чтобы отправить первое сообщение.")
|
|
240
|
+
interrupted = False
|
|
241
|
+
while True:
|
|
242
|
+
ui.completer.sessions = [
|
|
243
|
+
(row[0], f"{row[1] or 'без модели'} · {row[2]}") for row in store.list()
|
|
244
|
+
]
|
|
245
|
+
try:
|
|
246
|
+
text = (await ui.ask(chat=True)).strip()
|
|
247
|
+
except EOFError:
|
|
248
|
+
break
|
|
249
|
+
except KeyboardInterrupt:
|
|
250
|
+
if not ui.interrupted_empty:
|
|
251
|
+
interrupted = False
|
|
252
|
+
ui.muted("Ввод очищен.")
|
|
253
|
+
continue
|
|
254
|
+
if interrupted:
|
|
255
|
+
break
|
|
256
|
+
interrupted = True
|
|
257
|
+
ui.muted("Нажмите Ctrl+C ещё раз для выхода.")
|
|
258
|
+
continue
|
|
259
|
+
interrupted = False
|
|
260
|
+
if not text:
|
|
261
|
+
continue
|
|
262
|
+
try:
|
|
263
|
+
if not text.startswith("/"):
|
|
264
|
+
if agent is None:
|
|
265
|
+
ui.notice(
|
|
266
|
+
"Модель не выбрана",
|
|
267
|
+
"Используйте /model, затем отправьте сообщение.",
|
|
268
|
+
"warning",
|
|
269
|
+
)
|
|
270
|
+
continue
|
|
271
|
+
await cancellable(agent.turn(text), ui)
|
|
272
|
+
continue
|
|
273
|
+
command, *parts = text.split(maxsplit=1)
|
|
274
|
+
argument = parts[0].strip() if parts else ""
|
|
275
|
+
client.request_id = None
|
|
276
|
+
if command == "/exit":
|
|
277
|
+
break
|
|
278
|
+
if command == "/help":
|
|
279
|
+
ui.say(help_text())
|
|
280
|
+
elif command == "/permissions":
|
|
281
|
+
ui.notice("Разрешения", PERMISSIONS)
|
|
282
|
+
elif command == "/context":
|
|
283
|
+
await cancellable(show_context(session, agent, ui), ui)
|
|
284
|
+
elif command == "/model":
|
|
285
|
+
chosen = await cancellable(choose_model(client, settings, ui, argument or None), ui)
|
|
286
|
+
if chosen is None:
|
|
287
|
+
continue
|
|
288
|
+
model = chosen
|
|
289
|
+
session["model"] = model.id
|
|
290
|
+
if agent:
|
|
291
|
+
agent.model = model
|
|
292
|
+
agent.save()
|
|
293
|
+
else:
|
|
294
|
+
agent = Agent(client, model, session, store, tools, ui)
|
|
295
|
+
store.save(session)
|
|
296
|
+
ui.reset(model.id, root)
|
|
297
|
+
elif command in {"/profile", "/balance", "/subscription", "/usage"}:
|
|
298
|
+
await cancellable(account(client, ui, command[1:], argument or "2d"), ui)
|
|
299
|
+
elif command == "/sessions":
|
|
300
|
+
show_sessions(store, ui)
|
|
301
|
+
elif command in {"/new", "/resume"}:
|
|
302
|
+
replacement = (
|
|
303
|
+
store.load(argument)
|
|
304
|
+
if command == "/resume"
|
|
305
|
+
else new_session(root, model.id if model else "")
|
|
306
|
+
)
|
|
307
|
+
replacement_root = await asyncio.to_thread(Path(replacement["root"]).resolve)
|
|
308
|
+
if not replacement_root.is_dir():
|
|
309
|
+
raise ValueError("Каталог сессии не существует.")
|
|
310
|
+
if command == "/resume":
|
|
311
|
+
model = await resolve_model(client, ui, replacement["model"])
|
|
312
|
+
root, session = replacement_root, replacement
|
|
313
|
+
tools = Tools(root, ui, session["snapshots"])
|
|
314
|
+
agent = Agent(client, model, session, store, tools, ui) if model else None
|
|
315
|
+
store.save(session)
|
|
316
|
+
os.chdir(root)
|
|
317
|
+
ui.reset(model.id if model else None, root)
|
|
318
|
+
elif command == "/compact":
|
|
319
|
+
if agent:
|
|
320
|
+
await cancellable(agent.compact(), ui)
|
|
321
|
+
else:
|
|
322
|
+
ui.notice(
|
|
323
|
+
"Модель не выбрана", "Используйте /model для сжатия контекста.", "warning"
|
|
324
|
+
)
|
|
325
|
+
elif command == "/undo":
|
|
326
|
+
result = await tools.undo()
|
|
327
|
+
session["messages"].append(
|
|
328
|
+
{"role": "user", "content": "Результат /undo: " + result}
|
|
329
|
+
)
|
|
330
|
+
store.save(session)
|
|
331
|
+
ui.notice("Отмена правок", result)
|
|
332
|
+
elif command == "/diff":
|
|
333
|
+
if not tools.snapshots:
|
|
334
|
+
ui.muted("В этой сессии пока нет правок.")
|
|
335
|
+
for group in tools.snapshots:
|
|
336
|
+
for change in group:
|
|
337
|
+
ui.diff(unified(change["path"], change["before"], change["after"]))
|
|
338
|
+
else:
|
|
339
|
+
ui.notice(
|
|
340
|
+
"Неизвестная команда",
|
|
341
|
+
"Введите / для выбора команды или /help для справки.",
|
|
342
|
+
"warning",
|
|
343
|
+
)
|
|
344
|
+
except (ApiError, ValueError, OSError) as exc:
|
|
345
|
+
if isinstance(exc, ApiError) and text.startswith("/") and command != "/compact":
|
|
346
|
+
session.setdefault("diagnostics", []).append(
|
|
347
|
+
{
|
|
348
|
+
"at": datetime.now(UTC).isoformat(),
|
|
349
|
+
"kind": command,
|
|
350
|
+
"status": "error",
|
|
351
|
+
"request_id": exc.request_id or client.request_id,
|
|
352
|
+
"usage": None,
|
|
353
|
+
}
|
|
354
|
+
)
|
|
355
|
+
store.save(session)
|
|
356
|
+
ui.notice("Ошибка", str(exc), "error")
|
|
357
|
+
except EOFError:
|
|
358
|
+
break
|
|
359
|
+
except KeyboardInterrupt:
|
|
360
|
+
ui.notice("Операция прервана")
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def show_sessions(store: Store, ui: UI) -> None:
|
|
364
|
+
ui.table(
|
|
365
|
+
[(row[0], f"{row[1] or 'без модели'} · {row[2]} · {row[3]} UTC") for row in store.list()],
|
|
366
|
+
"Сессии",
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
async def run(args: argparse.Namespace) -> None:
|
|
371
|
+
settings = Settings.load(args.base_url, args.model)
|
|
372
|
+
ui, credentials, store = UI(settings.color), Credentials(settings.base_url), Store()
|
|
373
|
+
client: Client | None = None
|
|
374
|
+
try:
|
|
375
|
+
session = store.load(args.id) if args.command == "resume" else None
|
|
376
|
+
if session and (args.model or os.getenv("SPIRITLM_MODEL")):
|
|
377
|
+
session["model"] = args.model or os.environ["SPIRITLM_MODEL"]
|
|
378
|
+
chat = args.command in {None, "resume"}
|
|
379
|
+
if chat:
|
|
380
|
+
root = Path(session["root"]) if session else project_root(Path.cwd())
|
|
381
|
+
ui.header(session["model"] if session else settings.model, root)
|
|
382
|
+
if args.command == "sessions":
|
|
383
|
+
show_sessions(store, ui)
|
|
384
|
+
return
|
|
385
|
+
if args.command == "logout":
|
|
386
|
+
ui.say("Ключ удалён." if credentials.delete() else "Системное хранилище недоступно.")
|
|
387
|
+
if os.getenv("SPIRITLM_API_KEY"):
|
|
388
|
+
ui.say("Ключ окружения активен до удаления SPIRITLM_API_KEY из оболочки.")
|
|
389
|
+
return
|
|
390
|
+
key = credentials.get()
|
|
391
|
+
if args.command == "login" or not key:
|
|
392
|
+
key = (await ui.ask("API-ключ SpiritLM: ", secret=True)).strip()
|
|
393
|
+
if not key:
|
|
394
|
+
raise ValueError("API-ключ не указан.")
|
|
395
|
+
client = Client(settings, key)
|
|
396
|
+
await client.get("models")
|
|
397
|
+
if credentials.save(key):
|
|
398
|
+
ui.notice("Вход выполнен", "API-ключ сохранён в системном хранилище.", "success")
|
|
399
|
+
else:
|
|
400
|
+
ui.notice(
|
|
401
|
+
"Keyring недоступен", "Ключ хранится только в памяти этого процесса.", "warning"
|
|
402
|
+
)
|
|
403
|
+
if args.command == "login":
|
|
404
|
+
ui.say("Для следующего запуска задайте SPIRITLM_API_KEY или настройте keyring.")
|
|
405
|
+
if args.command == "login":
|
|
406
|
+
return
|
|
407
|
+
client = client or Client(settings, key)
|
|
408
|
+
if args.command == "models":
|
|
409
|
+
models = await client.models()
|
|
410
|
+
ui.table(model_rows(models), "Модели SpiritLM")
|
|
411
|
+
elif args.command == "account":
|
|
412
|
+
for name in ("profile", "balance", "subscription", "usage"):
|
|
413
|
+
try:
|
|
414
|
+
await account(client, ui, name)
|
|
415
|
+
except ApiError as exc:
|
|
416
|
+
ui.notice("Ошибка", str(exc), "error")
|
|
417
|
+
else:
|
|
418
|
+
await load_account_label(client, ui)
|
|
419
|
+
root = Path(session["root"]) if session else project_root(Path.cwd())
|
|
420
|
+
ui.reset(session["model"] if session else settings.model, root)
|
|
421
|
+
await interactive(client, settings, ui, store, session, header_shown=True)
|
|
422
|
+
finally:
|
|
423
|
+
if client:
|
|
424
|
+
await client.close()
|
|
425
|
+
store.close()
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def main() -> None:
|
|
429
|
+
parser = RussianParser(prog="sprt", description="SpiritCode — кодинг-агент для SpiritLM")
|
|
430
|
+
parser.add_argument(
|
|
431
|
+
"--version",
|
|
432
|
+
action="version",
|
|
433
|
+
version=__version__,
|
|
434
|
+
help="Показать версию и выйти",
|
|
435
|
+
)
|
|
436
|
+
parser.add_argument("--base-url", help="Адрес SpiritLM без /v1")
|
|
437
|
+
parser.add_argument("--model", help="ID модели SpiritLM")
|
|
438
|
+
commands = parser.add_subparsers(dest="command")
|
|
439
|
+
for command, description in {
|
|
440
|
+
"login": "Войти",
|
|
441
|
+
"logout": "Удалить ключ",
|
|
442
|
+
"models": "Каталог моделей",
|
|
443
|
+
"account": "Аккаунт SpiritLM",
|
|
444
|
+
"sessions": "Сохранённые сессии",
|
|
445
|
+
}.items():
|
|
446
|
+
commands.add_parser(command, help=description)
|
|
447
|
+
resume = commands.add_parser("resume", help="Продолжить сессию")
|
|
448
|
+
resume.add_argument("id")
|
|
449
|
+
args = parser.parse_args()
|
|
450
|
+
try:
|
|
451
|
+
asyncio.run(run(args))
|
|
452
|
+
except (EOFError, KeyboardInterrupt):
|
|
453
|
+
pass
|
|
454
|
+
except (ApiError, ValueError, OSError) as exc:
|
|
455
|
+
UI().notice("Ошибка", str(exc), "error")
|
|
456
|
+
raise SystemExit(1) from None
|
spiritcode/commands.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""The command palette and help share one source of descriptions and arguments."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass(frozen=True)
|
|
7
|
+
class Command:
|
|
8
|
+
name: str
|
|
9
|
+
description: str
|
|
10
|
+
arguments: str = ""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
COMMANDS = (
|
|
14
|
+
Command("/help", "Все команды и сочетания клавиш"),
|
|
15
|
+
Command("/model", "Поиск и смена модели", "[id]"),
|
|
16
|
+
Command("/context", "Контекст, токены и диагностика сессии"),
|
|
17
|
+
Command("/profile", "Профиль SpiritLM"),
|
|
18
|
+
Command("/balance", "Баланс аккаунта"),
|
|
19
|
+
Command("/subscription", "Подписка и доступные кредиты"),
|
|
20
|
+
Command("/usage", "Статистика аккаунта", "[2d|7d|30d|all]"),
|
|
21
|
+
Command("/new", "Начать новую сессию"),
|
|
22
|
+
Command("/sessions", "Сохранённые сессии"),
|
|
23
|
+
Command("/resume", "Продолжить сохранённую сессию", "<id>"),
|
|
24
|
+
Command("/compact", "Сжать контекст отдельным оплачиваемым запросом"),
|
|
25
|
+
Command("/diff", "Посмотреть правки сессии"),
|
|
26
|
+
Command("/undo", "Отменить последнюю группу правок"),
|
|
27
|
+
Command("/permissions", "Правила разрешений"),
|
|
28
|
+
Command("/exit", "Завершить SpiritCode"),
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def help_text() -> str:
|
|
33
|
+
commands = "\n".join(
|
|
34
|
+
f"{command.name}{' ' + command.arguments if command.arguments else ''} — "
|
|
35
|
+
f"{command.description}"
|
|
36
|
+
for command in COMMANDS
|
|
37
|
+
)
|
|
38
|
+
return commands + (
|
|
39
|
+
'\n\n@путь или @"путь с пробелами" — прикрепить файл'
|
|
40
|
+
"\nEnter — отправить; Shift+Enter — новая строка; стрелки — выбор / история"
|
|
41
|
+
"\nTab / Enter в меню — принять подсказку; Esc — закрыть меню"
|
|
42
|
+
"\nCtrl+C — прервать операцию; дважды в пустом вводе — выйти"
|
|
43
|
+
)
|
spiritcode/config.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Developer defaults and centralized URL/settings handling."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import tomllib
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from urllib.parse import urlsplit
|
|
8
|
+
|
|
9
|
+
from platformdirs import user_config_path, user_data_path
|
|
10
|
+
|
|
11
|
+
BASE_URL = "http://localhost:3000"
|
|
12
|
+
API_PATHS = {
|
|
13
|
+
"models": "/v1/models",
|
|
14
|
+
"metadata": "/v1/spiritcode/models",
|
|
15
|
+
"chat": "/v1/chat/completions",
|
|
16
|
+
"profile": "/v1/account",
|
|
17
|
+
"balance": "/v1/account/balance",
|
|
18
|
+
"subscription": "/v1/account/subscription",
|
|
19
|
+
"usage": "/v1/account/usage",
|
|
20
|
+
}
|
|
21
|
+
COLORS = {
|
|
22
|
+
"accent": "#ffe02e",
|
|
23
|
+
"text": "#f3f2ee",
|
|
24
|
+
"muted": "#a5a5a1",
|
|
25
|
+
"line": "#30302e",
|
|
26
|
+
"success": "#8fca93",
|
|
27
|
+
"error": "#ff6b6b",
|
|
28
|
+
"info": "#91b9ff",
|
|
29
|
+
}
|
|
30
|
+
BACKGROUND = "#080808"
|
|
31
|
+
STAR = r""" .-.
|
|
32
|
+
/ \
|
|
33
|
+
.--' '--.
|
|
34
|
+
/ | | \
|
|
35
|
+
\ /
|
|
36
|
+
'--. .--'
|
|
37
|
+
\ /
|
|
38
|
+
'-'"""
|
|
39
|
+
REQUEST_TIMEOUT = 100
|
|
40
|
+
ACCOUNT_TIMEOUT = 5
|
|
41
|
+
COMMAND_TIMEOUT = 120
|
|
42
|
+
MAX_ITERATIONS = 30
|
|
43
|
+
MAX_FILE_BYTES = 128_000
|
|
44
|
+
MAX_RESULT_CHARS = 24_000
|
|
45
|
+
MAX_FILES = 2_000
|
|
46
|
+
MAX_SSE_EVENT = 1_048_576
|
|
47
|
+
FALLBACK_CONTEXT = 16_000
|
|
48
|
+
DEFAULT_OUTPUT_TOKENS = 4_096
|
|
49
|
+
COMPACTION_THRESHOLD = 0.75
|
|
50
|
+
EXCLUDED = {".git", ".venv", "node_modules", "__pycache__", "dist", "build", ".next"}
|
|
51
|
+
SECRET_NAMES = {".env", ".npmrc", ".pypirc", "id_rsa", "id_ed25519", "credentials"}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def config_path() -> Path:
|
|
55
|
+
return user_config_path("spiritcode") / "config.toml"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def data_path() -> Path:
|
|
59
|
+
return user_data_path("spiritcode")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def validate_base_url(value: str) -> str:
|
|
63
|
+
parts = urlsplit(value)
|
|
64
|
+
local = parts.hostname in {"localhost", "127.0.0.1", "::1"}
|
|
65
|
+
if (
|
|
66
|
+
parts.scheme not in {"http", "https"}
|
|
67
|
+
or (parts.scheme == "http" and not local)
|
|
68
|
+
or not parts.hostname
|
|
69
|
+
or parts.username
|
|
70
|
+
or parts.password
|
|
71
|
+
or parts.query
|
|
72
|
+
or parts.fragment
|
|
73
|
+
or parts.path not in {"", "/"}
|
|
74
|
+
):
|
|
75
|
+
raise ValueError("Адрес SpiritLM: HTTPS origin без /v1; HTTP разрешён для localhost.")
|
|
76
|
+
return value.rstrip("/")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass
|
|
80
|
+
class Settings:
|
|
81
|
+
base_url: str = BASE_URL
|
|
82
|
+
model: str | None = None
|
|
83
|
+
color: bool = True
|
|
84
|
+
|
|
85
|
+
def url(self, name: str) -> str:
|
|
86
|
+
return self.base_url + API_PATHS[name]
|
|
87
|
+
|
|
88
|
+
@classmethod
|
|
89
|
+
def load(cls, base_url: str | None = None, model: str | None = None) -> "Settings":
|
|
90
|
+
path = config_path()
|
|
91
|
+
values = tomllib.loads(path.read_text("utf-8")) if path.exists() else {}
|
|
92
|
+
return cls(
|
|
93
|
+
validate_base_url(
|
|
94
|
+
base_url or os.getenv("SPIRITLM_BASE_URL") or values.get("base_url", BASE_URL)
|
|
95
|
+
),
|
|
96
|
+
model or os.getenv("SPIRITLM_MODEL") or values.get("model"),
|
|
97
|
+
"NO_COLOR" not in os.environ and values.get("color", True),
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
def save_model(self, model: str) -> None:
|
|
101
|
+
import json
|
|
102
|
+
|
|
103
|
+
self.model = model
|
|
104
|
+
path = config_path()
|
|
105
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
106
|
+
# JSON quoted strings are compatible with TOML basic strings here.
|
|
107
|
+
path.write_text(
|
|
108
|
+
f"base_url = {json.dumps(self.base_url)}\n"
|
|
109
|
+
f"model = {json.dumps(model, ensure_ascii=False)}\n"
|
|
110
|
+
f"color = {str(self.color).lower()}\n",
|
|
111
|
+
encoding="utf-8",
|
|
112
|
+
)
|