gigachat-cli 0.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. gigachat_cli-0.0.0/LICENSE.md +78 -0
  2. gigachat_cli-0.0.0/MANIFEST.in +2 -0
  3. gigachat_cli-0.0.0/PKG-INFO +138 -0
  4. gigachat_cli-0.0.0/README.md +115 -0
  5. gigachat_cli-0.0.0/pyproject.toml +35 -0
  6. gigachat_cli-0.0.0/setup.cfg +4 -0
  7. gigachat_cli-0.0.0/src/gigachat_cli/__init__.py +1 -0
  8. gigachat_cli-0.0.0/src/gigachat_cli/__main__.py +8 -0
  9. gigachat_cli-0.0.0/src/gigachat_cli/handler/file.py +40 -0
  10. gigachat_cli-0.0.0/src/gigachat_cli/handler/model.py +58 -0
  11. gigachat_cli-0.0.0/src/gigachat_cli/handler/terminal_command.py +40 -0
  12. gigachat_cli-0.0.0/src/gigachat_cli/main.py +9 -0
  13. gigachat_cli-0.0.0/src/gigachat_cli/screens/__init__.py +1 -0
  14. gigachat_cli-0.0.0/src/gigachat_cli/screens/chat.py +172 -0
  15. gigachat_cli-0.0.0/src/gigachat_cli/screens/help.py +58 -0
  16. gigachat_cli-0.0.0/src/gigachat_cli/screens/start.py +49 -0
  17. gigachat_cli-0.0.0/src/gigachat_cli/styles/__init__.py +1 -0
  18. gigachat_cli-0.0.0/src/gigachat_cli/styles/chat.css +41 -0
  19. gigachat_cli-0.0.0/src/gigachat_cli/styles/help.css +39 -0
  20. gigachat_cli-0.0.0/src/gigachat_cli/styles/start.css +64 -0
  21. gigachat_cli-0.0.0/src/gigachat_cli/utils/__init__.py +1 -0
  22. gigachat_cli-0.0.0/src/gigachat_cli/utils/command.py +113 -0
  23. gigachat_cli-0.0.0/src/gigachat_cli/utils/config.py +43 -0
  24. gigachat_cli-0.0.0/src/gigachat_cli/utils/core.py +54 -0
  25. gigachat_cli-0.0.0/src/gigachat_cli/utils/list.py +31 -0
  26. gigachat_cli-0.0.0/src/gigachat_cli/utils/openfile.py +7 -0
  27. gigachat_cli-0.0.0/src/gigachat_cli/widgets/__init__.py +1 -0
  28. gigachat_cli-0.0.0/src/gigachat_cli/widgets/banner.py +20 -0
  29. gigachat_cli-0.0.0/src/gigachat_cli/widgets/command_list.py +22 -0
  30. gigachat_cli-0.0.0/src/gigachat_cli/widgets/dir.py +10 -0
  31. gigachat_cli-0.0.0/src/gigachat_cli/widgets/model.py +18 -0
  32. gigachat_cli-0.0.0/src/gigachat_cli/widgets/typing.py +23 -0
  33. gigachat_cli-0.0.0/src/gigachat_cli.egg-info/PKG-INFO +138 -0
  34. gigachat_cli-0.0.0/src/gigachat_cli.egg-info/SOURCES.txt +36 -0
  35. gigachat_cli-0.0.0/src/gigachat_cli.egg-info/dependency_links.txt +1 -0
  36. gigachat_cli-0.0.0/src/gigachat_cli.egg-info/entry_points.txt +2 -0
  37. gigachat_cli-0.0.0/src/gigachat_cli.egg-info/requires.txt +7 -0
  38. gigachat_cli-0.0.0/src/gigachat_cli.egg-info/top_level.txt +1 -0
