7zon-cli 0.2.3__tar.gz → 0.2.5__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.
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/PKG-INFO +1 -1
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/pyproject.toml +1 -1
- 7zon_cli-0.2.5/src/zon7/__init__.py +1 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/src/zon7/cli.py +6 -8
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/src/zon7/context.py +6 -1
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/src/zon7/menu.py +92 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/src/zon7/prompts.py +1 -1
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/src/zon7/safety.py +7 -2
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/src/zon7/shell.py +2 -1
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/src/zon7/tools.py +65 -3
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/tests/test_cli.py +9 -3
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/tests/test_menu.py +36 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/tests/test_safety.py +22 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/tests/test_tools.py +61 -0
- 7zon_cli-0.2.3/src/zon7/__init__.py +0 -1
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/.github/workflows/ci.yml +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/.github/workflows/publish.yml +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/.gitignore +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/LICENSE +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/README.md +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/install-termux.sh +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/src/zon7/__main__.py +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/src/zon7/ai.py +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/src/zon7/banner.py +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/src/zon7/common.py +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/src/zon7/config.py +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/src/zon7/instagram.py +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/src/zon7/memory.py +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/src/zon7/providers/__init__.py +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/src/zon7/providers/claude.py +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/src/zon7/providers/gemini.py +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/src/zon7/secrets.py +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/tests/test_config.py +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/tests/test_context.py +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/tests/test_gemini.py +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/tests/test_instagram.py +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/tests/test_memory.py +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/tests/test_powershell_real.py +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/tests/test_secrets.py +0 -0
- {7zon_cli-0.2.3 → 7zon_cli-0.2.5}/tests/test_shell.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: 7zon-cli
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.5
|
|
4
4
|
Summary: 7ZON — terminalda ishlaydigan AI yordamchi: buyruq yozadi, xatolarni tuzatadi, tushuntiradi.
|
|
5
5
|
Project-URL: Homepage, https://github.com/7zon-uz/7ZON-CLI
|
|
6
6
|
Project-URL: Issues, https://github.com/7zon-uz/7ZON-CLI/issues
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.2.5"
|
|
@@ -306,7 +306,8 @@ def _has_key(cfg: dict[str, Any]) -> bool:
|
|
|
306
306
|
name = cfg.get("provider", "gemini")
|
|
307
307
|
if any(os.environ.get(e) for e in KEY_ENV.get(name, ())):
|
|
308
308
|
return True
|
|
309
|
-
|
|
309
|
+
# Eski versiya ko'rinmas belgini kalit sifatida saqlagan bo'lishi mumkin
|
|
310
|
+
return bool(config.clean_key(cfg.get(config.KEY_FIELDS.get(name, "")) or ""))
|
|
310
311
|
|
|
311
312
|
|
|
312
313
|
def _is_set_key_line(line: str) -> bool:
|
|
@@ -317,15 +318,13 @@ def _is_set_key_line(line: str) -> bool:
|
|
|
317
318
|
|
|
318
319
|
def _prompt_key(cfg: dict[str, Any], name: str | None = None) -> bool:
|
|
319
320
|
"""Kalitni yashirin so'raydi va saqlaydi. Saqlansa True."""
|
|
320
|
-
import getpass
|
|
321
|
-
|
|
322
321
|
name = name or cfg.get("provider", "gemini")
|
|
323
322
|
field = config.KEY_FIELDS[name]
|
|
324
323
|
console.print(f"[bold]{name.capitalize()} API kalit[/] kerak. Olish: [cyan]{KEY_URL[name]}[/]\n"
|
|
325
324
|
"[dim]Kalitni qo'ying (Ctrl+V yoki sichqonchaning o'ng tugmasi) va Enter bosing. "
|
|
326
|
-
"
|
|
325
|
+
"Kalit ekranda ochiq ko'rinmaydi, bu normal.[/]")
|
|
327
326
|
try:
|
|
328
|
-
key = config.clean_key(
|
|
327
|
+
key = config.clean_key(menu.read_secret(f"{name.capitalize()} API kalit: "))
|
|
329
328
|
except (EOFError, KeyboardInterrupt):
|
|
330
329
|
console.print()
|
|
331
330
|
return False
|
|
@@ -486,7 +485,7 @@ def config_set_key(
|
|
|
486
485
|
name = provider or cfg["provider"]
|
|
487
486
|
if name not in config.KEY_FIELDS:
|
|
488
487
|
_fail("Provayder: gemini yoki claude")
|
|
489
|
-
key = config.clean_key(
|
|
488
|
+
key = config.clean_key(menu.read_secret(f"{name.capitalize()} API kalit (Ctrl+V yoki o'ng tugma bilan joylang, keyin Enter): "))
|
|
490
489
|
problem = config.key_problem(key)
|
|
491
490
|
if problem:
|
|
492
491
|
_fail(problem)
|
|
@@ -503,10 +502,9 @@ def secret_add(name: str = typer.Argument(..., help="Masalan: INSTAGRAM_PASSWORD
|
|
|
503
502
|
key = vault.normalize(name)
|
|
504
503
|
except vault.SecretError as e:
|
|
505
504
|
_fail(str(e))
|
|
506
|
-
import getpass
|
|
507
505
|
|
|
508
506
|
try:
|
|
509
|
-
value =
|
|
507
|
+
value = menu.read_secret(f"{key} (ekranda ko'rinmaydi): ")
|
|
510
508
|
except (KeyboardInterrupt, EOFError):
|
|
511
509
|
console.print("\n[dim]Bekor qilindi.[/]")
|
|
512
510
|
raise typer.Exit(130)
|
|
@@ -28,7 +28,12 @@ WINDOWS_NOTE = (
|
|
|
28
28
|
"Windows notes: commands run in PowerShell. Write PowerShell syntax, not bash: join commands with `;` "
|
|
29
29
|
"(Windows PowerShell 5.1 has no `&&`), use $env:NAME for environment variables, New-Item -ItemType Directory, "
|
|
30
30
|
"Get-ChildItem, Remove-Item, Copy-Item, Test-Path, Invoke-WebRequest; open links with `Start-Process URL`; "
|
|
31
|
-
"install software with `winget install --id ID -e --accept-source-agreements --accept-package-agreements`."
|
|
31
|
+
"install software with `winget install --id ID -e --accept-source-agreements --accept-package-agreements`. "
|
|
32
|
+
"Never pass code with quotes to `python -c` (Windows PowerShell strips the inner double quotes and the code "
|
|
33
|
+
"breaks): write the script with write_file into ~/.7zon/scripts and run it with `python PATH`. "
|
|
34
|
+
"The 7ZON venv's tools are in ~/.7zon/venv/Scripts (python.exe, pip.exe), not venv/bin. "
|
|
35
|
+
"Save files from the internet with the download_file tool. The Desktop path is "
|
|
36
|
+
"[Environment]::GetFolderPath('Desktop') (it can be inside OneDrive)."
|
|
32
37
|
)
|
|
33
38
|
|
|
34
39
|
|
|
@@ -9,6 +9,7 @@ from __future__ import annotations
|
|
|
9
9
|
import os
|
|
10
10
|
import sys
|
|
11
11
|
from collections.abc import Callable, Sequence
|
|
12
|
+
from typing import Any
|
|
12
13
|
|
|
13
14
|
ORANGE = "\x1b[1;38;2;255;172;60m"
|
|
14
15
|
DIM = "\x1b[2m"
|
|
@@ -160,3 +161,94 @@ def choose(
|
|
|
160
161
|
if answer == str(i + 1) or answer in aliases:
|
|
161
162
|
return i
|
|
162
163
|
return len(options) - 1
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
# --------------------------------------------------------------------------- yashirin kiritish
|
|
167
|
+
|
|
168
|
+
def _windows_clipboard() -> str:
|
|
169
|
+
"""Windows clipboard matni (qo'shimcha kutubxonasiz)."""
|
|
170
|
+
try:
|
|
171
|
+
import ctypes
|
|
172
|
+
from ctypes import wintypes
|
|
173
|
+
|
|
174
|
+
user32 = ctypes.windll.user32 # type: ignore[attr-defined]
|
|
175
|
+
kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
|
|
176
|
+
user32.GetClipboardData.restype = wintypes.HANDLE
|
|
177
|
+
kernel32.GlobalLock.argtypes = [wintypes.HGLOBAL]
|
|
178
|
+
kernel32.GlobalLock.restype = ctypes.c_void_p
|
|
179
|
+
kernel32.GlobalUnlock.argtypes = [wintypes.HGLOBAL]
|
|
180
|
+
if not user32.OpenClipboard(None):
|
|
181
|
+
return ""
|
|
182
|
+
try:
|
|
183
|
+
handle = user32.GetClipboardData(13) # CF_UNICODETEXT
|
|
184
|
+
if not handle:
|
|
185
|
+
return ""
|
|
186
|
+
ptr = kernel32.GlobalLock(handle)
|
|
187
|
+
if not ptr:
|
|
188
|
+
return ""
|
|
189
|
+
try:
|
|
190
|
+
return ctypes.wstring_at(ptr)
|
|
191
|
+
finally:
|
|
192
|
+
kernel32.GlobalUnlock(handle)
|
|
193
|
+
finally:
|
|
194
|
+
user32.CloseClipboard()
|
|
195
|
+
except Exception:
|
|
196
|
+
return ""
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _read_secret_windows(prompt: str, getch: Callable[[], str], clipboard: Callable[[], str],
|
|
200
|
+
write: Callable[[str], Any]) -> str:
|
|
201
|
+
"""Windows konsolida yashirin kiritish: Ctrl+V va o'ng tugma bilan joylash ishlaydi.
|
|
202
|
+
|
|
203
|
+
Oddiy getpass cmd.exe'da Ctrl+V'ni kalit o'rniga ko'rinmas \\x16 belgi sifatida o'qiydi.
|
|
204
|
+
Har bir belgi o'rniga • chiqariladi, shunda joylash ishlagani ko'rinib turadi.
|
|
205
|
+
"""
|
|
206
|
+
write(prompt)
|
|
207
|
+
chars: list[str] = []
|
|
208
|
+
while True:
|
|
209
|
+
ch = getch()
|
|
210
|
+
if ch in ("\r", "\n"):
|
|
211
|
+
break
|
|
212
|
+
if ch == "\x03":
|
|
213
|
+
write("\n")
|
|
214
|
+
raise KeyboardInterrupt
|
|
215
|
+
if ch == "\x1a" and not chars: # Ctrl+Z
|
|
216
|
+
write("\n")
|
|
217
|
+
raise EOFError
|
|
218
|
+
if ch in ("\x00", "\xe0"): # strelka va F tugmalari: ikkinchi belgini tashlaymiz
|
|
219
|
+
getch()
|
|
220
|
+
continue
|
|
221
|
+
if ch == "\x08": # Backspace
|
|
222
|
+
if chars:
|
|
223
|
+
chars.pop()
|
|
224
|
+
write("\b \b")
|
|
225
|
+
continue
|
|
226
|
+
added = clipboard() if ch == "\x16" else ch # Ctrl+V
|
|
227
|
+
added = "".join(c for c in added if c.isprintable())
|
|
228
|
+
chars.extend(added)
|
|
229
|
+
write("•" * len(added))
|
|
230
|
+
write("\n")
|
|
231
|
+
return "".join(chars)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def read_secret(prompt: str) -> str:
|
|
235
|
+
"""Parol yoki API kalitni ekranga chiqarmay o'qiydi (Windows'da joylash ham ishlaydi)."""
|
|
236
|
+
if os.name == "nt" and is_interactive():
|
|
237
|
+
import msvcrt
|
|
238
|
+
|
|
239
|
+
def write(s: str) -> None:
|
|
240
|
+
sys.stdout.write(s)
|
|
241
|
+
sys.stdout.flush()
|
|
242
|
+
|
|
243
|
+
return _read_secret_windows(prompt, msvcrt.getwch, _windows_clipboard, write)
|
|
244
|
+
try:
|
|
245
|
+
piped = not sys.stdin.isatty()
|
|
246
|
+
except (AttributeError, ValueError):
|
|
247
|
+
piped = True
|
|
248
|
+
if piped: # pipe yoki test: yashiradigan ekran yo'q, qatorni oddiy o'qiymiz
|
|
249
|
+
sys.stdout.write(prompt)
|
|
250
|
+
sys.stdout.flush()
|
|
251
|
+
return sys.stdin.readline().rstrip("\r\n")
|
|
252
|
+
import getpass
|
|
253
|
+
|
|
254
|
+
return getpass.getpass(prompt)
|
|
@@ -44,7 +44,7 @@ You have tools: run_command (shell), read_file, write_file, edit_file (change pa
|
|
|
44
44
|
|
|
45
45
|
Working in a codebase: explore before changing. Use glob and grep (not shell find/grep) to locate code, read_file to read it, then edit_file for small changes. When the user shares a screenshot, design or PDF path, open it with view_file. When the user says "eslab qol" / "remember" or states a lasting preference, call save_memory. The user can undo your file changes with /undo. When the user asks you to do something on their computer (create a folder or project, write or edit files, run, build, install, use git, find files), do it yourself with the tools instead of telling them which commands to type. The user approves each command and file write, so just call the tool; do not ask "shall I run this?" in text first. Work step by step, check results (for example with list_directory or a quick command), and fix problems you hit.
|
|
46
46
|
|
|
47
|
-
Be proactive. Never answer "if you have X installed, you could..." — check yourself (for example `command -v gh`) and do the task. The user's computer usually has command-line tools that are already signed in: gh for GitHub (`gh repo list OWNER --limit 5 --json name,updatedAt,visibility`, `gh api ...`), git, docker, npm, cloud CLIs. For anything involving online accounts, use those existing sign-ins. To read a web page or a public API, use fetch_url. To search the web, use fetch_url with https://html.duckduckgo.com/html/?q=YOUR+QUERY and then open the best results.
|
|
47
|
+
Be proactive. Never answer "if you have X installed, you could..." — check yourself (for example `command -v gh`) and do the task. The user's computer usually has command-line tools that are already signed in: gh for GitHub (`gh repo list OWNER --limit 5 --json name,updatedAt,visibility`, `gh api ...`), git, docker, npm, cloud CLIs. For anything involving online accounts, use those existing sign-ins. To read a web page or a public API, use fetch_url. To search the web, use fetch_url with https://html.duckduckgo.com/html/?q=YOUR+QUERY and then open the best results. To save pictures or other files from the internet, use download_file. Never make up URLs of files, pictures or API endpoints: take them from a search, API answer or page you actually read; a guessed URL ends in 404.
|
|
48
48
|
|
|
49
49
|
Editing code: read the file first, then change only what is needed with edit_file (exact old text → new text); use write_file for new files or full rewrites. After changes, run the project's build or tests when there are any.
|
|
50
50
|
|
|
@@ -28,13 +28,15 @@ CAUTION_PATTERNS = [
|
|
|
28
28
|
(r"\bkill(all)?\b|\bpkill\b", "jarayonlarni to'xtatadi"),
|
|
29
29
|
(r"\bchmod\b|\bchown\b", "ruxsatlarni o'zgartiradi"),
|
|
30
30
|
(r"\bmv\b", "fayllarni ko'chiradi yoki ustidan yozadi"),
|
|
31
|
-
(r"(^|[
|
|
31
|
+
(r"(^|[^>=\-])>(?![>=])\s*\S", "faylning ustidan yozadi"),
|
|
32
32
|
(r"\b(npm|pnpm|yarn|pip|brew|apt(-get)?|dnf|pacman)\s+(uninstall|remove|purge)\b", "paketni o'chiradi"),
|
|
33
33
|
(r"\bdocker\s+(system\s+prune|rm|rmi|volume\s+rm)\b", "Docker resurslarini o'chiradi"),
|
|
34
34
|
(r"\bgit\s+(clean|checkout\s+--|restore)\b", "lokal o'zgarishlarni bekor qiladi"),
|
|
35
35
|
]
|
|
36
36
|
|
|
37
37
|
|
|
38
|
+
REDIRECT_PATTERN = CAUTION_PATTERNS[5][0]
|
|
39
|
+
QUOTED = re.compile(r"'[^']*'|\"(?:[^\"\\]|\\.)*\"")
|
|
38
40
|
HARMLESS_REDIRECTS = re.compile(r"(\d*|&)>>?\s*/dev/null\b|\d*>&\d+|<\s*/dev/null\b")
|
|
39
41
|
|
|
40
42
|
|
|
@@ -48,8 +50,11 @@ def assess(command: str) -> tuple[str, list[str]]:
|
|
|
48
50
|
return "danger", reasons
|
|
49
51
|
# Zararsiz yo'naltirishlar (chiqishni yashirish, stderr→stdout) faylni o'zgartirmaydi
|
|
50
52
|
harmless = HARMLESS_REDIRECTS.sub(" ", command)
|
|
53
|
+
# Qo'shtirnoq ichidagi matn (masalan, python -c '...' kodi) yo'naltirish emas: "a > b" taqqoslash, "->" strelka
|
|
54
|
+
unquoted = QUOTED.sub("''", harmless)
|
|
51
55
|
for pattern, reason in CAUTION_PATTERNS:
|
|
52
|
-
if
|
|
56
|
+
text = unquoted if pattern == REDIRECT_PATTERN else harmless
|
|
57
|
+
if re.search(pattern, text, re.IGNORECASE):
|
|
53
58
|
reasons.append(reason)
|
|
54
59
|
return ("caution" if reasons else "safe"), reasons
|
|
55
60
|
|
|
@@ -42,7 +42,8 @@ def argv(command: str, marker: str | None = None, interactive: bool = False, ps:
|
|
|
42
42
|
# UTF-8 chiqish va rang kodlarisiz oddiy matn (PowerShell 7.2+ da $PSStyle bor)
|
|
43
43
|
script = ("[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "
|
|
44
44
|
"$OutputEncoding = [System.Text.Encoding]::UTF8; "
|
|
45
|
-
"if ($PSStyle) { $PSStyle.OutputRendering = 'PlainText' }
|
|
45
|
+
"if ($PSStyle) { $PSStyle.OutputRendering = 'PlainText' }; "
|
|
46
|
+
"$PSNativeCommandArgumentPassing = 'Standard'\n" + command)
|
|
46
47
|
if marker:
|
|
47
48
|
script += (
|
|
48
49
|
"\n$__7zon_ok = $?"
|
|
@@ -6,7 +6,6 @@ Har bir o'zgartiruvchi amal (buyruq, fayl yozish) foydalanuvchi tasdig'idan keyi
|
|
|
6
6
|
from __future__ import annotations
|
|
7
7
|
|
|
8
8
|
import difflib
|
|
9
|
-
import getpass
|
|
10
9
|
import html
|
|
11
10
|
import os
|
|
12
11
|
import re
|
|
@@ -37,6 +36,8 @@ MAX_ATTACH_BYTES = 15_000_000
|
|
|
37
36
|
VIEWABLE = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif",
|
|
38
37
|
".webp": "image/webp", ".pdf": "application/pdf"}
|
|
39
38
|
FETCH_TIMEOUT = 20
|
|
39
|
+
DOWNLOAD_TIMEOUT = 60
|
|
40
|
+
MAX_DOWNLOAD_BYTES = 100_000_000
|
|
40
41
|
CWD_MARKER = "__7ZON_CWD__"
|
|
41
42
|
# Rang va kursor kodlari: ekranda axlat bo'lib ko'rinmasin va AI'ga bormasin
|
|
42
43
|
ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(\x07|\x1b\\)")
|
|
@@ -171,6 +172,26 @@ TOOL_SPECS: list[dict[str, Any]] = [
|
|
|
171
172
|
"additionalProperties": False,
|
|
172
173
|
},
|
|
173
174
|
},
|
|
175
|
+
{
|
|
176
|
+
"name": "download_file",
|
|
177
|
+
"description": (
|
|
178
|
+
"Save a file from a public URL (picture, PDF, archive, dataset) to a path on disk. Creates missing "
|
|
179
|
+
"folders. Use only URLs you got from a tool result (an API answer or a page you read); never guess "
|
|
180
|
+
"or make up file URLs. For pictures of a topic use the Wikimedia Commons API with fetch_url first: "
|
|
181
|
+
"https://commons.wikimedia.org/w/api.php?action=query&generator=search&gsrsearch=QUERY&gsrnamespace=6"
|
|
182
|
+
"&gsrlimit=20&prop=imageinfo&iiprop=url|mime&iiurlwidth=1280&format=json and then download each "
|
|
183
|
+
"imageinfo thumburl (or url). Check the returned content_type; HTML means it was not the file."
|
|
184
|
+
),
|
|
185
|
+
"parameters": {
|
|
186
|
+
"type": "object",
|
|
187
|
+
"properties": {
|
|
188
|
+
"url": {"type": "string", "description": "Direct http(s) URL of the file."},
|
|
189
|
+
"path": {"type": "string", "description": "Where to save it, e.g. ~/Desktop/folder/photo1.jpg"},
|
|
190
|
+
},
|
|
191
|
+
"required": ["url", "path"],
|
|
192
|
+
"additionalProperties": False,
|
|
193
|
+
},
|
|
194
|
+
},
|
|
174
195
|
{
|
|
175
196
|
"name": "glob",
|
|
176
197
|
"description": (
|
|
@@ -263,14 +284,14 @@ class ToolRunner:
|
|
|
263
284
|
console: Console,
|
|
264
285
|
ask: Callable[[str], str],
|
|
265
286
|
cwd: Path | None = None,
|
|
266
|
-
secret_input: Callable[[str], str] =
|
|
287
|
+
secret_input: Callable[[str], str] | None = None,
|
|
267
288
|
load_saved_secrets: bool = True,
|
|
268
289
|
headless: bool = False,
|
|
269
290
|
) -> None:
|
|
270
291
|
self.headless = headless # -p rejimi: savol berib bo'lmaydi
|
|
271
292
|
self.console = console
|
|
272
293
|
self.ask = ask # oddiy qator kiritish (menyu terminal bo'lmaganda ishlatadi)
|
|
273
|
-
self.secret_input = secret_input # yashirin kiritish: yozilgan belgilar ekranda ko'rinmaydi
|
|
294
|
+
self.secret_input = secret_input or menu.read_secret # yashirin kiritish: yozilgan belgilar ekranda ko'rinmaydi
|
|
274
295
|
self.cwd = (cwd or Path.cwd()).resolve()
|
|
275
296
|
self.auto_approve = False # "Barchasiga ruxsat" tanlangandan keyin xavfli bo'lmagan amallar so'ralmaydi
|
|
276
297
|
# Maxfiy qiymatlar: faqat shu jarayon xotirasida va buyruqlar muhitida, AI'ga hech qachon bormaydi
|
|
@@ -295,6 +316,9 @@ class ToolRunner:
|
|
|
295
316
|
|
|
296
317
|
def _env(self) -> dict[str, str]:
|
|
297
318
|
env = dict(os.environ)
|
|
319
|
+
# Windows'da Python skriptlari emoji/o'zbekcha matnni cp1251 bilan chiqara olmay yiqiladi
|
|
320
|
+
env.setdefault("PYTHONIOENCODING", "utf-8")
|
|
321
|
+
env.setdefault("PYTHONUTF8", "1")
|
|
298
322
|
env.update(self.secrets)
|
|
299
323
|
return env
|
|
300
324
|
|
|
@@ -356,6 +380,7 @@ class ToolRunner:
|
|
|
356
380
|
"write_file": self.write_file,
|
|
357
381
|
"list_directory": self.list_directory,
|
|
358
382
|
"fetch_url": self.fetch_url,
|
|
383
|
+
"download_file": self.download_file,
|
|
359
384
|
"edit_file": self.edit_file,
|
|
360
385
|
"request_secret": self.request_secret,
|
|
361
386
|
"instagram": self.instagram,
|
|
@@ -549,6 +574,43 @@ class ToolRunner:
|
|
|
549
574
|
self.console.print(f"[dim]📁 ko'rildi: {target}[/]")
|
|
550
575
|
return {"path": str(target), "entries": entries}
|
|
551
576
|
|
|
577
|
+
def download_file(self, url: str, path: str) -> dict[str, Any]:
|
|
578
|
+
url = url.strip()
|
|
579
|
+
if not re.match(r"^https?://", url, re.IGNORECASE):
|
|
580
|
+
return {"error": "Only http(s) URLs are supported."}
|
|
581
|
+
target = self._path(path)
|
|
582
|
+
exists = target.exists()
|
|
583
|
+
self.console.print(f"[bold]⬇️ Yuklab olish:[/] [cyan]{url}[/]\n → {target}")
|
|
584
|
+
if exists:
|
|
585
|
+
self.console.print("[yellow]⚠ bu fayl bor, ustidan yoziladi[/]")
|
|
586
|
+
if not self._confirm("caution" if exists else "safe"):
|
|
587
|
+
return {"declined": True, "message": "The user declined this download."}
|
|
588
|
+
request = urllib.request.Request(url, headers={
|
|
589
|
+
# Wikimedia kabi saytlar tushunarli User-Agent talab qiladi
|
|
590
|
+
"User-Agent": "7zon-cli/1.0 (https://github.com/7zon-uz/7ZON-CLI)", "Accept": "*/*"})
|
|
591
|
+
try:
|
|
592
|
+
with urllib.request.urlopen(request, timeout=DOWNLOAD_TIMEOUT) as resp:
|
|
593
|
+
data = resp.read(MAX_DOWNLOAD_BYTES + 1)
|
|
594
|
+
ctype = resp.headers.get("Content-Type", "")
|
|
595
|
+
except urllib.error.HTTPError as e:
|
|
596
|
+
msg = "HTTP 404: this URL does not exist; get real URLs from an API or page first" if e.code == 404 \
|
|
597
|
+
else f"HTTP {e.code}"
|
|
598
|
+
self.console.print(f"[red]✗ {msg.split(':')[0]}[/]")
|
|
599
|
+
return {"error": msg}
|
|
600
|
+
except (urllib.error.URLError, TimeoutError) as e:
|
|
601
|
+
return {"error": f"Could not open URL: {getattr(e, 'reason', e)}"}
|
|
602
|
+
if len(data) > MAX_DOWNLOAD_BYTES:
|
|
603
|
+
return {"error": f"File is larger than {MAX_DOWNLOAD_BYTES // 1_000_000} MB; download it with a command."}
|
|
604
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
605
|
+
if exists:
|
|
606
|
+
self._checkpoint(target)
|
|
607
|
+
target.write_bytes(data)
|
|
608
|
+
self.console.print(f"[green]✓ saqlandi[/] [dim]{len(data) // 1024} KB, {ctype or '?'}[/]")
|
|
609
|
+
result: dict[str, Any] = {"saved": str(target), "bytes": len(data), "content_type": ctype}
|
|
610
|
+
if "html" in ctype.lower():
|
|
611
|
+
result["warning"] = "The server returned an HTML page, not the file. Use a direct file URL."
|
|
612
|
+
return result
|
|
613
|
+
|
|
552
614
|
def fetch_url(self, url: str) -> dict[str, Any]:
|
|
553
615
|
url = url.strip()
|
|
554
616
|
if not re.match(r"^https?://", url, re.IGNORECASE):
|
|
@@ -250,7 +250,7 @@ def test_has_key(monkeypatch):
|
|
|
250
250
|
def test_prompt_key_saves_hidden(monkeypatch):
|
|
251
251
|
import getpass
|
|
252
252
|
|
|
253
|
-
monkeypatch.setattr(
|
|
253
|
+
monkeypatch.setattr(cli.menu, "read_secret", lambda prompt="": " SECRET123_long_test_key_000 ")
|
|
254
254
|
cfg = {"provider": "gemini"}
|
|
255
255
|
assert cli._prompt_key(cfg) is True
|
|
256
256
|
assert cfg["gemini_api_key"] == "SECRET123_long_test_key_000"
|
|
@@ -260,7 +260,7 @@ def test_prompt_key_saves_hidden(monkeypatch):
|
|
|
260
260
|
def test_prompt_key_empty(monkeypatch):
|
|
261
261
|
import getpass
|
|
262
262
|
|
|
263
|
-
monkeypatch.setattr(
|
|
263
|
+
monkeypatch.setattr(cli.menu, "read_secret", lambda prompt="": "")
|
|
264
264
|
cfg = {"provider": "gemini"}
|
|
265
265
|
assert cli._prompt_key(cfg) is False
|
|
266
266
|
assert "gemini_api_key" not in cfg
|
|
@@ -281,7 +281,7 @@ def test_set_key_typed_inside_chat(monkeypatch):
|
|
|
281
281
|
|
|
282
282
|
for e in ("GEMINI_API_KEY", "GOOGLE_API_KEY"):
|
|
283
283
|
monkeypatch.delenv(e, raising=False)
|
|
284
|
-
monkeypatch.setattr(
|
|
284
|
+
monkeypatch.setattr(cli.menu, "read_secret", lambda prompt="": "NEWKEY_long_test_key_00000")
|
|
285
285
|
monkeypatch.setattr(cli.ai, "make_agent", lambda *a, **k: FakeAgent())
|
|
286
286
|
result = runner.invoke(cli.app, ["chat"], input="7zon config set-key\nsalom\nexit\n")
|
|
287
287
|
assert result.exit_code == 0
|
|
@@ -289,3 +289,9 @@ def test_set_key_typed_inside_chat(monkeypatch):
|
|
|
289
289
|
assert "Javob" in result.output
|
|
290
290
|
assert "NEWKEY_long_test_key_00000" not in result.output
|
|
291
291
|
assert config.load()["gemini_api_key"] == "NEWKEY_long_test_key_00000"
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def test_junk_saved_key_counts_as_missing(monkeypatch):
|
|
295
|
+
for e in ("GEMINI_API_KEY", "GOOGLE_API_KEY"):
|
|
296
|
+
monkeypatch.delenv(e, raising=False)
|
|
297
|
+
assert cli._has_key({"provider": "gemini", "gemini_api_key": "\x16"}) is False
|
|
@@ -31,3 +31,39 @@ def test_arrow_ctrl_c(monkeypatch, capsys):
|
|
|
31
31
|
with pytest.raises(KeyboardInterrupt):
|
|
32
32
|
menu.select_arrows("?", ["a", "b"])
|
|
33
33
|
assert "\x1b[?25h" in capsys.readouterr().out # kursor qaytariladi
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# ---------------------------------------------------------------- Windows yashirin kiritish
|
|
37
|
+
|
|
38
|
+
def _run_reader(keys, clip=""):
|
|
39
|
+
from zon7 import menu
|
|
40
|
+
|
|
41
|
+
it = iter(keys)
|
|
42
|
+
out = []
|
|
43
|
+
value = menu._read_secret_windows("Kalit: ", lambda: next(it), lambda: clip, out.append)
|
|
44
|
+
return value, "".join(out)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def test_windows_secret_ctrl_v_pastes_clipboard():
|
|
48
|
+
value, shown = _run_reader(["\x16", "\r"], clip="AQ.secret_key_123\r\n")
|
|
49
|
+
assert value == "AQ.secret_key_123"
|
|
50
|
+
assert "secret" not in shown
|
|
51
|
+
assert "•" * len("AQ.secret_key_123") in shown
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_windows_secret_typed_and_backspace():
|
|
55
|
+
value, shown = _run_reader(["a", "b", "x", "\x08", "c", "\r"])
|
|
56
|
+
assert value == "abc"
|
|
57
|
+
assert "abc" not in shown
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_windows_secret_right_click_paste_arrives_as_keys():
|
|
61
|
+
value, _ = _run_reader(list("KEY123") + ["\r"])
|
|
62
|
+
assert value == "KEY123"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def test_windows_secret_ctrl_c():
|
|
66
|
+
import pytest
|
|
67
|
+
|
|
68
|
+
with pytest.raises(KeyboardInterrupt):
|
|
69
|
+
_run_reader(["a", "\x03"])
|
|
@@ -62,3 +62,25 @@ def test_harmless_redirects_are_safe(cmd):
|
|
|
62
62
|
|
|
63
63
|
def test_real_overwrite_still_caution():
|
|
64
64
|
assert assess("echo x > /dev/null; echo y > notes.txt")[0] == "caution"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# ---------------------------------------------------------------- qo'shtirnoq ichidagi ">" yo'naltirish emas
|
|
68
|
+
|
|
69
|
+
def test_python_code_with_arrow_and_comparison_is_not_overwrite():
|
|
70
|
+
from zon7 import safety
|
|
71
|
+
|
|
72
|
+
cmd = """python -c 'print(f"Downloading {u} -> {p}")\nif count > 6: pass'"""
|
|
73
|
+
assert "faylning ustidan yozadi" not in safety.assess(cmd)[1]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def test_real_redirect_still_flagged():
|
|
77
|
+
from zon7 import safety
|
|
78
|
+
|
|
79
|
+
assert "faylning ustidan yozadi" in safety.assess("echo salom > notes.txt")[1]
|
|
80
|
+
assert "faylning ustidan yozadi" in safety.assess('echo "a > b" > out.txt')[1]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def test_powershell_arrow_ops_not_flagged():
|
|
84
|
+
from zon7 import safety
|
|
85
|
+
|
|
86
|
+
assert safety.assess("Get-Process | Where-Object { $_.CPU -gt 10 }")[0] == "safe"
|
|
@@ -338,3 +338,64 @@ def test_edit_preserves_line_endings(tmp_path):
|
|
|
338
338
|
assert crlf.read_bytes() == b"a\r\nB\r\nc\r\n"
|
|
339
339
|
runner("write_file", {"path": "new.txt", "content": "x\ny\n"})
|
|
340
340
|
assert (tmp_path / "new.txt").read_bytes() == b"x\ny\n"
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
# ---------------------------------------------------------------- download_file
|
|
344
|
+
|
|
345
|
+
import http.server # noqa: E402
|
|
346
|
+
import threading # noqa: E402
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
@pytest.fixture
|
|
350
|
+
def file_server():
|
|
351
|
+
class Handler(http.server.BaseHTTPRequestHandler):
|
|
352
|
+
def do_GET(self): # noqa: N802
|
|
353
|
+
if self.path == "/pic.jpg":
|
|
354
|
+
body, ctype = b"\xff\xd8\xff" + b"0" * 2048, "image/jpeg"
|
|
355
|
+
elif self.path == "/page":
|
|
356
|
+
body, ctype = b"<html>hi</html>", "text/html"
|
|
357
|
+
else:
|
|
358
|
+
self.send_response(404)
|
|
359
|
+
self.end_headers()
|
|
360
|
+
return
|
|
361
|
+
self.send_response(200)
|
|
362
|
+
self.send_header("Content-Type", ctype)
|
|
363
|
+
self.send_header("Content-Length", str(len(body)))
|
|
364
|
+
self.end_headers()
|
|
365
|
+
self.wfile.write(body)
|
|
366
|
+
|
|
367
|
+
def log_message(self, *a):
|
|
368
|
+
pass
|
|
369
|
+
|
|
370
|
+
srv = http.server.HTTPServer(("127.0.0.1", 0), Handler)
|
|
371
|
+
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
|
372
|
+
yield f"http://127.0.0.1:{srv.server_port}"
|
|
373
|
+
srv.shutdown()
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def test_download_file_saves_into_new_folder(tmp_path, file_server):
|
|
377
|
+
r = make_runner(tmp_path, ["y"])
|
|
378
|
+
out = r("download_file", {"url": f"{file_server}/pic.jpg", "path": "rasul damas/damas_1.jpg"})
|
|
379
|
+
saved = tmp_path / "rasul damas" / "damas_1.jpg"
|
|
380
|
+
assert out["saved"] == str(saved.resolve())
|
|
381
|
+
assert saved.read_bytes().startswith(b"\xff\xd8\xff")
|
|
382
|
+
assert out["content_type"] == "image/jpeg"
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def test_download_file_404_says_url_is_made_up(tmp_path, file_server):
|
|
386
|
+
r = make_runner(tmp_path, ["y"])
|
|
387
|
+
out = r("download_file", {"url": f"{file_server}/nope.jpg", "path": "x.jpg"})
|
|
388
|
+
assert "404" in out["error"] and "real URLs" in out["error"]
|
|
389
|
+
assert not (tmp_path / "x.jpg").exists()
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def test_download_file_warns_on_html(tmp_path, file_server):
|
|
393
|
+
r = make_runner(tmp_path, ["y"])
|
|
394
|
+
out = r("download_file", {"url": f"{file_server}/page", "path": "p.jpg"})
|
|
395
|
+
assert "warning" in out
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def test_child_python_gets_utf8(tmp_path):
|
|
399
|
+
r = make_runner(tmp_path, [])
|
|
400
|
+
env = r._env()
|
|
401
|
+
assert env["PYTHONIOENCODING"] == "utf-8" and env["PYTHONUTF8"] == "1"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "0.2.3"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|