7zon-cli 0.2.2__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.
- 7zon_cli-0.2.2.dist-info/METADATA +341 -0
- 7zon_cli-0.2.2.dist-info/RECORD +24 -0
- 7zon_cli-0.2.2.dist-info/WHEEL +4 -0
- 7zon_cli-0.2.2.dist-info/entry_points.txt +2 -0
- 7zon_cli-0.2.2.dist-info/licenses/LICENSE +21 -0
- zon7/__init__.py +1 -0
- zon7/__main__.py +3 -0
- zon7/ai.py +45 -0
- zon7/banner.py +74 -0
- zon7/cli.py +517 -0
- zon7/common.py +16 -0
- zon7/config.py +80 -0
- zon7/context.py +91 -0
- zon7/instagram.py +224 -0
- zon7/memory.py +66 -0
- zon7/menu.py +162 -0
- zon7/prompts.py +85 -0
- zon7/providers/__init__.py +1 -0
- zon7/providers/claude.py +220 -0
- zon7/providers/gemini.py +381 -0
- zon7/safety.py +61 -0
- zon7/secrets.py +133 -0
- zon7/shell.py +61 -0
- zon7/tools.py +855 -0
zon7/cli.py
ADDED
|
@@ -0,0 +1,517 @@
|
|
|
1
|
+
"""7ZON CLI — terminalda ishlaydigan AI yordamchi."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
import shlex
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
import typer
|
|
13
|
+
from rich.console import Console
|
|
14
|
+
from rich.live import Live
|
|
15
|
+
from rich.markdown import Markdown
|
|
16
|
+
from rich.panel import Panel
|
|
17
|
+
from rich.syntax import Syntax
|
|
18
|
+
from rich.text import Text
|
|
19
|
+
|
|
20
|
+
from zon7 import __version__, ai, banner, config, context, memory, menu, prompts, safety, shell, tools
|
|
21
|
+
from zon7 import secrets as vault
|
|
22
|
+
from zon7.ai import AIError, stream_answer, suggest_command
|
|
23
|
+
|
|
24
|
+
app = typer.Typer(
|
|
25
|
+
name="7zon",
|
|
26
|
+
help="7ZON — terminalda ishlaydigan AI yordamchi. Buyruq yozadi, xatolarni tuzatadi, tushuntiradi.",
|
|
27
|
+
add_completion=False,
|
|
28
|
+
rich_markup_mode="rich",
|
|
29
|
+
)
|
|
30
|
+
config_app = typer.Typer(help="Sozlamalarni ko'rish va o'zgartirish.", no_args_is_help=True)
|
|
31
|
+
app.add_typer(config_app, name="config")
|
|
32
|
+
secret_app = typer.Typer(help="Parollar va tokenlar (tizim omborida, AI'ga ko'rinmaydi).", no_args_is_help=True)
|
|
33
|
+
app.add_typer(secret_app, name="secret")
|
|
34
|
+
|
|
35
|
+
console = Console()
|
|
36
|
+
err = Console(stderr=True)
|
|
37
|
+
|
|
38
|
+
MAX_OUTPUT_CHARS = 30_000
|
|
39
|
+
RISK_STYLE = {"safe": ("green", "✓ xavfsiz"), "caution": ("yellow", "⚠ ehtiyot bo'ling"), "danger": ("red", "✖ XAVFLI")}
|
|
40
|
+
EXIT_WORDS = {"exit", "quit", "chiqish", "q", ":q"}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _choose(title: str, options: list, default: int, danger: bool = False) -> int:
|
|
44
|
+
"""Strelkali menyu (terminalda) yoki qatorli javob. Ctrl+C bekor qiladi."""
|
|
45
|
+
try:
|
|
46
|
+
return menu.choose(title, options, default, ask=console.input, danger=danger)
|
|
47
|
+
except (KeyboardInterrupt, EOFError):
|
|
48
|
+
console.print("\n[dim]Bekor qilindi.[/]")
|
|
49
|
+
raise typer.Exit(130)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _fail(message: str, code: int = 1) -> None:
|
|
53
|
+
err.print(f"[bold red]Xato:[/] {message}")
|
|
54
|
+
raise typer.Exit(code)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _stream_markdown(system: str, messages: list[dict], cfg: dict) -> str:
|
|
58
|
+
buffer: list[str] = []
|
|
59
|
+
with Live(Markdown(""), console=console, refresh_per_second=12, vertical_overflow="visible") as live:
|
|
60
|
+
def on_text(chunk: str) -> None:
|
|
61
|
+
buffer.append(chunk)
|
|
62
|
+
live.update(Markdown("".join(buffer)))
|
|
63
|
+
|
|
64
|
+
return stream_answer(system, messages, cfg, on_text)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _run(command: str) -> int:
|
|
68
|
+
return subprocess.run(shell.argv(command, interactive=True)).returncode
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _run_capture(command: str) -> tuple[int, str]:
|
|
72
|
+
"""Buyruqni ishga tushiradi: chiqishni ekranga ham chiqaradi, ham yig'adi."""
|
|
73
|
+
proc = subprocess.Popen(
|
|
74
|
+
shell.argv(command), stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
|
75
|
+
text=True, encoding="utf-8", errors="replace",
|
|
76
|
+
)
|
|
77
|
+
lines: list[str] = []
|
|
78
|
+
assert proc.stdout is not None
|
|
79
|
+
for line in proc.stdout:
|
|
80
|
+
sys.stdout.write(line)
|
|
81
|
+
lines.append(line)
|
|
82
|
+
return proc.wait(), "".join(lines)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _trim(output: str) -> tuple[str, bool]:
|
|
86
|
+
"""Juda uzun loglarning boshi va oxirini qoldiradi (xato odatda oxirida bo'ladi)."""
|
|
87
|
+
if len(output) <= MAX_OUTPUT_CHARS:
|
|
88
|
+
return output, False
|
|
89
|
+
head = output[: MAX_OUTPUT_CHARS // 4]
|
|
90
|
+
tail = output[-(MAX_OUTPUT_CHARS * 3 // 4):]
|
|
91
|
+
return f"{head}\n\n[... {len(output) - len(head) - len(tail)} belgi qisqartirildi ...]\n\n{tail}", True
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# --------------------------------------------------------------------------- ask
|
|
95
|
+
|
|
96
|
+
@app.command()
|
|
97
|
+
def ask(
|
|
98
|
+
request: list[str] = typer.Argument(..., help="Nima qilmoqchisiz, oddiy so'zlar bilan."),
|
|
99
|
+
yes: bool = typer.Option(False, "--yes", "-y", help="Xavfsiz buyruqni so'ramasdan bajarish."),
|
|
100
|
+
print_only: bool = typer.Option(False, "--print", "-p", help="Faqat buyruqni chiqarish (skriptlar uchun)."),
|
|
101
|
+
) -> None:
|
|
102
|
+
"""Tabiiy tildagi so'rovdan terminal buyrug'ini yaratadi va bajaradi.
|
|
103
|
+
|
|
104
|
+
Misol: [cyan]7zon ask "3000-portni band qilgan jarayonni o'chir"[/]
|
|
105
|
+
"""
|
|
106
|
+
cfg = config.load()
|
|
107
|
+
text = " ".join(request).strip()
|
|
108
|
+
if not text:
|
|
109
|
+
_fail("So'rov bo'sh.")
|
|
110
|
+
|
|
111
|
+
try:
|
|
112
|
+
with console.status("[cyan]O'ylayapman...[/]", spinner="dots"):
|
|
113
|
+
result = suggest_command(text, context.describe(), prompts.ask_system(cfg["lang"]), cfg)
|
|
114
|
+
except AIError as e:
|
|
115
|
+
_fail(str(e))
|
|
116
|
+
|
|
117
|
+
command = result["command"].strip()
|
|
118
|
+
if not command:
|
|
119
|
+
console.print(Panel(result["explanation"] or "Buni terminal buyrug'i bilan bajarib bo'lmaydi.", border_style="yellow"))
|
|
120
|
+
raise typer.Exit(1)
|
|
121
|
+
|
|
122
|
+
if print_only:
|
|
123
|
+
print(command)
|
|
124
|
+
return
|
|
125
|
+
|
|
126
|
+
local_level, reasons = safety.assess(command)
|
|
127
|
+
level = safety.stricter(result["risk"], local_level)
|
|
128
|
+
color, label = RISK_STYLE[level]
|
|
129
|
+
|
|
130
|
+
body = Text()
|
|
131
|
+
body.append(result["explanation"] + "\n\n")
|
|
132
|
+
body.append(label, style=f"bold {color}")
|
|
133
|
+
if reasons:
|
|
134
|
+
body.append(": " + "; ".join(reasons), style=color)
|
|
135
|
+
console.print(Panel(Syntax(command, "bash", theme="ansi_dark", word_wrap=True), title="[bold]7ZON[/]", border_style=color))
|
|
136
|
+
console.print(body)
|
|
137
|
+
|
|
138
|
+
while True:
|
|
139
|
+
if yes and level == "safe":
|
|
140
|
+
break
|
|
141
|
+
if level == "danger":
|
|
142
|
+
if _choose("XAVFLI buyruq. Bajarilsinmi?",
|
|
143
|
+
[("Bajarish (xavfli!)", {"ha", "yes"}), ("Bekor qilish", {"n", "no"})],
|
|
144
|
+
default=1, danger=True) != 0:
|
|
145
|
+
console.print("[dim]Bekor qilindi.[/]")
|
|
146
|
+
return
|
|
147
|
+
break
|
|
148
|
+
choice = _choose("Bajarilsinmi?", [
|
|
149
|
+
("Bajarish", {"y", "yes", "ha", "h"}),
|
|
150
|
+
("Tahrirlash", {"e", "edit"}),
|
|
151
|
+
("Bekor qilish", {"n", "no"}),
|
|
152
|
+
], default=0)
|
|
153
|
+
if choice == 0:
|
|
154
|
+
break
|
|
155
|
+
if choice == 1:
|
|
156
|
+
try:
|
|
157
|
+
edited = _edit(command)
|
|
158
|
+
except (KeyboardInterrupt, EOFError):
|
|
159
|
+
edited = ""
|
|
160
|
+
if not edited.strip():
|
|
161
|
+
console.print("[dim]Bekor qilindi.[/]")
|
|
162
|
+
return
|
|
163
|
+
command = edited.strip()
|
|
164
|
+
level, reasons = safety.assess(command)
|
|
165
|
+
continue
|
|
166
|
+
console.print("[dim]Bekor qilindi.[/]")
|
|
167
|
+
return
|
|
168
|
+
|
|
169
|
+
code = _run(command)
|
|
170
|
+
if code != 0:
|
|
171
|
+
console.print(
|
|
172
|
+
f"\n[yellow]Buyruq {code} kodi bilan tugadi.[/] Tahlil qilish uchun: "
|
|
173
|
+
f"[cyan]7zon fix -- {command}[/]"
|
|
174
|
+
)
|
|
175
|
+
raise typer.Exit(code)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _edit(command: str) -> str:
|
|
179
|
+
try:
|
|
180
|
+
import readline
|
|
181
|
+
|
|
182
|
+
readline.set_startup_hook(lambda: readline.insert_text(command))
|
|
183
|
+
try:
|
|
184
|
+
return input("Buyruq: ")
|
|
185
|
+
finally:
|
|
186
|
+
readline.set_startup_hook()
|
|
187
|
+
except ImportError: # Windows
|
|
188
|
+
console.print(f"[dim]Hozirgi: {command}[/]")
|
|
189
|
+
return input("Buyruq: ")
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
# --------------------------------------------------------------------------- fix
|
|
193
|
+
|
|
194
|
+
@app.command(context_settings={"allow_extra_args": True, "ignore_unknown_options": True})
|
|
195
|
+
def fix(
|
|
196
|
+
ctx: typer.Context,
|
|
197
|
+
force: bool = typer.Option(False, "--force", "-f", help="Buyruq muvaffaqiyatli tugasa ham tahlil qilish."),
|
|
198
|
+
) -> None:
|
|
199
|
+
"""Xatoni tushuntiradi va yechim beradi.
|
|
200
|
+
|
|
201
|
+
Misollar:
|
|
202
|
+
[cyan]7zon fix -- npm run build[/]
|
|
203
|
+
[cyan]python app.py 2>&1 | 7zon fix[/]
|
|
204
|
+
"""
|
|
205
|
+
cfg = config.load()
|
|
206
|
+
args = list(ctx.args)
|
|
207
|
+
|
|
208
|
+
if args:
|
|
209
|
+
command = shlex.join(args) if len(args) > 1 else args[0]
|
|
210
|
+
console.print(f"[dim]$ {command}[/]")
|
|
211
|
+
code, output = _run_capture(command)
|
|
212
|
+
if code == 0 and not force:
|
|
213
|
+
console.print("\n[green]✓ Buyruq muvaffaqiyatli tugadi, xato yo'q.[/] (Baribir tahlil uchun: --force)")
|
|
214
|
+
return
|
|
215
|
+
header = f"Command: {command}\nExit code: {code}"
|
|
216
|
+
elif not sys.stdin.isatty():
|
|
217
|
+
output = sys.stdin.read()
|
|
218
|
+
header = "Command: (output was piped in; command unknown)"
|
|
219
|
+
else:
|
|
220
|
+
_fail("Buyruq yoki xato matni kerak.\n 7zon fix -- npm run build\n npm run build 2>&1 | 7zon fix")
|
|
221
|
+
return
|
|
222
|
+
|
|
223
|
+
if not output.strip():
|
|
224
|
+
_fail("Tahlil qilish uchun chiqish (output) bo'sh.")
|
|
225
|
+
|
|
226
|
+
output, trimmed = _trim(output)
|
|
227
|
+
if trimmed:
|
|
228
|
+
console.print("[dim]Log juda uzun, boshi va oxiri yuborildi.[/]")
|
|
229
|
+
|
|
230
|
+
console.print(Panel.fit("[bold]7ZON tahlili[/]", border_style="cyan"))
|
|
231
|
+
content = f"<environment>\n{context.describe()}\n</environment>\n\n{header}\n\n<output>\n{output}\n</output>"
|
|
232
|
+
try:
|
|
233
|
+
_stream_markdown(prompts.fix_system(cfg["lang"]), [{"role": "user", "content": content}], cfg)
|
|
234
|
+
except AIError as e:
|
|
235
|
+
_fail(str(e))
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
# --------------------------------------------------------------------------- explain
|
|
239
|
+
|
|
240
|
+
@app.command()
|
|
241
|
+
def explain(command: list[str] = typer.Argument(..., help="Tushuntiriladigan buyruq.")) -> None:
|
|
242
|
+
"""Buyruq nima qilishini qismlarga bo'lib tushuntiradi.
|
|
243
|
+
|
|
244
|
+
Misol: [cyan]7zon explain "tar -xzvf archive.tar.gz -C /opt"[/]
|
|
245
|
+
"""
|
|
246
|
+
cfg = config.load()
|
|
247
|
+
text = " ".join(command)
|
|
248
|
+
level, reasons = safety.assess(text)
|
|
249
|
+
if level != "safe":
|
|
250
|
+
color, label = RISK_STYLE[level]
|
|
251
|
+
console.print(f"[{color}]{label}: {'; '.join(reasons)}[/]\n")
|
|
252
|
+
try:
|
|
253
|
+
_stream_markdown(
|
|
254
|
+
prompts.explain_system(cfg["lang"]),
|
|
255
|
+
[{"role": "user", "content": f"<environment>\n{context.describe()}\n</environment>\n\nCommand:\n{text}"}],
|
|
256
|
+
cfg,
|
|
257
|
+
)
|
|
258
|
+
except AIError as e:
|
|
259
|
+
_fail(str(e))
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
# --------------------------------------------------------------------------- chat
|
|
263
|
+
|
|
264
|
+
@app.command()
|
|
265
|
+
def chat() -> None:
|
|
266
|
+
"""AI bilan terminalda suhbat. Chiqish: [cyan]exit[/] yoki Ctrl+D."""
|
|
267
|
+
_chat_session()
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _build_agent(cfg: dict, headless: bool = False, yolo: bool = False) -> tuple[Any, Any]:
|
|
271
|
+
runner = tools.ToolRunner(console, console.input, headless=headless)
|
|
272
|
+
runner.auto_approve = yolo
|
|
273
|
+
try:
|
|
274
|
+
tools.ToolRunner.prepare_workspace()
|
|
275
|
+
except OSError:
|
|
276
|
+
pass
|
|
277
|
+
system = (
|
|
278
|
+
prompts.chat_system(cfg["lang"])
|
|
279
|
+
+ "\n\nUser environment:\n" + context.describe()
|
|
280
|
+
+ f"\nWorking directory (full path): {runner.cwd}\nHome directory: {Path.home()}"
|
|
281
|
+
+ "\nThe 7ZON workspace ~/.7zon (scripts/, sessions/ with chmod 700) already exists; do not create it again."
|
|
282
|
+
)
|
|
283
|
+
if headless:
|
|
284
|
+
system += ("\n\nHeadless mode: nobody is watching, so you cannot ask questions. Do the task with sensible "
|
|
285
|
+
"defaults; actions that need approval are refused unless --yolo was given.")
|
|
286
|
+
remembered = memory.load(runner.cwd)
|
|
287
|
+
if remembered:
|
|
288
|
+
system += "\n\nMemory (facts and project rules saved earlier; follow them):\n" + remembered
|
|
289
|
+
return ai.make_agent(system, cfg, tools.TOOL_SPECS), runner
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _headless(task: str, yolo: bool) -> None:
|
|
293
|
+
cfg = config.load()
|
|
294
|
+
try:
|
|
295
|
+
agent, runner = _build_agent(cfg, headless=True, yolo=yolo)
|
|
296
|
+
agent.send(task, runner, lambda text: console.print(Markdown(text.strip())), lambda: contextlib.nullcontext())
|
|
297
|
+
except AIError as e:
|
|
298
|
+
_fail(str(e))
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _chat_session(yolo: bool = False) -> None:
|
|
302
|
+
cfg = config.load()
|
|
303
|
+
try:
|
|
304
|
+
prov = ai.provider(cfg)
|
|
305
|
+
except AIError as e:
|
|
306
|
+
_fail(str(e))
|
|
307
|
+
banner.render(console, __version__, cfg, prov)
|
|
308
|
+
banner.tips(console)
|
|
309
|
+
agent, runner = _build_agent(cfg, yolo=yolo)
|
|
310
|
+
if yolo:
|
|
311
|
+
console.print("[yellow]⚡ YOLO rejimi: oddiy amallar so'ralmaydi (xavfli amallar baribir so'raladi).[/]")
|
|
312
|
+
prefix = f"[bold {banner.ORANGE[2]}]7ZON ›[/]"
|
|
313
|
+
|
|
314
|
+
def on_text(text: str) -> None:
|
|
315
|
+
console.print(Markdown(text.strip()))
|
|
316
|
+
|
|
317
|
+
def thinking():
|
|
318
|
+
return console.status("[dim]O'ylayapman...[/]", spinner="dots")
|
|
319
|
+
|
|
320
|
+
while True:
|
|
321
|
+
try:
|
|
322
|
+
question = console.input("\n[bold green]Siz ›[/] ").strip()
|
|
323
|
+
except (EOFError, KeyboardInterrupt):
|
|
324
|
+
console.print()
|
|
325
|
+
break
|
|
326
|
+
if not question:
|
|
327
|
+
continue
|
|
328
|
+
if question.lower() in EXIT_WORDS or question.lower() in ("/exit", "/quit"):
|
|
329
|
+
break
|
|
330
|
+
if question.startswith("/"):
|
|
331
|
+
_slash_command(question, agent, runner, thinking)
|
|
332
|
+
continue
|
|
333
|
+
console.print(prefix)
|
|
334
|
+
try:
|
|
335
|
+
agent.send(question, runner, on_text, thinking)
|
|
336
|
+
except AIError as e:
|
|
337
|
+
err.print(f"[bold red]Xato:[/] {e}")
|
|
338
|
+
except (KeyboardInterrupt, EOFError):
|
|
339
|
+
console.print("\n[dim]To'xtatildi.[/]")
|
|
340
|
+
console.print("[dim]Xayr! 👋[/]")
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
SLASH_HELP = """[bold]Buyruqlar:[/]
|
|
344
|
+
[cyan]/help[/] shu ro'yxat
|
|
345
|
+
[cyan]/clear[/] suhbatni tozalash (yangidan boshlash)
|
|
346
|
+
[cyan]/compress[/] uzun suhbatni qisqa xulosaga aylantirish
|
|
347
|
+
[cyan]/memory[/] eslab qolingan faktlar va loyiha qoidalari (7ZON.md)
|
|
348
|
+
[cyan]/undo[/] 7ZON qilgan oxirgi fayl o'zgarishini qaytarish
|
|
349
|
+
[cyan]/yolo[/] ruxsat so'rashni yoqish/o'chirish (xavfli amallar baribir so'raladi)
|
|
350
|
+
[cyan]/exit[/] chiqish"""
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _slash_command(line: str, agent: Any, runner: Any, thinking: Any) -> None:
|
|
354
|
+
cmd = line.split()[0].lower()
|
|
355
|
+
if cmd == "/help":
|
|
356
|
+
console.print(SLASH_HELP)
|
|
357
|
+
elif cmd == "/clear":
|
|
358
|
+
agent.clear()
|
|
359
|
+
console.print("[green]✓ Suhbat tozalandi.[/]")
|
|
360
|
+
elif cmd == "/compress":
|
|
361
|
+
try:
|
|
362
|
+
with thinking():
|
|
363
|
+
done = agent.compress()
|
|
364
|
+
except AIError as e:
|
|
365
|
+
err.print(f"[bold red]Xato:[/] {e}")
|
|
366
|
+
return
|
|
367
|
+
console.print("[green]✓ Suhbat xulosaga aylantirildi.[/]" if done else "[dim]Qisqartirish uchun suhbat hali qisqa.[/]")
|
|
368
|
+
elif cmd == "/memory":
|
|
369
|
+
text = memory.load(runner.cwd)
|
|
370
|
+
console.print(Markdown(text) if text else "[dim]Hali hech narsa eslab qolinmagan. Masalan: \"eslab qol: men pnpm ishlataman\"[/]")
|
|
371
|
+
console.print(f"[dim]Fayllar: {memory.global_file()} va {memory.project_file(runner.cwd)}[/]")
|
|
372
|
+
elif cmd == "/undo":
|
|
373
|
+
restored = runner.undo()
|
|
374
|
+
console.print(f"[green]✓ Qaytarildi:[/] {restored}" if restored else "[dim]Qaytariladigan o'zgarish yo'q.[/]")
|
|
375
|
+
elif cmd == "/yolo":
|
|
376
|
+
runner.auto_approve = not runner.auto_approve
|
|
377
|
+
state = "[yellow]YOQILDI[/]: oddiy amallar so'ralmaydi" if runner.auto_approve else "[green]o'chirildi[/]: har amal so'raladi"
|
|
378
|
+
console.print(f"YOLO {state}. Xavfli amallar va Instagram'ga joylash baribir so'raladi.")
|
|
379
|
+
else:
|
|
380
|
+
console.print(f"[yellow]Noma'lum buyruq: {cmd}[/]. Ro'yxat: [cyan]/help[/]")
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
# --------------------------------------------------------------------------- config
|
|
384
|
+
|
|
385
|
+
@config_app.command("show")
|
|
386
|
+
def config_show() -> None:
|
|
387
|
+
"""Joriy sozlamalarni ko'rsatadi."""
|
|
388
|
+
cfg = config.load()
|
|
389
|
+
prov = ai.provider(cfg)
|
|
390
|
+
env_name = next((n for n in prov.ENV_KEYS if os.environ.get(n)), None)
|
|
391
|
+
if env_name:
|
|
392
|
+
key_info = f"{config.mask(os.environ[env_name])} ({env_name})"
|
|
393
|
+
else:
|
|
394
|
+
key_info = config.mask(cfg.get(config.KEY_FIELDS[cfg["provider"]]))
|
|
395
|
+
console.print(f"[bold]Fayl:[/] {config.config_path()}")
|
|
396
|
+
console.print(f"[bold]provider:[/] {cfg['provider']}")
|
|
397
|
+
console.print(f"[bold]model:[/] {cfg['model'] or prov.DEFAULT_MODEL}" + ("" if cfg["model"] else " [dim](standart)[/]"))
|
|
398
|
+
console.print(f"[bold]lang:[/] {cfg['lang']}")
|
|
399
|
+
if cfg["provider"] == "claude":
|
|
400
|
+
console.print(f"[bold]effort:[/] {cfg['effort']}")
|
|
401
|
+
console.print(f"[bold]api kalit:[/] {key_info}")
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
@config_app.command("set")
|
|
405
|
+
def config_set(
|
|
406
|
+
key: str = typer.Argument(..., help="provider | model | lang | effort"),
|
|
407
|
+
value: str = typer.Argument(...),
|
|
408
|
+
) -> None:
|
|
409
|
+
"""Sozlamani o'zgartiradi. Misol: [cyan]7zon config set provider claude[/]"""
|
|
410
|
+
if key.endswith("api_key"):
|
|
411
|
+
_fail("API kalit uchun: 7zon config set-key")
|
|
412
|
+
try:
|
|
413
|
+
config.set_value(key, value)
|
|
414
|
+
except KeyError:
|
|
415
|
+
_fail(f"Noma'lum sozlama: {key}. Mavjudlari: provider, model, lang, effort")
|
|
416
|
+
except ValueError as e:
|
|
417
|
+
_fail(str(e))
|
|
418
|
+
if key == "provider":
|
|
419
|
+
# Boshqa provayderning modeli mos kelmaydi, standartga qaytaramiz
|
|
420
|
+
config.set_value("model", "")
|
|
421
|
+
console.print(f"[green]✓[/] {key} = {value}")
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
@config_app.command("set-key")
|
|
425
|
+
def config_set_key(
|
|
426
|
+
provider: str = typer.Option(None, "--provider", help="gemini | claude (standart: joriy provayder)"),
|
|
427
|
+
) -> None:
|
|
428
|
+
"""API kalitni saqlaydi. Gemini: aistudio.google.com/apikey · Claude: console.anthropic.com"""
|
|
429
|
+
cfg = config.load()
|
|
430
|
+
name = provider or cfg["provider"]
|
|
431
|
+
if name not in config.KEY_FIELDS:
|
|
432
|
+
_fail("Provayder: gemini yoki claude")
|
|
433
|
+
key = typer.prompt(f"{name.capitalize()} API kalit", hide_input=True).strip()
|
|
434
|
+
if not key:
|
|
435
|
+
_fail("Kalit bo'sh.")
|
|
436
|
+
config.set_value(config.KEY_FIELDS[name], key)
|
|
437
|
+
console.print(f"[green]✓ Saqlandi:[/] {config.config_path()} (faqat sizga o'qish ruxsati bilan)")
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
# --------------------------------------------------------------------------- secret
|
|
441
|
+
|
|
442
|
+
@secret_app.command("add")
|
|
443
|
+
def secret_add(name: str = typer.Argument(..., help="Masalan: INSTAGRAM_PASSWORD")) -> None:
|
|
444
|
+
"""Maxfiy qiymatni yashirin kiritib, tizim omboriga (Keychain) saqlaydi."""
|
|
445
|
+
try:
|
|
446
|
+
key = vault.normalize(name)
|
|
447
|
+
except vault.SecretError as e:
|
|
448
|
+
_fail(str(e))
|
|
449
|
+
import getpass
|
|
450
|
+
|
|
451
|
+
try:
|
|
452
|
+
value = getpass.getpass(f"{key} (ekranda ko'rinmaydi): ")
|
|
453
|
+
except (KeyboardInterrupt, EOFError):
|
|
454
|
+
console.print("\n[dim]Bekor qilindi.[/]")
|
|
455
|
+
raise typer.Exit(130)
|
|
456
|
+
if not value:
|
|
457
|
+
_fail("Qiymat bo'sh.")
|
|
458
|
+
where = vault.save(key, value)
|
|
459
|
+
if not where:
|
|
460
|
+
_fail("Saqlab bo'lmadi.")
|
|
461
|
+
place = "Keychain'ga" if where == "keychain" else f"{vault.secrets_file()} ga (faqat sizga ochiq)"
|
|
462
|
+
console.print(f"[green]✓ {key} {place} saqlandi.[/] 7ZON uni buyruqlarda [cyan]${key}[/] sifatida ishlatadi, qiymatini AI ko'rmaydi.")
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
@secret_app.command("list")
|
|
466
|
+
def secret_list() -> None:
|
|
467
|
+
"""Saqlangan maxfiy qiymatlar nomlari (qiymatlarning o'zi ko'rsatilmaydi)."""
|
|
468
|
+
items = vault.names()
|
|
469
|
+
if not items:
|
|
470
|
+
console.print("[dim]Hali hech narsa saqlanmagan. Qo'shish: 7zon secret add NOM[/]")
|
|
471
|
+
return
|
|
472
|
+
for key in items:
|
|
473
|
+
console.print(f"🔐 {key}")
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
@secret_app.command("remove")
|
|
477
|
+
def secret_remove(name: str = typer.Argument(...)) -> None:
|
|
478
|
+
"""Maxfiy qiymatni o'chiradi."""
|
|
479
|
+
try:
|
|
480
|
+
key = vault.normalize(name)
|
|
481
|
+
except vault.SecretError as e:
|
|
482
|
+
_fail(str(e))
|
|
483
|
+
if vault.delete(key):
|
|
484
|
+
console.print(f"[green]✓ {key} o'chirildi.[/]")
|
|
485
|
+
else:
|
|
486
|
+
_fail(f"{key} topilmadi.")
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
# --------------------------------------------------------------------------- root
|
|
490
|
+
|
|
491
|
+
def _version(value: bool) -> None:
|
|
492
|
+
if value:
|
|
493
|
+
console.print(f"7zon {__version__}")
|
|
494
|
+
raise typer.Exit()
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
@app.callback(invoke_without_command=True)
|
|
498
|
+
def root(
|
|
499
|
+
ctx: typer.Context,
|
|
500
|
+
version: bool = typer.Option(False, "--version", "-v", callback=_version, is_eager=True, help="Versiyani ko'rsatish."),
|
|
501
|
+
prompt: str = typer.Option(None, "--prompt", "-p", help="Vazifani suhbatsiz bajarish (skript va CI uchun)."),
|
|
502
|
+
yolo: bool = typer.Option(False, "--yolo", help="Oddiy amallar uchun ruxsat so'ramaslik."),
|
|
503
|
+
) -> None:
|
|
504
|
+
"""Argumentsiz: logo va agent suhbati. -p bilan: bitta vazifani bajarib chiqadi."""
|
|
505
|
+
if ctx.invoked_subcommand is None:
|
|
506
|
+
if prompt:
|
|
507
|
+
_headless(prompt, yolo)
|
|
508
|
+
else:
|
|
509
|
+
_chat_session(yolo)
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def main() -> None:
|
|
513
|
+
app()
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
if __name__ == "__main__":
|
|
517
|
+
main()
|
zon7/common.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Provayderlar uchun umumiy narsalar."""
|
|
2
|
+
|
|
3
|
+
COMMAND_SCHEMA = {
|
|
4
|
+
"type": "object",
|
|
5
|
+
"properties": {
|
|
6
|
+
"command": {"type": "string"},
|
|
7
|
+
"explanation": {"type": "string"},
|
|
8
|
+
"risk": {"type": "string", "enum": ["safe", "caution", "danger"]},
|
|
9
|
+
},
|
|
10
|
+
"required": ["command", "explanation", "risk"],
|
|
11
|
+
"additionalProperties": False,
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class AIError(Exception):
|
|
16
|
+
"""Foydalanuvchiga ko'rsatiladigan tushunarli xato."""
|
zon7/config.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""7ZON sozlamalari: ~/.config/7zon/config.json (yoki $XDG_CONFIG_HOME/7zon)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
DEFAULTS: dict[str, Any] = {
|
|
11
|
+
"provider": "gemini", # gemini | claude
|
|
12
|
+
"model": "", # bo'sh = provayderning standart modeli
|
|
13
|
+
"lang": "uz", # uz | en | ru
|
|
14
|
+
"effort": "low", # faqat Claude uchun: low | medium | high | xhigh | max
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
KEY_FIELDS = {"gemini": "gemini_api_key", "claude": "anthropic_api_key"}
|
|
18
|
+
|
|
19
|
+
ALLOWED: dict[str, tuple[str, ...] | None] = {
|
|
20
|
+
"provider": ("gemini", "claude"),
|
|
21
|
+
"model": None,
|
|
22
|
+
"lang": ("uz", "en", "ru"),
|
|
23
|
+
"effort": ("low", "medium", "high", "xhigh", "max"),
|
|
24
|
+
"gemini_api_key": None,
|
|
25
|
+
"anthropic_api_key": None,
|
|
26
|
+
"secret_names": None,
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def config_dir() -> Path:
|
|
31
|
+
base = os.environ.get("XDG_CONFIG_HOME")
|
|
32
|
+
root = Path(base) if base else Path.home() / ".config"
|
|
33
|
+
return root / "7zon"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def config_path() -> Path:
|
|
37
|
+
return config_dir() / "config.json"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def load() -> dict[str, Any]:
|
|
41
|
+
data = dict(DEFAULTS)
|
|
42
|
+
path = config_path()
|
|
43
|
+
if path.exists():
|
|
44
|
+
try:
|
|
45
|
+
stored = json.loads(path.read_text(encoding="utf-8"))
|
|
46
|
+
# v0.1.0 dagi eski "api_key" Claude kaliti edi
|
|
47
|
+
if "api_key" in stored and "anthropic_api_key" not in stored:
|
|
48
|
+
stored["anthropic_api_key"] = stored.pop("api_key")
|
|
49
|
+
data.update(stored)
|
|
50
|
+
except (json.JSONDecodeError, OSError):
|
|
51
|
+
pass
|
|
52
|
+
return data
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def save(data: dict[str, Any]) -> None:
|
|
56
|
+
path = config_path()
|
|
57
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
58
|
+
stored = {k: v for k, v in data.items() if k not in DEFAULTS or v != DEFAULTS[k]}
|
|
59
|
+
path.write_text(json.dumps(stored, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
60
|
+
try:
|
|
61
|
+
os.chmod(path, 0o600) # API kalitni boshqa foydalanuvchilar o'qiy olmasin
|
|
62
|
+
except OSError:
|
|
63
|
+
pass
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def set_value(key: str, value: str) -> None:
|
|
67
|
+
if key not in ALLOWED:
|
|
68
|
+
raise KeyError(key)
|
|
69
|
+
allowed = ALLOWED[key]
|
|
70
|
+
if allowed is not None and value not in allowed:
|
|
71
|
+
raise ValueError(f"{key} uchun ruxsat etilgan qiymatlar: {', '.join(allowed)}")
|
|
72
|
+
data = load()
|
|
73
|
+
data[key] = value
|
|
74
|
+
save(data)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def mask(secret: str | None) -> str:
|
|
78
|
+
if not secret:
|
|
79
|
+
return "—"
|
|
80
|
+
return secret[:7] + "…" + secret[-4:] if len(secret) > 12 else "****"
|