@@ -0,0 +1,78 @@
1
+ # MIT License
2
+
3
+ ## Лицензионное соглашение / License Agreement
4
+
5
+ ### Русская версия
6
+
7
+ **Авторское право (c) 2023 AI Forever**
8
+
9
+ Настоящим предоставляется бесплатное разрешение любому лицу, получившему копию данного программного обеспечения и сопутствующей документации (в дальнейшем «Программное обеспечение»), использовать Программное обеспечение без ограничений, включая, но не ограничиваясь правами на использование, копирование, изменение, объединение, публикацию, распространение, сублицензирование и/или продажу копий Программного обеспечения, а также лицам, которым предоставляется данное Программное обеспечение, при соблюдении следующих условий:
10
+
11
+ #### ✅ Разрешено:
12
+ - Использовать в коммерческих целях
13
+ - Распространять
14
+ - Изменять
15
+ - Объединять с другим кодом
16
+ - Использовать в частных проектах
17
+ - Сублицензировать
18
+
19
+ #### 📝 Обязательства:
20
+ Указанное выше уведомление об авторских правах и данное уведомление о разрешении должны быть включены во все копии или существенные части Программного обеспечения.
21
+
22
+ #### ⚠️ Отказ от гарантий:
23
+ **ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ «КАК ЕСТЬ», БЕЗ КАКИХ-ЛИБО ГАРАНТИЙ, ЯВНЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ.**
24
+
25
+ #### 🛡️ Ограничение ответственности:
26
+ **НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ АВТОРЫ ИЛИ ПРАВООБЛАДАТЕЛИ НЕ НЕСУТ ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ УБЫТКИ ИЛИ ПРЕТЕНЗИИ.**
27
+
28
+ ---
29
+
30
+ ### English Version
31
+
32
+ **Copyright (c) 2023 AI Forever**
33
+
34
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
35
+
36
+ #### ✅ Permitted:
37
+ - Commercial use
38
+ - Distribution
39
+ - Modification
40
+ - Private use
41
+ - Sublicensing
42
+
43
+ #### 📝 Requirements:
44
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
45
+
46
+ #### ⚠️ Disclaimer:
47
+ **THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.**
48
+
49
+ #### 🛡️ Liability:
50
+ **IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY.**
51
+
52
+ ---
53
+
54
+ ### Полный текст на английском / Full English Text
55
+
56
+ ```text
57
+ MIT License
58
+
59
+ Copyright (c) 2023 AI Forever
60
+
61
+ Permission is hereby granted, free of charge, to any person obtaining a copy
62
+ of this software and associated documentation files (the "Software"), to deal
63
+ in the Software without restriction, including without limitation the rights
64
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
65
+ copies of the Software, and to permit persons to whom the Software is
66
+ furnished to do so, subject to the following conditions:
67
+
68
+ The above copyright notice and this permission notice shall be included in all
69
+ copies or substantial portions of the Software.
70
+
71
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
72
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
73
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
74
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
75
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
76
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
77
+ SOFTWARE.
78
+ ```
@@ -0,0 +1,2 @@
1
+ recursive-include src/gigachat_cli *.css
2
+ recursive-include src/gigachat_cli *.md
@@ -0,0 +1,138 @@
1
+ Metadata-Version: 2.4
2
+ Name: gigachat-cli
3
+ Version: 0.0.0
4
+ Summary: GigaChat CLI utility
5
+ Author-email: THEChrismoth <klevindanila@ya.ru>
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: Programming Language :: Python :: 3.13
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Topic :: Utilities
11
+ Classifier: Topic :: Terminals
12
+ Requires-Python: >=3.13
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE.md
15
+ Requires-Dist: aiofiles>=25.1.0
16
+ Requires-Dist: asyncio>=4.0.0
17
+ Requires-Dist: importlib-resources>=6.5.2
18
+ Requires-Dist: langchain-gigachat>=0.3.12
19
+ Requires-Dist: regex>=2025.9.18
20
+ Requires-Dist: setuptools-scm>=9.2.2
21
+ Requires-Dist: textual>=6.2.0
22
+ Dynamic: license-file
23
+
24
+ # GigaChat CLI
25
+
26
+ [![PyPI Version](https://img.shields.io/pypi/v/gigachat-cli.svg)](https://pypi.org/project/gigachat-cli/)
27
+ [![PyPI - License](https://img.shields.io/pypi/l/gigachat-cli)](https://gitverse.ru/THEChrismoth/GigaChat-Cli/content/master/LICENSE.md)
28
+ [![Python Version](https://img.shields.io/pypi/pyversions/gigachat-cli)](https://pypi.org/project/gigachat-cli/)
29
+
30
+ Текстовый интерфейс для работы с GigaChat AI через командную строку с поддержкой терминальных команд и работы с файлами.
31
+
32
+ ![GigaChat CLI Screenshot](https://gitverse.ru/api/repos/THEChrismoth/GigaChat-Cli/raw/branch/asset/gigachat_menu.jpg)
33
+
34
+ ## Особенности
35
+
36
+ - **Интуитивный текстовый интерфейс** - современный TUI на базе Textual
37
+ - **Интерактивный чат** - общайтесь с GigaChat в реальном времени
38
+ - **Встроенный терминал** - выполняйте системные команды прямо из чата (префикс ёёё!ёёё)
39
+ - **Работа с файлами** - загружайте и анализируйте файлы с помощью команды ёёё/fileёёё
40
+ - **История диалога** - автоматическое сохранение контекста беседы
41
+ - **Подсветка синтаксиса** - красивый вывод кода и терминальных команд
42
+
43
+ ## Установка
44
+
45
+ ### Установка из PyPI
46
+ ```
47
+ pip install gigachat-cli
48
+ ```
49
+ ### Установка из исходного кода
50
+ ```
51
+ git clone https://gitverse.ru/THEChrismoth/GigaChat_Cli.git
52
+ cd gigachat_cli
53
+ pip install .
54
+ ```
55
+ ## Настройка аутентификации
56
+
57
+ ### Получение API ключа
58
+
59
+ 1. Перейдите на [SberAI Developer Studio](https://developers.sber.ru/studio/login)
60
+ 2. Зарегистрируйтесь или войдите в аккаунт
61
+ 3. Создайте новый API ключ
62
+
63
+ ### Настройка переменной окружения
64
+ ```
65
+ export GIGACHAT_API_KEY="ваш_api_ключ_здесь"
66
+ ```
67
+ Для постоянного хранения добавьте в ваш ~/.bashrc, ~/.zshrc или ~/.profile:
68
+ ```
69
+ echo 'export GIGACHAT_API_KEY="ваш_api_ключ_здесь"' >> ~/.bashrc
70
+ ```
71
+ ## Начало работы
72
+
73
+ ### Запуск приложения
74
+ ```
75
+ gigachat
76
+ ```
77
+ ### Основное использование
78
+
79
+ 1. **Запустите приложение** - введите команду gigachat
80
+ 2. **Выберите "Начать чат"** - из главного меню
81
+ 3. **Введите сообщение** - пишите вопросы и нажимайте Shift+Enter для отправки
82
+ 4. **Используйте терминальные команды** - начинайте команды с **!** (например: **!ls -la**)
83
+ 5. **Работайте с файлами** - используйте **/file имя_файла ваш_запрос**
84
+ 6. **Выход** - введите **/exit** или нажмите Ctrl+Q
85
+
86
+ ![GigaChat CLI Screenshot](https://gitverse.ru/api/repos/THEChrismoth/GigaChat-Cli/raw/branch/asset/gigachat_work.jpg)
87
+
88
+ ## Горячие клавиши
89
+
90
+ - **Shift+Enter** - отправить сообщение
91
+ - **Ctrl+Shift+V** - вставить текст из буфера обмена
92
+ - **Ctrl+Q** - выйти из приложения
93
+ - **Escape** - вернуться назад (в меню помощи)
94
+
95
+ ## Примеры использования
96
+
97
+ ### Базовый чат
98
+
99
+ Просто введите ваш вопрос и нажмите Shift+Enter
100
+
101
+ ### Терминальные команды
102
+
103
+ - `!pwd` - показать текущую директорию
104
+ - `!python --version` - проверить версию Python
105
+ - `!git status` - проверить статус git репозитория
106
+
107
+ ### Работа с файлами
108
+
109
+ - `/file main.py объясни что делает этот код` - анализ кода Python
110
+ - `/file README.md улучши этот README файл` - улучшение документации
111
+ - `/file data.json проанализируй эту JSON структуру` - анализ JSON данных
112
+
113
+ ## Требования
114
+
115
+ - Python >= 3.13
116
+ - GigaChat API ключ
117
+
118
+ ## Зависимости
119
+
120
+ - textual >= 6.2.0 - фреймворк для TUI приложений
121
+ - langchain-gigachat >= 0.3.12 - интеграция с GigaChat
122
+ - asyncio >= 4.0.0 - асинхронное программирование
123
+
124
+ ## Лицензия
125
+
126
+ MIT License - смотрите файл [LICENSE.md](LICENSE.md) для деталей.
127
+
128
+ ## Поддержка
129
+
130
+ Если вы столкнулись с проблемами или у вас есть предложения:
131
+
132
+ 1. Создайте issue в репозитории
133
+ 2. Убедитесь что GIGACHAT_API_KEY корректно установлен
134
+ 3. Проверьте что Python версии 3.13 или выше
135
+
136
+ ---
137
+
138
+ **GigaChat CLI** - мощный инструмент для разработчиков, сочетающий возможности AI-ассистента с удобством командной строки.
@@ -0,0 +1,115 @@
1
+ # GigaChat CLI
2
+
3
+ [![PyPI Version](https://img.shields.io/pypi/v/gigachat-cli.svg)](https://pypi.org/project/gigachat-cli/)
4
+ [![PyPI - License](https://img.shields.io/pypi/l/gigachat-cli)](https://gitverse.ru/THEChrismoth/GigaChat-Cli/content/master/LICENSE.md)
5
+ [![Python Version](https://img.shields.io/pypi/pyversions/gigachat-cli)](https://pypi.org/project/gigachat-cli/)
6
+
7
+ Текстовый интерфейс для работы с GigaChat AI через командную строку с поддержкой терминальных команд и работы с файлами.
8
+
9
+ ![GigaChat CLI Screenshot](https://gitverse.ru/api/repos/THEChrismoth/GigaChat-Cli/raw/branch/asset/gigachat_menu.jpg)
10
+
11
+ ## Особенности
12
+
13
+ - **Интуитивный текстовый интерфейс** - современный TUI на базе Textual
14
+ - **Интерактивный чат** - общайтесь с GigaChat в реальном времени
15
+ - **Встроенный терминал** - выполняйте системные команды прямо из чата (префикс ёёё!ёёё)
16
+ - **Работа с файлами** - загружайте и анализируйте файлы с помощью команды ёёё/fileёёё
17
+ - **История диалога** - автоматическое сохранение контекста беседы
18
+ - **Подсветка синтаксиса** - красивый вывод кода и терминальных команд
19
+
20
+ ## Установка
21
+
22
+ ### Установка из PyPI
23
+ ```
24
+ pip install gigachat-cli
25
+ ```
26
+ ### Установка из исходного кода
27
+ ```
28
+ git clone https://gitverse.ru/THEChrismoth/GigaChat_Cli.git
29
+ cd gigachat_cli
30
+ pip install .
31
+ ```
32
+ ## Настройка аутентификации
33
+
34
+ ### Получение API ключа
35
+
36
+ 1. Перейдите на [SberAI Developer Studio](https://developers.sber.ru/studio/login)
37
+ 2. Зарегистрируйтесь или войдите в аккаунт
38
+ 3. Создайте новый API ключ
39
+
40
+ ### Настройка переменной окружения
41
+ ```
42
+ export GIGACHAT_API_KEY="ваш_api_ключ_здесь"
43
+ ```
44
+ Для постоянного хранения добавьте в ваш ~/.bashrc, ~/.zshrc или ~/.profile:
45
+ ```
46
+ echo 'export GIGACHAT_API_KEY="ваш_api_ключ_здесь"' >> ~/.bashrc
47
+ ```
48
+ ## Начало работы
49
+
50
+ ### Запуск приложения
51
+ ```
52
+ gigachat
53
+ ```
54
+ ### Основное использование
55
+
56
+ 1. **Запустите приложение** - введите команду gigachat
57
+ 2. **Выберите "Начать чат"** - из главного меню
58
+ 3. **Введите сообщение** - пишите вопросы и нажимайте Shift+Enter для отправки
59
+ 4. **Используйте терминальные команды** - начинайте команды с **!** (например: **!ls -la**)
60
+ 5. **Работайте с файлами** - используйте **/file имя_файла ваш_запрос**
61
+ 6. **Выход** - введите **/exit** или нажмите Ctrl+Q
62
+
63
+ ![GigaChat CLI Screenshot](https://gitverse.ru/api/repos/THEChrismoth/GigaChat-Cli/raw/branch/asset/gigachat_work.jpg)
64
+
65
+ ## Горячие клавиши
66
+
67
+ - **Shift+Enter** - отправить сообщение
68
+ - **Ctrl+Shift+V** - вставить текст из буфера обмена
69
+ - **Ctrl+Q** - выйти из приложения
70
+ - **Escape** - вернуться назад (в меню помощи)
71
+
72
+ ## Примеры использования
73
+
74
+ ### Базовый чат
75
+
76
+ Просто введите ваш вопрос и нажмите Shift+Enter
77
+
78
+ ### Терминальные команды
79
+
80
+ - `!pwd` - показать текущую директорию
81
+ - `!python --version` - проверить версию Python
82
+ - `!git status` - проверить статус git репозитория
83
+
84
+ ### Работа с файлами
85
+
86
+ - `/file main.py объясни что делает этот код` - анализ кода Python
87
+ - `/file README.md улучши этот README файл` - улучшение документации
88
+ - `/file data.json проанализируй эту JSON структуру` - анализ JSON данных
89
+
90
+ ## Требования
91
+
92
+ - Python >= 3.13
93
+ - GigaChat API ключ
94
+
95
+ ## Зависимости
96
+
97
+ - textual >= 6.2.0 - фреймворк для TUI приложений
98
+ - langchain-gigachat >= 0.3.12 - интеграция с GigaChat
99
+ - asyncio >= 4.0.0 - асинхронное программирование
100
+
101
+ ## Лицензия
102
+
103
+ MIT License - смотрите файл [LICENSE.md](LICENSE.md) для деталей.
104
+
105
+ ## Поддержка
106
+
107
+ Если вы столкнулись с проблемами или у вас есть предложения:
108
+
109
+ 1. Создайте issue в репозитории
110
+ 2. Убедитесь что GIGACHAT_API_KEY корректно установлен
111
+ 3. Проверьте что Python версии 3.13 или выше
112
+
113
+ ---
114
+
115
+ **GigaChat CLI** - мощный инструмент для разработчиков, сочетающий возможности AI-ассистента с удобством командной строки.
@@ -0,0 +1,35 @@
1
+ [project]
2
+ name = "gigachat-cli"
3
+ dynamic = ["version"]
4
+ description = "GigaChat CLI utility"
5
+ authors = [
6
+ {name = "THEChrismoth",email = "klevindanila@ya.ru"}
7
+ ]
8
+ readme = "README.md"
9
+ requires-python = ">=3.13"
10
+ dependencies = [
11
+ "aiofiles>=25.1.0",
12
+ "asyncio>=4.0.0",
13
+ "importlib-resources>=6.5.2",
14
+ "langchain-gigachat>=0.3.12",
15
+ "regex>=2025.9.18",
16
+ "setuptools-scm>=9.2.2",
17
+ "textual>=6.2.0",
18
+ ]
19
+ classifiers = [
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.13",
22
+ "License :: OSI Approved :: MIT License",
23
+ "Operating System :: OS Independent",
24
+ "Topic :: Utilities",
25
+ "Topic :: Terminals",
26
+ ]
27
+
28
+ [project.scripts]
29
+ gigachat = "gigachat_cli.__main__:main"
30
+
31
+ [tool.setuptools]
32
+ package-dir = {"" = "src"}
33
+
34
+ [tool.setuptools_scm]
35
+ write_to = "src/gigachat_cli/_version.py"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,8 @@
1
+ from gigachat_cli.main import Main
2
+
3
+ def main():
4
+ app = Main()
5
+ app.run()
6
+
7
+ if __name__ == "__main__":
8
+ main()
@@ -0,0 +1,40 @@
1
+ import re
2
+ import asyncio
3
+
4
+ from textual.widgets import TextArea
5
+
6
+ from gigachat_cli.utils.openfile import open_file
7
+ from gigachat_cli.widgets.typing import TypingIndicator
8
+
9
+ # Хендлер обработки команды /file
10
+ class FileHandler:
11
+ async def handle(self, user_text: str, text_area: TextArea, screen):
12
+ if not user_text.lower().startswith('/file'):
13
+ return False
14
+
15
+ match = re.match(r'/file\s+(\S+)\s+(.+)', user_text)
16
+
17
+ if match:
18
+ filename = match.group(1)
19
+ message = match.group(2).strip()
20
+
21
+ file = open_file(filename)
22
+
23
+ if file.startswith("Ошибка"):
24
+ screen.user_inputs.append(("Система", file))
25
+ screen.update_chat_display()
26
+ return True
27
+
28
+ screen.user_inputs.append(("Вы", f"{message}\n```\n{file}\n```"))
29
+ screen.update_chat_display()
30
+
31
+ screen.current_typing_indicator = TypingIndicator()
32
+ chat_container = screen.query_one("#chat_container")
33
+ chat_container.mount(screen.current_typing_indicator)
34
+
35
+ asyncio.create_task(screen.get_bot_response(f"{message}\n```\n{file}\n```"))
36
+
37
+ return True
38
+
39
+ return False
40
+
@@ -0,0 +1,58 @@
1
+ import re
2
+
3
+ from textual.widgets import TextArea
4
+
5
+ from gigachat_cli.utils.config import Config
6
+
7
+ # Хендлер обработки команды /model
8
+ class ModelHandler:
9
+ def __init__(self, cfg: Config):
10
+ self.cfg = cfg
11
+ self.model_names = {
12
+ "GigaChat-2": "GigaChat 2 Lite",
13
+ "GigaChat-2-Pro": "GigaChat 2 Pro",
14
+ "GigaChat-2-Max": "GigaChat 2 Max",
15
+ }
16
+
17
+ async def handle(self, user_text: str, text_area: TextArea, screen):
18
+ if not user_text.lower().startswith('/model'):
19
+ return False
20
+
21
+ if user_text.strip() == '/model':
22
+ model_list = "\n\n".join([f"• {key}: {value}" for key, value in self.model_names.items()])
23
+ screen.user_inputs.append(("Система", f"**Доступные модели:**\n\n{model_list}"))
24
+
25
+ screen.update_chat_display()
26
+
27
+ # Очищаем поле ввода
28
+ text_area = screen.query_one("#message_input", TextArea)
29
+ text_area.text = ""
30
+ text_area.focus()
31
+
32
+ return True
33
+ else:
34
+ # Если есть аргументы - обрабатываем выбор модели
35
+ match = re.match(r'/model\s+(.+)', user_text)
36
+ if match:
37
+ model_key = match.group(1).strip()
38
+ model_names = self.model_names
39
+
40
+ if model_key in model_names:
41
+ self.cfg.set_model(model_key)
42
+ screen.user_inputs.append(("Система", f"Выбрана модель: {model_names[model_key]}"))
43
+
44
+ else:
45
+ screen.user_inputs.append(("Система", f"Модель '{model_key}' не найдена. Используйте /model для просмотра списка."))
46
+
47
+ screen._update_model_display()
48
+ screen.update_chat_display()
49
+
50
+ # Очищаем поле ввода
51
+ text_area = screen.query_one("#message_input", TextArea)
52
+ text_area.text = ""
53
+ text_area.focus()
54
+
55
+ return True
56
+
57
+ return False
58
+
@@ -0,0 +1,40 @@
1
+ from textual.widgets import TextArea
2
+
3
+ from gigachat_cli.utils.command import CommandUtils
4
+ from gigachat_cli.widgets.typing import TypingIndicator
5
+
6
+ class TerminalHandler:
7
+ def __init__(self, command_utils: CommandUtils):
8
+ super().__init__()
9
+ self.command_utils = command_utils
10
+
11
+ async def handle(self, user_text: str, text_area: TextArea, screen):
12
+ is_terminal, command = CommandUtils.is_terminal_command(user_text)
13
+ if is_terminal:
14
+
15
+ screen.user_inputs.append(("Вы", f"`!{command}`"))
16
+ screen.update_chat_display()
17
+
18
+ screen.current_typing_indicator = TypingIndicator()
19
+ chat_container = screen.query_one("#chat_container")
20
+ chat_container.mount(screen.current_typing_indicator)
21
+
22
+
23
+ success, output, return_code = await self.command_utils.execute_system_command(command)
24
+
25
+ if screen.current_typing_indicator:
26
+ screen.current_typing_indicator.stop_animation()
27
+ screen.current_typing_indicator.remove()
28
+ screen.current_typing_indicator = None
29
+
30
+ formatted_output = CommandUtils.format_command_output(output, success, return_code)
31
+ screen.user_inputs.append(("Система", formatted_output))
32
+
33
+ # Обновляем отображение директории после выполнения команды
34
+ screen._update_directory_display()
35
+
36
+ screen.update_chat_display()
37
+ text_area.text = ""
38
+ text_area.focus()
39
+ return True
40
+ return False
@@ -0,0 +1,9 @@
1
+ from textual.app import App
2
+
3
+ from gigachat_cli.screens.start import MenuApp
4
+
5
+ # Основное приложение
6
+ class Main(App):
7
+ def on_mount(self) -> None:
8
+ # Устанавливаем стартовый экран при запуске
9
+ self.push_screen(MenuApp())