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/ui.py ADDED
@@ -0,0 +1,409 @@
1
+ import os
2
+ import re
3
+ import sys
4
+ from collections.abc import Iterable
5
+ from pathlib import Path
6
+ from typing import Any, Literal
7
+
8
+ from prompt_toolkit import PromptSession
9
+ from prompt_toolkit.application import Application
10
+ from prompt_toolkit.completion import Completer, Completion, DummyCompleter, PathCompleter
11
+ from prompt_toolkit.document import Document
12
+ from prompt_toolkit.filters import Condition, has_completions, is_done
13
+ from prompt_toolkit.history import DummyHistory
14
+ from prompt_toolkit.input.ansi_escape_sequences import ANSI_SEQUENCES
15
+ from prompt_toolkit.key_binding import KeyBindings
16
+ from prompt_toolkit.keys import Keys
17
+ from prompt_toolkit.layout import ConditionalContainer, HSplit, VSplit, Window
18
+ from prompt_toolkit.layout.containers import WindowAlign
19
+ from prompt_toolkit.layout.controls import FormattedTextControl
20
+ from prompt_toolkit.output import ColorDepth
21
+ from prompt_toolkit.styles import Style
22
+ from rich import box
23
+ from rich.console import Console
24
+ from rich.live import Live
25
+ from rich.markdown import Markdown
26
+ from rich.padding import Padding
27
+ from rich.spinner import Spinner
28
+ from rich.syntax import Syntax
29
+ from rich.table import Table
30
+ from rich.text import Text
31
+
32
+ from spiritcode.commands import COMMANDS
33
+ from spiritcode.config import COLORS, STAR
34
+ from spiritcode.keyboard import prepare_keyboard
35
+
36
+ ANSI = re.compile(r"\x1b(?:\][^\x07\x1b]*(?:\x07|\x1b\\)|\[[0-?]*[ -/]*[@-~]|[@-_])")
37
+ CONTROLS = re.compile(r"[\x00-\x08\x0b-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]")
38
+ KEY = re.compile(r"sk-spiritlm-[A-Za-z0-9_-]+")
39
+ NoticeKind = Literal["info", "warning", "error", "success"]
40
+
41
+ # CSI-u (Kitty) and xterm modifyOtherKeys encode Shift+Enter separately from Enter.
42
+ for sequence in ("\x1b[13;2u", "\x1b[27;2;13~", "\x1b[13;2~"):
43
+ ANSI_SEQUENCES[sequence] = Keys.ControlO
44
+
45
+
46
+ def clean(value: str) -> str:
47
+ return CONTROLS.sub("", ANSI.sub("", KEY.sub("[ключ скрыт]", value)))
48
+
49
+
50
+ class InputCompleter(Completer):
51
+ def __init__(self) -> None:
52
+ self.models: list[str] = []
53
+ self.sessions: list[tuple[str, str]] = []
54
+
55
+ def get_completions(self, document: Document, complete_event: Any) -> Iterable[Completion]:
56
+ text = document.text_before_cursor
57
+ if text.startswith("/"):
58
+ command, separator, argument = text.partition(" ")
59
+ if not separator:
60
+ for item in COMMANDS:
61
+ if item.name.startswith(command) and item.name != command:
62
+ yield Completion(
63
+ item.name,
64
+ start_position=-len(command),
65
+ display_meta=item.description,
66
+ )
67
+ return
68
+ candidates: list[tuple[str, str]] = []
69
+ if command == "/model":
70
+ candidates = [(model, "Модель SpiritLM") for model in self.models]
71
+ elif command == "/resume":
72
+ candidates = self.sessions
73
+ elif command == "/usage":
74
+ candidates = [
75
+ (period, "Период статистики") for period in ("2d", "7d", "30d", "all")
76
+ ]
77
+ for value, description in candidates:
78
+ if argument.casefold() in value.casefold() and argument != value:
79
+ yield Completion(
80
+ value,
81
+ start_position=-len(argument),
82
+ display_meta=clean(description),
83
+ display=clean(value),
84
+ )
85
+ return
86
+ # Completion is opt-in for normal text; never pop a file menu over prose.
87
+ match = re.search(r'(?:^|\s)@("?)([^"\n]*)$', text)
88
+ if match:
89
+ quote, path = match.groups()
90
+ for completion in PathCompleter(expanduser=True).get_completions(
91
+ Document(path), complete_event
92
+ ):
93
+ directory = completion.display_text.endswith("/")
94
+ if directory:
95
+ completion.text += "/"
96
+ if quote and not directory:
97
+ completion.text += '"'
98
+ elif not quote and " " in path + completion.text:
99
+ completion = Completion(
100
+ '"' + path + completion.text + ("" if directory else '"'),
101
+ start_position=-len(path),
102
+ display=completion.display,
103
+ )
104
+ yield completion
105
+
106
+
107
+ def input_bindings(ui: "UI") -> KeyBindings:
108
+ bindings = KeyBindings()
109
+
110
+ @bindings.add("enter")
111
+ def submit(event: Any) -> None:
112
+ buffer = event.current_buffer
113
+ state = buffer.complete_state
114
+ if state and state.completions:
115
+ completion = state.current_completion or state.completions[0]
116
+ buffer.cancel_completion()
117
+ buffer.apply_completion(completion)
118
+ else:
119
+ buffer.validate_and_handle()
120
+
121
+ @bindings.add("tab")
122
+ def complete(event: Any) -> None:
123
+ buffer = event.current_buffer
124
+ if buffer.complete_state:
125
+ buffer.complete_next()
126
+ else:
127
+ buffer.start_completion(select_first=True)
128
+
129
+ @bindings.add("escape", filter=has_completions)
130
+ def close_menu(event: Any) -> None:
131
+ event.current_buffer.cancel_completion()
132
+
133
+ @bindings.add("escape", "enter")
134
+ @bindings.add("c-o")
135
+ def newline(event: Any) -> None:
136
+ event.current_buffer.insert_text("\n")
137
+
138
+ @bindings.add("c-c")
139
+ def interrupt(event: Any) -> None:
140
+ ui.interrupted_empty = not event.current_buffer.text
141
+ event.app.exit(exception=KeyboardInterrupt)
142
+
143
+ @bindings.add("insert")
144
+ def commands(event: Any) -> None:
145
+ event.current_buffer.insert_text("/")
146
+
147
+ return bindings
148
+
149
+
150
+ class UI:
151
+ def __init__(self, color: bool = True) -> None:
152
+ self.interrupted_empty = True
153
+ self.color = color and "NO_COLOR" not in os.environ
154
+ self.console = Console(no_color=not self.color, highlight=False)
155
+ self.completer = InputCompleter()
156
+ self.model_label = "модель не выбрана"
157
+ self.chat_input = False
158
+ self.account_label = "Аккаунт не загружен"
159
+ self.transcript: list[tuple[object, ...]] = []
160
+ self.terminal_size: tuple[int, int] | None = None
161
+ self.prompt: PromptSession[str] | None = None
162
+ self.style = Style.from_dict(
163
+ {
164
+ "prompt": f"bold {COLORS['accent']}",
165
+ "hint": COLORS["muted"],
166
+ "input-border": "#515967",
167
+ "completion-menu.completion": "bg:#1b1b1b #f3f2ee",
168
+ "completion-menu.completion.current": "bg:#ffe02e #080808",
169
+ "completion-menu.meta.completion": "bg:#1b1b1b #a5a5a1",
170
+ "completion-menu.meta.completion.current": "bg:#30302e #f3f2ee",
171
+ "bottom-toolbar": "noreverse",
172
+ }
173
+ if self.color
174
+ else {}
175
+ )
176
+ if sys.stdin.isatty() and sys.stdout.isatty():
177
+ self.prompt = PromptSession(
178
+ multiline=True,
179
+ key_bindings=input_bindings(self),
180
+ completer=self.completer,
181
+ complete_while_typing=True,
182
+ enable_history_search=False,
183
+ style=self.style,
184
+ color_depth=None if self.color else ColorDepth.DEPTH_1_BIT,
185
+ reserve_space_for_menu=0,
186
+ prompt_continuation=" ",
187
+ erase_when_done=True,
188
+ )
189
+ self.prompt.app.before_render += self._before_render
190
+ layout = self.prompt.layout.container
191
+ assert isinstance(layout, HSplit)
192
+ chat_active = Condition(lambda: self.chat_input) & ~is_done
193
+
194
+ def separator() -> ConditionalContainer:
195
+ return ConditionalContainer(
196
+ Window(height=1, char="─", style="class:input-border"),
197
+ filter=chat_active,
198
+ )
199
+
200
+ layout.children.insert(0, separator())
201
+ layout.children.insert(2, separator())
202
+ layout.children.insert(
203
+ 3,
204
+ ConditionalContainer(
205
+ VSplit(
206
+ [
207
+ Window(
208
+ FormattedTextControl(" /help — команды"),
209
+ width=18,
210
+ height=1,
211
+ style="class:hint",
212
+ ),
213
+ Window(
214
+ FormattedTextControl(lambda: self.model_label + " "),
215
+ align=WindowAlign.RIGHT,
216
+ height=1,
217
+ wrap_lines=False,
218
+ style="class:hint",
219
+ ),
220
+ ]
221
+ ),
222
+ filter=chat_active,
223
+ ),
224
+ )
225
+ self.live: Live | None = None
226
+ self.response = ""
227
+
228
+ def _print(self, *objects: object) -> None:
229
+ self.transcript.append(objects)
230
+ self.console.print(*objects)
231
+
232
+ def _before_render(self, app: Application[str]) -> None:
233
+ # Grow the input area only while a menu is open. Otherwise a prompt
234
+ # near the terminal bottom leaves no room for the floating completions.
235
+ state = app.current_buffer.complete_state
236
+ if self.prompt:
237
+ self.prompt.reserve_space_for_menu = (
238
+ min(len(state.completions), 6) + 1 if state and state.completions else 0
239
+ )
240
+ size = app.output.get_size()
241
+ width = size.columns
242
+ previous_size = self.terminal_size
243
+ self.terminal_size = (size.columns, size.rows)
244
+ if previous_size is None or previous_size == self.terminal_size:
245
+ return
246
+ # Re-render Rich objects at the new width. Old terminal cells cannot be
247
+ # reflowed reliably: full-width rules otherwise leave duplicate rows.
248
+ app.output.erase_screen()
249
+ app.output.cursor_goto(0, 0)
250
+ app.output.flush()
251
+ for objects in self.transcript:
252
+ self.console.print(*objects, width=width)
253
+ app.renderer.reset()
254
+ app.renderer.request_absolute_cursor_position()
255
+
256
+ def say(self, text: str) -> None:
257
+ self._print(Text(clean(text), style=COLORS["text"]))
258
+
259
+ def muted(self, text: str) -> None:
260
+ self._print(Text(clean(text), style=COLORS["muted"]))
261
+
262
+ def notice(self, title: str, body: str = "", kind: NoticeKind = "info") -> None:
263
+ color = COLORS["accent" if kind == "warning" else kind]
264
+ symbol = {"info": "│", "warning": "!", "error": "×", "success": "✓"}[kind]
265
+ self._print()
266
+ self._print(Text(f"{symbol} {clean(title)}", style=f"bold {color}"))
267
+ if body:
268
+ self._print(Padding(Text(clean(body), style=COLORS["muted"]), (0, 0, 0, 2)))
269
+ self._print()
270
+
271
+ def header(self, model: str | None, root: Path) -> None:
272
+ self.model_label = clean(model) if model else "модель не выбрана · /model"
273
+ info = Text()
274
+ info.append("SpiritCode\n", style=f"bold {COLORS['accent']}")
275
+ info.append(clean(self.account_label) + "\n", style=COLORS["muted"])
276
+ info.append(self.model_label + "\n", style=COLORS["muted"])
277
+ info.append(clean(str(root)), style=COLORS["muted"])
278
+ self._print()
279
+ if self.console.width >= 64:
280
+ layout = Table.grid(padding=(0, 3))
281
+ layout.add_column(no_wrap=True)
282
+ layout.add_column(ratio=1)
283
+ layout.add_row(Text(STAR, style=COLORS["accent"]), Padding(info, (2, 0)))
284
+ self._print(layout)
285
+ else:
286
+ self._print(info)
287
+ self._print()
288
+
289
+ def reset(self, model: str | None, root: Path) -> None:
290
+ self.transcript.clear()
291
+ if self.console.is_terminal:
292
+ self.console.file.write("\x1b[2J\x1b[H\x1b[3J")
293
+ self.console.file.flush()
294
+ self.header(model, root)
295
+
296
+ async def ask(
297
+ self,
298
+ text: str = "❯ ",
299
+ *,
300
+ secret: bool = False,
301
+ completer: Completer | None = None,
302
+ chat: bool = False,
303
+ ) -> str:
304
+ if self.prompt:
305
+ if secret:
306
+ password_prompt: PromptSession[str] = PromptSession(
307
+ history=DummyHistory(),
308
+ style=self.style,
309
+ color_depth=None if self.color else ColorDepth.DEPTH_1_BIT,
310
+ )
311
+ return await password_prompt.prompt_async(clean(text), is_password=True)
312
+ self.chat_input = chat
313
+ extended_keyboard = prepare_keyboard(self.prompt.app.input) and chat
314
+ output = self.prompt.app.output
315
+ if extended_keyboard:
316
+ output.write_raw("\x1b[>1u")
317
+ output.flush()
318
+ try:
319
+ result = await self.prompt.prompt_async(
320
+ [("class:prompt", clean(text))],
321
+ completer=(completer or self.completer)
322
+ if chat or completer
323
+ else DummyCompleter(),
324
+ complete_while_typing=chat or completer is not None,
325
+ )
326
+ if chat and result.strip():
327
+ self._print(Text("❯ " + clean(result), style=COLORS["accent"]))
328
+ return result
329
+ finally:
330
+ if extended_keyboard:
331
+ output.write_raw("\x1b[<u")
332
+ output.flush()
333
+ self.chat_input = False
334
+ # Piped input has no cursor controls, animations, or background reader.
335
+ if secret:
336
+ import getpass
337
+
338
+ return getpass.getpass(clean(text))
339
+ line = sys.stdin.readline()
340
+ if not line:
341
+ raise EOFError
342
+ value = line.rstrip("\n")
343
+ if chat and value.strip():
344
+ self._print(Text("❯ " + clean(value), style=COLORS["accent"]))
345
+ return value
346
+
347
+ async def approve(self, description: str) -> bool:
348
+ self.notice("Ожидание разрешения", description, "warning")
349
+ if not self.prompt:
350
+ self.notice("Действие отклонено", "Нет интерактивного терминала.", "warning")
351
+ return False
352
+ try:
353
+ return (await self.ask("Разрешить? [да/нет] ")).strip().lower() in {"да", "yes", "y"}
354
+ except (KeyboardInterrupt, EOFError):
355
+ return False
356
+
357
+ def begin_response(self) -> None:
358
+ self.response = ""
359
+ self._print()
360
+ self._print(Text("● SpiritCode", style=f"bold {COLORS['accent']}"))
361
+ if self.console.is_terminal:
362
+ self.live = Live(
363
+ Padding(Spinner("dots", text="Думаю…", style=COLORS["muted"]), (0, 0, 0, 2)),
364
+ console=self.console,
365
+ refresh_per_second=8,
366
+ )
367
+ self.live.start()
368
+
369
+ def delta(self, text: str) -> None:
370
+ self.response += text
371
+ if self.live:
372
+ self.live.update(Padding(Markdown(clean(self.response)), (0, 0, 0, 2)))
373
+
374
+ def end_response(self) -> None:
375
+ content = Padding(Markdown(clean(self.response)), (0, 0, 0, 2))
376
+ if self.live:
377
+ self.live.update(content)
378
+ self.live.stop()
379
+ self.live = None
380
+ self.transcript.append((content,))
381
+ elif self.response:
382
+ self._print(content)
383
+ self._print()
384
+
385
+ def tool(self, title: str, detail: str, *, error: bool = False) -> None:
386
+ text = Text(
387
+ " × " if error else " · ", style=COLORS["error"] if error else COLORS["muted"]
388
+ )
389
+ text.append(clean(title), style=COLORS["error"] if error else COLORS["info"])
390
+ text.append(" " + clean(detail), style=COLORS["muted"])
391
+ self._print(text)
392
+
393
+ def diff(self, text: str) -> None:
394
+ self._print(Padding(Syntax(clean(text), "diff", word_wrap=True), (0, 0, 0, 2)))
395
+
396
+ def table(self, rows: list[tuple[str, str]], title: str = "") -> None:
397
+ table = Table(
398
+ title=Text(clean(title), style=f"bold {COLORS['accent']}"),
399
+ title_justify="left",
400
+ show_header=False,
401
+ box=box.SIMPLE,
402
+ padding=(0, 1),
403
+ expand=False,
404
+ )
405
+ table.add_column(style=COLORS["muted"])
406
+ table.add_column(style=COLORS["text"])
407
+ for key, value in rows:
408
+ table.add_row(Text(clean(key)), Text(clean(value)))
409
+ self._print(table)
@@ -0,0 +1,75 @@
1
+ Metadata-Version: 2.4
2
+ Name: spiritcode
3
+ Version: 0.1.0
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
+ ![Интерфейс SpiritCode в терминале](image.png)
30
+
31
+ ## Установка
32
+
33
+ ```sh
34
+ pip install spiritcode
35
+ sprt
36
+ ```
37
+
38
+ При первом запуске введите API-ключ SpiritLM, затем выберите модель через `/model`.
39
+ `spiritcode` и `python -m spiritcode` — альтернативные способы запуска.
40
+
41
+ ## Команды
42
+
43
+ | Команда | Описание |
44
+ | --- | --- |
45
+ | `sprt` | Открыть чат в текущем проекте |
46
+ | `sprt login` | Войти по API-ключу |
47
+ | `sprt logout` | Удалить сохранённый ключ |
48
+ | `sprt models` | Показать модели |
49
+ | `sprt account` | Показать аккаунт |
50
+ | `sprt sessions` | Показать сохранённые сессии |
51
+ | `sprt resume <id>` | Продолжить сессию |
52
+ | `sprt --base-url <url> --model <id>` | Указать сервер без `/v1` и модель |
53
+ | `sprt --help` | Справка |
54
+ | `sprt --version` | Версия |
55
+
56
+ В чате:
57
+
58
+ | Команда | Описание |
59
+ | --- | --- |
60
+ | `/help` | Команды и сочетания клавиш |
61
+ | `/model [id]` | Поиск и смена модели |
62
+ | `/context` | Контекст, токены и диагностика сессии |
63
+ | `/profile` | Профиль SpiritLM |
64
+ | `/balance` | Баланс аккаунта |
65
+ | `/subscription` | Подписка и доступные кредиты |
66
+ | `/usage [2d\|7d\|30d\|all]` | Статистика аккаунта |
67
+ | `/new` | Новая сессия |
68
+ | `/sessions` | Сохранённые сессии |
69
+ | `/resume <id>` | Продолжить сессию |
70
+ | `/compact` | Сжать контекст отдельным оплачиваемым запросом |
71
+ | `/diff` | Правки сессии |
72
+ | `/undo` | Отменить последнюю группу правок |
73
+ | `/permissions` | Правила разрешений |
74
+ | `/exit` | Выход |
75
+ | `@путь` или `@"путь с пробелами"` | Прикрепить файл |
@@ -0,0 +1,19 @@
1
+ spiritcode/__init__.py,sha256=WBUl8e3RYiaLkbqjFVIu4U6HITDMa6bTnyGt2Qnd0N4,68
2
+ spiritcode/__main__.py,sha256=ZZQgR2YM89sc5NCCia9o7wxZAYcflx0dF00IbyE7HBM,40
3
+ spiritcode/agent.py,sha256=S_uHVDznhXoe76jT7JmF3PJYwi3PirvccHFUjOvoZHs,10873
4
+ spiritcode/api.py,sha256=jO1hS7c3-FHbUsdBw_qVO6QYkvBwGwYQYu7dPJjpL2c,5803
5
+ spiritcode/cli.py,sha256=DcIX87dHxQGFN9qll4KAW3QL11FGerlVQ-pPPGkFkYE,20349
6
+ spiritcode/commands.py,sha256=amPN91ixZHD5Ug6LusdxiW3x5hD0Dt6lVwIUuTFFp30,2071
7
+ spiritcode/config.py,sha256=bf-iYgR0lmjjKU43VYAtmidEDj6gD7DyKvktpHAaPQ8,3270
8
+ spiritcode/context.py,sha256=ilix_090_13O7__R0mA36kt6cSNT83WsJoG0lJ6xgzc,3435
9
+ spiritcode/credentials.py,sha256=17wNaQI3eawwmAmBMve2d5-zOVLjaEpCbT2-0WGO_jM,922
10
+ spiritcode/display.py,sha256=u0Zm-cvz57Lx3cl5uWaV7q6YktUwWDW8VMM7QAjj1bc,4465
11
+ spiritcode/keyboard.py,sha256=UA2VDf3baOuRDpiq8j3WG8zND29dUdizMoSLKiSyXTQ,3393
12
+ spiritcode/permissions.py,sha256=U1KB-l3J9qCHFUpiIRns3krpKXENBa_bbTW6tXiUfYo,1597
13
+ spiritcode/store.py,sha256=qASnPbzd_UeOQZsVnrmdRgZRHwSvO5vstBee53JDl_A,2927
14
+ spiritcode/tools.py,sha256=M8g54s99SJfVRbVSHn3uJ-cmNU9tPYPZaN3yv3bGShw,14874
15
+ spiritcode/ui.py,sha256=B0-BbiNsqtxOFgRqfN0ZAgXAdwPKtBHzAXpaWpgfr0c,16650
16
+ spiritcode-0.1.0.dist-info/METADATA,sha256=DcV5TiBhuqF7H19oEcN64L6KYZ6f5HECYVLvKRwfKG4,3092
17
+ spiritcode-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
18
+ spiritcode-0.1.0.dist-info/entry_points.txt,sha256=vSylhJMc_uhPKCJ2V2cm4rf_nEC5WpRVEX1uRIeidBY,78
19
+ spiritcode-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ spiritcode = spiritcode.cli:main
3
+ sprt = spiritcode.cli:main