wosb-ai-cli 1.0.1__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.
- wosb_ai_cli-1.0.1/PKG-INFO +27 -0
- wosb_ai_cli-1.0.1/setup.cfg +4 -0
- wosb_ai_cli-1.0.1/setup.py +34 -0
- wosb_ai_cli-1.0.1/wosb_ai_cli.egg-info/PKG-INFO +27 -0
- wosb_ai_cli-1.0.1/wosb_ai_cli.egg-info/SOURCES.txt +9 -0
- wosb_ai_cli-1.0.1/wosb_ai_cli.egg-info/dependency_links.txt +1 -0
- wosb_ai_cli-1.0.1/wosb_ai_cli.egg-info/entry_points.txt +2 -0
- wosb_ai_cli-1.0.1/wosb_ai_cli.egg-info/requires.txt +2 -0
- wosb_ai_cli-1.0.1/wosb_ai_cli.egg-info/top_level.txt +1 -0
- wosb_ai_cli-1.0.1/wosb_code/__init__.py +19 -0
- wosb_ai_cli-1.0.1/wosb_code/wosb_code.py +441 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: wosb-ai-cli
|
|
3
|
+
Version: 1.0.1
|
|
4
|
+
Summary: CLI-инструмент для бесплатного доступа к нейросетям через WOSB AI
|
|
5
|
+
Home-page: https://ai.wosb-chat.us.ci
|
|
6
|
+
Author: WOSB
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Classifier: Environment :: Console
|
|
10
|
+
Requires-Python: >=3.8
|
|
11
|
+
Description-Content-Type: text/plain
|
|
12
|
+
Requires-Dist: requests
|
|
13
|
+
Requires-Dist: rich
|
|
14
|
+
Dynamic: author
|
|
15
|
+
Dynamic: classifier
|
|
16
|
+
Dynamic: description
|
|
17
|
+
Dynamic: description-content-type
|
|
18
|
+
Dynamic: home-page
|
|
19
|
+
Dynamic: requires-dist
|
|
20
|
+
Dynamic: requires-python
|
|
21
|
+
Dynamic: summary
|
|
22
|
+
|
|
23
|
+
WOSB Code Pro — автономный консольный ИИ-агент уровня Claude Code / Qwen Code.
|
|
24
|
+
Поддерживает точечное редактирование файлов (edit_file), поиск по коду, выполнение команд в терминале и бесплатные API-ключи (Gemini, Groq, OpenRouter, WOSB AI и др.).
|
|
25
|
+
|
|
26
|
+
Установка: pip install wosb-ai-cli
|
|
27
|
+
Запуск: wosb
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# setup.py
|
|
2
|
+
from setuptools import setup, find_packages
|
|
3
|
+
|
|
4
|
+
setup(
|
|
5
|
+
name="wosb-ai-cli",
|
|
6
|
+
version="1.0.1",
|
|
7
|
+
description="CLI-инструмент для бесплатного доступа к нейросетям через WOSB AI",
|
|
8
|
+
long_description=(
|
|
9
|
+
"WOSB Code Pro — автономный консольный ИИ-агент уровня Claude Code / Qwen Code.\n"
|
|
10
|
+
"Поддерживает точечное редактирование файлов (edit_file), поиск по коду, "
|
|
11
|
+
"выполнение команд в терминале и бесплатные API-ключи (Gemini, Groq, OpenRouter, WOSB AI и др.).\n\n"
|
|
12
|
+
"Установка: pip install wosb-ai-cli\n"
|
|
13
|
+
"Запуск: wosb"
|
|
14
|
+
),
|
|
15
|
+
long_description_content_type="text/plain",
|
|
16
|
+
author="WOSB",
|
|
17
|
+
url="https://ai.wosb-chat.us.ci",
|
|
18
|
+
python_requires=">=3.8",
|
|
19
|
+
packages=find_packages(),
|
|
20
|
+
install_requires=[
|
|
21
|
+
"requests",
|
|
22
|
+
"rich",
|
|
23
|
+
],
|
|
24
|
+
classifiers=[
|
|
25
|
+
"Programming Language :: Python :: 3",
|
|
26
|
+
"Operating System :: OS Independent",
|
|
27
|
+
"Environment :: Console",
|
|
28
|
+
],
|
|
29
|
+
entry_points={
|
|
30
|
+
"console_scripts": [
|
|
31
|
+
"wosb=wosb_code.cli:main",
|
|
32
|
+
],
|
|
33
|
+
},
|
|
34
|
+
)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: wosb-ai-cli
|
|
3
|
+
Version: 1.0.1
|
|
4
|
+
Summary: CLI-инструмент для бесплатного доступа к нейросетям через WOSB AI
|
|
5
|
+
Home-page: https://ai.wosb-chat.us.ci
|
|
6
|
+
Author: WOSB
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Classifier: Environment :: Console
|
|
10
|
+
Requires-Python: >=3.8
|
|
11
|
+
Description-Content-Type: text/plain
|
|
12
|
+
Requires-Dist: requests
|
|
13
|
+
Requires-Dist: rich
|
|
14
|
+
Dynamic: author
|
|
15
|
+
Dynamic: classifier
|
|
16
|
+
Dynamic: description
|
|
17
|
+
Dynamic: description-content-type
|
|
18
|
+
Dynamic: home-page
|
|
19
|
+
Dynamic: requires-dist
|
|
20
|
+
Dynamic: requires-python
|
|
21
|
+
Dynamic: summary
|
|
22
|
+
|
|
23
|
+
WOSB Code Pro — автономный консольный ИИ-агент уровня Claude Code / Qwen Code.
|
|
24
|
+
Поддерживает точечное редактирование файлов (edit_file), поиск по коду, выполнение команд в терминале и бесплатные API-ключи (Gemini, Groq, OpenRouter, WOSB AI и др.).
|
|
25
|
+
|
|
26
|
+
Установка: pip install wosb-ai-cli
|
|
27
|
+
Запуск: wosb
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
setup.py
|
|
2
|
+
wosb_ai_cli.egg-info/PKG-INFO
|
|
3
|
+
wosb_ai_cli.egg-info/SOURCES.txt
|
|
4
|
+
wosb_ai_cli.egg-info/dependency_links.txt
|
|
5
|
+
wosb_ai_cli.egg-info/entry_points.txt
|
|
6
|
+
wosb_ai_cli.egg-info/requires.txt
|
|
7
|
+
wosb_ai_cli.egg-info/top_level.txt
|
|
8
|
+
wosb_code/__init__.py
|
|
9
|
+
wosb_code/wosb_code.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
wosb_code
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# setup.py
|
|
2
|
+
from setuptools import setup, find_packages
|
|
3
|
+
|
|
4
|
+
setup(
|
|
5
|
+
name="wosb-code",
|
|
6
|
+
version="1.0.0",
|
|
7
|
+
description="CLI-инструмент для бесплатного доступа к нейросетям через WOSB AI",
|
|
8
|
+
author="WOSB",
|
|
9
|
+
packages=find_packages(),
|
|
10
|
+
install_requires=[
|
|
11
|
+
"requests",
|
|
12
|
+
"rich", # Для красивого вывода в терминале
|
|
13
|
+
],
|
|
14
|
+
entry_points={
|
|
15
|
+
"console_scripts": [
|
|
16
|
+
"wosb=wosb_code.cli:main", # Создает команду 'wosb'
|
|
17
|
+
],
|
|
18
|
+
},
|
|
19
|
+
)
|
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import re
|
|
3
|
+
import json
|
|
4
|
+
import subprocess
|
|
5
|
+
import requests
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from rich.console import Console
|
|
8
|
+
from rich.markdown import Markdown
|
|
9
|
+
from rich.prompt import Prompt
|
|
10
|
+
from rich.panel import Panel
|
|
11
|
+
|
|
12
|
+
console = Console()
|
|
13
|
+
CONFIG_PATH = Path.home() / ".wosb_universal_cli.json"
|
|
14
|
+
|
|
15
|
+
PREFIX_PROVIDERS = [
|
|
16
|
+
("AIza", "Google Gemini", "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions", "gemini-2.5-flash"),
|
|
17
|
+
("gsk_", "Groq", "https://api.groq.com/openai/v1/chat/completions", "qwen-2.5-coder-32b"),
|
|
18
|
+
("sk-or-", "OpenRouter", "https://openrouter.ai/api/v1/chat/completions", "qwen/qwen-2.5-coder-32b-instruct:free"),
|
|
19
|
+
("sk-ant-", "Anthropic Claude", "https://api.anthropic.com/v1/messages", "claude-3-7-sonnet-latest"),
|
|
20
|
+
("xai-", "xAI (Grok)", "https://api.x.ai/v1/chat/completions", "grok-3-mini"),
|
|
21
|
+
("hf_", "Hugging Face", "https://router.huggingface.co/v1/chat/completions", "Qwen/Qwen2.5-Coder-32B-Instruct"),
|
|
22
|
+
("csk-", "Cerebras", "https://api.cerebras.ai/v1/chat/completions", "qwen-3-32b"),
|
|
23
|
+
("fw_", "Fireworks AI", "https://api.fireworks.ai/inference/v1/chat/completions", "accounts/fireworks/models/deepseek-v3"),
|
|
24
|
+
("pplx-", "Perplexity", "https://api.perplexity.ai/chat/completions", "sonar"),
|
|
25
|
+
("wosb-api", "WOSB AI", "https://ai.wosb-chat.us.ci/api/v1/chat/completions", "groq_gpt_120"),
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
PROBE_PROVIDERS = [
|
|
29
|
+
("DeepSeek", "https://api.deepseek.com/chat/completions", "https://api.deepseek.com/models", "deepseek-chat"),
|
|
30
|
+
("OpenAI", "https://api.openai.com/v1/chat/completions", "https://api.openai.com/v1/models", "gpt-4o-mini"),
|
|
31
|
+
("ProxyAPI (РФ)", "https://api.proxyapi.ru/openai/v1/chat/completions", "https://api.proxyapi.ru/openai/v1/models", "gpt-4o-mini"),
|
|
32
|
+
("Together AI", "https://api.together.xyz/v1/chat/completions", "https://api.together.xyz/v1/models", "Qwen/Qwen2.5-Coder-32B-Instruct"),
|
|
33
|
+
("SambaNova", "https://api.sambanova.ai/v1/chat/completions", "https://api.sambanova.ai/v1/models", "DeepSeek-R1-Distill-Llama-70B"),
|
|
34
|
+
("Mistral AI", "https://api.mistral.ai/v1/chat/completions", "https://api.mistral.ai/v1/models", "codestral-latest"),
|
|
35
|
+
("Alibaba Qwen", "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions", "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/models", "qwen-coder-plus"),
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def get_desktop_path() -> str:
|
|
40
|
+
home = Path.home()
|
|
41
|
+
onedrive_desktop = home / "OneDrive" / "Desktop"
|
|
42
|
+
if onedrive_desktop.exists():
|
|
43
|
+
return str(onedrive_desktop)
|
|
44
|
+
return str(home / "Desktop")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def resolve_smart_path(raw_path: str) -> Path:
|
|
48
|
+
cleaned = raw_path.strip().strip('"').strip("'")
|
|
49
|
+
expanded = os.path.expandvars(os.path.expanduser(cleaned))
|
|
50
|
+
p = Path(expanded)
|
|
51
|
+
norm = cleaned.replace("\\", "/")
|
|
52
|
+
if norm.startswith("~/Desktop/"):
|
|
53
|
+
return Path(get_desktop_path()) / norm[len("~/Desktop/"):]
|
|
54
|
+
if norm.lower().startswith("desktop/"):
|
|
55
|
+
return Path(get_desktop_path()) / norm[len("desktop/"):]
|
|
56
|
+
return p
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def load_project_rules() -> str:
|
|
60
|
+
"""Читает файл правил проекта WOSB.md или CLAUDE.md, если он есть в папке."""
|
|
61
|
+
for fname in ("WOSB.md", "CLAUDE.md", ".wosbrules"):
|
|
62
|
+
p = Path(fname)
|
|
63
|
+
if p.exists():
|
|
64
|
+
try:
|
|
65
|
+
text = p.read_text(encoding="utf-8", errors="ignore")[:8000]
|
|
66
|
+
return f"\nПРАВИЛА ПРОЕКТА ({fname}):\n{text}\n"
|
|
67
|
+
except Exception:
|
|
68
|
+
pass
|
|
69
|
+
return ""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def build_system_prompt() -> str:
|
|
73
|
+
desktop = get_desktop_path()
|
|
74
|
+
cwd = os.getcwd()
|
|
75
|
+
rules = load_project_rules()
|
|
76
|
+
return f"""Ты — профессиональный автономный ИИ-агент уровня Claude Code / Qwen Code.
|
|
77
|
+
Рабочая папка: {cwd}
|
|
78
|
+
Рабочий стол: {desktop}
|
|
79
|
+
{rules}
|
|
80
|
+
Ты действуешь через строгие XML-теги инструментов (это исключает ошибки экранирования кавычек и слешей).
|
|
81
|
+
Выводи ТОЛЬКО ОДИН блок инструмента за один ответ:
|
|
82
|
+
|
|
83
|
+
1. Точечное редактирование файла (ЗАМЕНА куска кода без перезаписи всего файла — ИСПОЛЬЗУЙ ЭТО ДЛЯ ПРАВОК!):
|
|
84
|
+
<tool name="edit_file">
|
|
85
|
+
<path>путь_к_файлу</path>
|
|
86
|
+
<search>точный старый фрагмент кода, который нужно заменить</search>
|
|
87
|
+
<replace>новый фрагмент кода</replace>
|
|
88
|
+
</tool>
|
|
89
|
+
|
|
90
|
+
2. Создание нового файла или полная перезапись маленького файла:
|
|
91
|
+
<tool name="write_file">
|
|
92
|
+
<path>путь_к_файлу</path>
|
|
93
|
+
<content>полное содержимое файла</content>
|
|
94
|
+
</tool>
|
|
95
|
+
|
|
96
|
+
3. Поиск текста/функций по всему проекту (как ripgrep):
|
|
97
|
+
<tool name="search_text">
|
|
98
|
+
<query>искомая_строка</query>
|
|
99
|
+
</tool>
|
|
100
|
+
|
|
101
|
+
4. Чтение файла (с поддержкой диапазона строк, чтобы не забивать память):
|
|
102
|
+
<tool name="read_file">
|
|
103
|
+
<path>путь_к_файлу</path>
|
|
104
|
+
<start_line>1</start_line>
|
|
105
|
+
<end_line>250</end_line>
|
|
106
|
+
</tool>
|
|
107
|
+
|
|
108
|
+
5. Список файлов в папке:
|
|
109
|
+
<tool name="list_files">
|
|
110
|
+
<path>.</path>
|
|
111
|
+
</tool>
|
|
112
|
+
|
|
113
|
+
6. Выполнение команды в терминале Windows:
|
|
114
|
+
<tool name="run_cmd">
|
|
115
|
+
<command>команда</command>
|
|
116
|
+
</tool>
|
|
117
|
+
|
|
118
|
+
7. Завершение задачи и итоговый ответ пользователю:
|
|
119
|
+
<tool name="finish">
|
|
120
|
+
<message>Подробный отчет на русском языке, что было сделано</message>
|
|
121
|
+
</tool>
|
|
122
|
+
|
|
123
|
+
ЖЕЛЕЗНЫЕ ПРАВИЛА:
|
|
124
|
+
- Для изменения существующих файлов ВСЕГДА сначала прочитай нужный участок через read_file и используй edit_file (перезаписывай целиком через write_file только новые файлы).
|
|
125
|
+
- НИКОГДА не используй '~' в путях. Для Рабочего стола пиши полный путь: {desktop}\имя_файла."""
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def load_config():
|
|
129
|
+
if CONFIG_PATH.exists():
|
|
130
|
+
try:
|
|
131
|
+
return json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
|
|
132
|
+
except Exception:
|
|
133
|
+
pass
|
|
134
|
+
return {}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def save_config(cfg):
|
|
138
|
+
CONFIG_PATH.write_text(json.dumps(cfg, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def auto_detect_provider(api_key: str):
|
|
142
|
+
for prefix, name, chat_url, default_model in PREFIX_PROVIDERS:
|
|
143
|
+
if api_key.startswith(prefix):
|
|
144
|
+
return name, chat_url, default_model
|
|
145
|
+
|
|
146
|
+
with console.status("[bold cyan]Определяю провайдера по ключу среди крупных ИИ...[/bold cyan]"):
|
|
147
|
+
headers = {"Authorization": f"Bearer {api_key}"}
|
|
148
|
+
for name, chat_url, models_url, default_model in PROBE_PROVIDERS:
|
|
149
|
+
try:
|
|
150
|
+
r = requests.get(models_url, headers=headers, timeout=4)
|
|
151
|
+
if r.status_code == 200:
|
|
152
|
+
return name, chat_url, default_model
|
|
153
|
+
except Exception:
|
|
154
|
+
continue
|
|
155
|
+
|
|
156
|
+
return None, None, None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def setup_key():
|
|
160
|
+
console.print("\n[bold cyan]Подключение API-ключа (DeepSeek, OpenAI, Google, Claude, Grok, Groq, WOSB и др.)[/bold cyan]")
|
|
161
|
+
api_key = Prompt.ask("Вставьте любой API-ключ").strip()
|
|
162
|
+
|
|
163
|
+
prov_name, chat_url, default_model = auto_detect_provider(api_key)
|
|
164
|
+
|
|
165
|
+
if chat_url:
|
|
166
|
+
console.print(f"[bold green]✔ Определён сервис:[/bold green] {prov_name} ({chat_url})")
|
|
167
|
+
else:
|
|
168
|
+
console.print("[yellow]Не удалось определить сервер автоматически.[/yellow]")
|
|
169
|
+
prov_name = "Custom API"
|
|
170
|
+
chat_url = Prompt.ask("Введите API URL (до /chat/completions)").strip()
|
|
171
|
+
default_model = ""
|
|
172
|
+
|
|
173
|
+
model = Prompt.ask(
|
|
174
|
+
"Введите название модели",
|
|
175
|
+
default=default_model if default_model else None
|
|
176
|
+
).strip()
|
|
177
|
+
|
|
178
|
+
cfg = {
|
|
179
|
+
"provider": prov_name,
|
|
180
|
+
"api_key": api_key,
|
|
181
|
+
"api_url": chat_url,
|
|
182
|
+
"model": model
|
|
183
|
+
}
|
|
184
|
+
save_config(cfg)
|
|
185
|
+
console.print("[bold green]✔ Настройки сохранены![/bold green]\n")
|
|
186
|
+
return cfg
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def parse_tool_xml(text: str):
|
|
190
|
+
"""Надежный парсер XML-инструментов (не ломается от кавычек и переносов строк в коде)."""
|
|
191
|
+
tool_match = re.search(r'<tool\s+name="([^"]+)">(.*?)</tool>', text, re.DOTALL)
|
|
192
|
+
if not tool_match:
|
|
193
|
+
return None
|
|
194
|
+
tool_name = tool_match.group(1).strip()
|
|
195
|
+
body = tool_match.group(2)
|
|
196
|
+
|
|
197
|
+
params = {}
|
|
198
|
+
for tag in ("path", "search", "replace", "content", "query", "start_line", "end_line", "command", "message"):
|
|
199
|
+
m = re.search(rf"<{tag}>(.*?)</{tag}>", body, re.DOTALL)
|
|
200
|
+
if m:
|
|
201
|
+
val = m.group(1)
|
|
202
|
+
if val.startswith("\n"):
|
|
203
|
+
val = val[1:]
|
|
204
|
+
if val.endswith("\n"):
|
|
205
|
+
val = val[:-1]
|
|
206
|
+
params[tag] = val
|
|
207
|
+
return tool_name, params
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def trim_history(messages: list, max_messages: int = 24) -> list:
|
|
211
|
+
"""Сжимает историю, чтобы не переполнять контекстное окно на длинных задачах."""
|
|
212
|
+
if len(messages) <= max_messages:
|
|
213
|
+
return messages
|
|
214
|
+
system_msg = messages[0]
|
|
215
|
+
first_user = messages[1]
|
|
216
|
+
tail = messages[-(max_messages - 2):]
|
|
217
|
+
return [system_msg, first_user] + tail
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def execute_tool(tool_name: str, params: dict) -> str:
|
|
221
|
+
if tool_name == "list_files":
|
|
222
|
+
target_raw = params.get("path", ".")
|
|
223
|
+
target = str(resolve_smart_path(target_raw)) if target_raw != "." else "."
|
|
224
|
+
ignore = {".git", "__pycache__", "venv", ".venv", "node_modules"}
|
|
225
|
+
result = []
|
|
226
|
+
for root, dirs, files in os.walk(target):
|
|
227
|
+
dirs[:] = [d for d in dirs if d not in ignore and not d.endswith(".egg-info")]
|
|
228
|
+
for f in files:
|
|
229
|
+
result.append(os.path.join(root, f))
|
|
230
|
+
console.print(f"[dim]📂 Список файлов ({len(result)} шт.)[/dim]")
|
|
231
|
+
return "Список файлов:\n" + "\n".join(result[:200])
|
|
232
|
+
|
|
233
|
+
elif tool_name == "search_text":
|
|
234
|
+
query = params.get("query", "").strip()
|
|
235
|
+
if not query:
|
|
236
|
+
return "Ошибка: пустой поисковый запрос."
|
|
237
|
+
ignore = {".git", "__pycache__", "venv", ".venv", "node_modules"}
|
|
238
|
+
matches = []
|
|
239
|
+
for root, dirs, files in os.walk("."):
|
|
240
|
+
dirs[:] = [d for d in dirs if d not in ignore and not d.endswith(".egg-info")]
|
|
241
|
+
for f in files:
|
|
242
|
+
p = Path(root) / f
|
|
243
|
+
try:
|
|
244
|
+
if p.stat().st_size > 200_000:
|
|
245
|
+
continue
|
|
246
|
+
lines = p.read_text(encoding="utf-8", errors="ignore").splitlines()
|
|
247
|
+
for idx, line in enumerate(lines, 1):
|
|
248
|
+
if query.lower() in line.lower():
|
|
249
|
+
matches.append(f"{p}:{idx}: {line.strip()[:140]}")
|
|
250
|
+
if len(matches) >= 60:
|
|
251
|
+
break
|
|
252
|
+
except Exception:
|
|
253
|
+
pass
|
|
254
|
+
if len(matches) >= 60:
|
|
255
|
+
break
|
|
256
|
+
console.print(f"[dim]🔍 Поиск '{query}': найдено {len(matches)} совпадений[/dim]")
|
|
257
|
+
return "Результаты поиска:\n" + ("\n".join(matches) if matches else "Совпадений не найдено.")
|
|
258
|
+
|
|
259
|
+
elif tool_name == "read_file":
|
|
260
|
+
p = resolve_smart_path(params.get("path", ""))
|
|
261
|
+
if not p.exists():
|
|
262
|
+
return f"Ошибка: файл '{p}' не существует."
|
|
263
|
+
lines = p.read_text(encoding="utf-8", errors="ignore").splitlines()
|
|
264
|
+
total = len(lines)
|
|
265
|
+
start = max(1, int(params.get("start_line", 1) or 1))
|
|
266
|
+
end = min(total, int(params.get("end_line", start + 249) or (start + 249)))
|
|
267
|
+
chunk = "\n".join(f"{i}: {lines[i-1]}" for i in range(start, end + 1))
|
|
268
|
+
console.print(f"[dim]📖 Чтение {p} (строки {start}-{end} из {total})[/dim]")
|
|
269
|
+
return f"Файл {p} (строки {start}-{end} из {total}):\n{chunk}"
|
|
270
|
+
|
|
271
|
+
elif tool_name == "edit_file":
|
|
272
|
+
p = resolve_smart_path(params.get("path", ""))
|
|
273
|
+
search_block = params.get("search", "")
|
|
274
|
+
replace_block = params.get("replace", "")
|
|
275
|
+
if not p.exists():
|
|
276
|
+
return f"Ошибка: файл '{p}' не найден для редактирования."
|
|
277
|
+
text = p.read_text(encoding="utf-8", errors="ignore")
|
|
278
|
+
if search_block not in text:
|
|
279
|
+
# Пробуем нормализовать переносы строк CRLF -> LF
|
|
280
|
+
norm_text = text.replace("\r\n", "\n")
|
|
281
|
+
norm_search = search_block.replace("\r\n", "\n")
|
|
282
|
+
if norm_search not in norm_text:
|
|
283
|
+
console.print(f"[yellow]⚠ Не найден фрагмент для замены в {p}[/yellow]")
|
|
284
|
+
return "Ошибка edit_file: точный блок <search> не найден в файле. Прочитай файл через read_file и проверь отступы."
|
|
285
|
+
new_text = norm_text.replace(norm_search, replace_block, 1)
|
|
286
|
+
else:
|
|
287
|
+
new_text = text.replace(search_block, replace_block, 1)
|
|
288
|
+
|
|
289
|
+
p.write_text(new_text, encoding="utf-8")
|
|
290
|
+
console.print(f"[bold green]✏ Точечно обновлён файл:[/bold green] [cyan]{p.resolve()}[/cyan]")
|
|
291
|
+
return f"Успешно: фрагмент в файле '{p.resolve()}' заменён."
|
|
292
|
+
|
|
293
|
+
elif tool_name == "write_file":
|
|
294
|
+
p = resolve_smart_path(params.get("path", ""))
|
|
295
|
+
content = params.get("content", "")
|
|
296
|
+
try:
|
|
297
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
298
|
+
p.write_text(content, encoding="utf-8")
|
|
299
|
+
console.print(f"[bold green]✔ Записан файл:[/bold green] [cyan]{p.resolve()}[/cyan]")
|
|
300
|
+
return f"Файл успешно записан: {p.resolve()}"
|
|
301
|
+
except Exception as e:
|
|
302
|
+
console.print(f"[bold red]✖ Ошибка записи {p}:[/bold red] {e}")
|
|
303
|
+
return f"Ошибка при записи файла: {e}"
|
|
304
|
+
|
|
305
|
+
elif tool_name == "run_cmd":
|
|
306
|
+
cmd = params.get("command", "").strip()
|
|
307
|
+
console.print(f"[bold magenta]⚡ Команда:[/bold magenta] [cyan]{cmd}[/cyan]")
|
|
308
|
+
try:
|
|
309
|
+
proc = subprocess.run(cmd, shell=True, capture_output=True, timeout=90)
|
|
310
|
+
stdout = proc.stdout.decode("utf-8", errors="replace")
|
|
311
|
+
stderr = proc.stderr.decode("utf-8", errors="replace")
|
|
312
|
+
out = (stdout + "\n" + stderr).strip()
|
|
313
|
+
console.print(Panel(out[:1500] if out else "(выполнено успешно)", title=f"Код выхода: {proc.returncode}"))
|
|
314
|
+
return f"Код выхода: {proc.returncode}\nВывод:\n{out[:8000]}"
|
|
315
|
+
except Exception as e:
|
|
316
|
+
console.print(f"[bold red]✖ Ошибка команды:[/bold red] {e}")
|
|
317
|
+
return f"Ошибка выполнения команды: {e}"
|
|
318
|
+
|
|
319
|
+
return f"Неизвестный инструмент: {tool_name}"
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def call_llm(cfg, messages):
|
|
323
|
+
url = cfg["api_url"]
|
|
324
|
+
key = cfg["api_key"]
|
|
325
|
+
model = cfg["model"]
|
|
326
|
+
|
|
327
|
+
if "api.anthropic.com" in url:
|
|
328
|
+
headers = {
|
|
329
|
+
"x-api-key": key,
|
|
330
|
+
"anthropic-version": "2023-06-01",
|
|
331
|
+
"Content-Type": "application/json"
|
|
332
|
+
}
|
|
333
|
+
system_msg = messages[0]["content"] if messages[0]["role"] == "system" else ""
|
|
334
|
+
msgs = [m for m in messages if m["role"] != "system"]
|
|
335
|
+
payload = {
|
|
336
|
+
"model": model,
|
|
337
|
+
"max_tokens": 4096,
|
|
338
|
+
"system": system_msg,
|
|
339
|
+
"messages": msgs
|
|
340
|
+
}
|
|
341
|
+
resp = requests.post(url, headers=headers, json=payload, timeout=120)
|
|
342
|
+
resp.raise_for_status()
|
|
343
|
+
return resp.json()["content"][0]["text"]
|
|
344
|
+
|
|
345
|
+
headers = {
|
|
346
|
+
"Authorization": f"Bearer {key}",
|
|
347
|
+
"Content-Type": "application/json"
|
|
348
|
+
}
|
|
349
|
+
payload = {
|
|
350
|
+
"model": model,
|
|
351
|
+
"messages": messages,
|
|
352
|
+
"temperature": 0.1
|
|
353
|
+
}
|
|
354
|
+
resp = requests.post(url, headers=headers, json=payload, timeout=120)
|
|
355
|
+
resp.raise_for_status()
|
|
356
|
+
return resp.json()["choices"][0]["message"]["content"]
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def main():
|
|
360
|
+
console.print(Panel(
|
|
361
|
+
"[bold cyan]⚡ WOSB Code Pro v3.0 — Автономный агент уровня Claude Code / Qwen Code[/bold cyan]\n"
|
|
362
|
+
"Возможности: точечный diff-редактор (edit_file), поиск по коду (search_text),\n"
|
|
363
|
+
"построчное чтение больших файлов, правила WOSB.md и 40 шагов автономной работы.\n"
|
|
364
|
+
"Команды: [bold]/key[/bold] (сменить ключ), [bold]/model[/bold] (сменить модель), [bold]/clear[/bold] (очистить чат), [bold]/exit[/bold] (выход)"
|
|
365
|
+
))
|
|
366
|
+
|
|
367
|
+
cfg = load_config()
|
|
368
|
+
if not cfg.get("api_key") or not cfg.get("api_url"):
|
|
369
|
+
cfg = setup_key()
|
|
370
|
+
|
|
371
|
+
console.print(f"Сервис: [green]{cfg.get('provider')}[/green] | Модель: [cyan]{cfg['model']}[/cyan]\n")
|
|
372
|
+
|
|
373
|
+
messages = [{"role": "system", "content": build_system_prompt()}]
|
|
374
|
+
|
|
375
|
+
while True:
|
|
376
|
+
try:
|
|
377
|
+
user_input = Prompt.ask("[bold blue]Капитан[/bold blue]")
|
|
378
|
+
if not user_input.strip():
|
|
379
|
+
continue
|
|
380
|
+
|
|
381
|
+
cmd = user_input.strip().lower()
|
|
382
|
+
if cmd in ["/exit", "/quit"]:
|
|
383
|
+
break
|
|
384
|
+
if cmd == "/key":
|
|
385
|
+
cfg = setup_key()
|
|
386
|
+
continue
|
|
387
|
+
if cmd == "/model":
|
|
388
|
+
cfg["model"] = Prompt.ask("Новая модель", default=cfg["model"]).strip()
|
|
389
|
+
save_config(cfg)
|
|
390
|
+
console.print(f"Модель: [cyan]{cfg['model']}[/cyan]\n")
|
|
391
|
+
continue
|
|
392
|
+
if cmd == "/clear":
|
|
393
|
+
messages = [{"role": "system", "content": build_system_prompt()}]
|
|
394
|
+
console.print("[green]Память очищена.[/green]\n")
|
|
395
|
+
continue
|
|
396
|
+
|
|
397
|
+
enforced_prompt = (
|
|
398
|
+
f"{user_input}\n\n"
|
|
399
|
+
"[СИСТЕМА: Вызови нужный инструмент в формате <tool name=\"...\">...</tool>. "
|
|
400
|
+
"Для правки существующих файлов используй edit_file!]"
|
|
401
|
+
)
|
|
402
|
+
messages.append({"role": "user", "content": enforced_prompt})
|
|
403
|
+
|
|
404
|
+
for step in range(40):
|
|
405
|
+
messages = trim_history(messages)
|
|
406
|
+
with console.status(f"[bold green]Агент работает (шаг {step + 1}/40)...[/bold green]"):
|
|
407
|
+
raw_reply = call_llm(cfg, messages)
|
|
408
|
+
|
|
409
|
+
parsed = parse_tool_xml(raw_reply)
|
|
410
|
+
if not parsed:
|
|
411
|
+
console.print(f"\n[bold green]{cfg['model']}[/bold green]:")
|
|
412
|
+
console.print(Markdown(raw_reply))
|
|
413
|
+
console.print()
|
|
414
|
+
messages.append({"role": "assistant", "content": raw_reply})
|
|
415
|
+
break
|
|
416
|
+
|
|
417
|
+
tool_name, params = parsed
|
|
418
|
+
messages.append({"role": "assistant", "content": raw_reply})
|
|
419
|
+
|
|
420
|
+
if tool_name == "finish":
|
|
421
|
+
console.print(f"\n[bold green]{cfg['model']}[/bold green]:")
|
|
422
|
+
console.print(Markdown(params.get("message", "Задача выполнена.")))
|
|
423
|
+
console.print()
|
|
424
|
+
break
|
|
425
|
+
else:
|
|
426
|
+
tool_result = execute_tool(tool_name, params)
|
|
427
|
+
messages.append({
|
|
428
|
+
"role": "user",
|
|
429
|
+
"content": f"Результат {tool_name}:\n{tool_result}\nЕсли всё готово — вызови <tool name=\"finish\">."
|
|
430
|
+
})
|
|
431
|
+
|
|
432
|
+
except KeyboardInterrupt:
|
|
433
|
+
console.print("\n[yellow]Прервано пользователем.[/yellow]")
|
|
434
|
+
except Exception as e:
|
|
435
|
+
console.print(f"[bold red]Ошибка:[/bold red] {e}\n")
|
|
436
|
+
if messages and messages[-1]["role"] == "user":
|
|
437
|
+
messages.pop()
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
if __name__ == "__main__":
|
|
441
|
+
main()
|