7zon-cli 0.2.2__tar.gz → 0.2.4__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 (40) hide show
  1. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/PKG-INFO +14 -10
  2. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/README.md +13 -9
  3. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/pyproject.toml +1 -1
  4. 7zon_cli-0.2.4/src/zon7/__init__.py +1 -0
  5. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/src/zon7/cli.py +60 -5
  6. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/src/zon7/config.py +26 -0
  7. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/src/zon7/menu.py +92 -0
  8. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/src/zon7/providers/gemini.py +8 -2
  9. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/src/zon7/tools.py +2 -3
  10. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/tests/test_cli.py +75 -1
  11. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/tests/test_config.py +30 -0
  12. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/tests/test_gemini.py +9 -0
  13. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/tests/test_menu.py +36 -0
  14. 7zon_cli-0.2.2/src/zon7/__init__.py +0 -1
  15. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/.github/workflows/ci.yml +0 -0
  16. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/.github/workflows/publish.yml +0 -0
  17. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/.gitignore +0 -0
  18. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/LICENSE +0 -0
  19. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/install-termux.sh +0 -0
  20. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/src/zon7/__main__.py +0 -0
  21. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/src/zon7/ai.py +0 -0
  22. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/src/zon7/banner.py +0 -0
  23. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/src/zon7/common.py +0 -0
  24. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/src/zon7/context.py +0 -0
  25. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/src/zon7/instagram.py +0 -0
  26. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/src/zon7/memory.py +0 -0
  27. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/src/zon7/prompts.py +0 -0
  28. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/src/zon7/providers/__init__.py +0 -0
  29. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/src/zon7/providers/claude.py +0 -0
  30. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/src/zon7/safety.py +0 -0
  31. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/src/zon7/secrets.py +0 -0
  32. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/src/zon7/shell.py +0 -0
  33. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/tests/test_context.py +0 -0
  34. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/tests/test_instagram.py +0 -0
  35. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/tests/test_memory.py +0 -0
  36. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/tests/test_powershell_real.py +0 -0
  37. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/tests/test_safety.py +0 -0
  38. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/tests/test_secrets.py +0 -0
  39. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/tests/test_shell.py +0 -0
  40. {7zon_cli-0.2.2 → 7zon_cli-0.2.4}/tests/test_tools.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: 7zon-cli
3
- Version: 0.2.2
3
+ Version: 0.2.4
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
@@ -44,6 +44,7 @@ Vazifani oddiy so'z bilan ayting: 7ZON buyruqlarni ishga tushiradi, fayl yozadi
44
44
  loyiha bo'ylab qidiradi, rasm va PDF'larni ko'radi, xatolarni tuzatadi. Har bir amaldan oldin ruxsat so'raydi.
45
45
 
46
46
  [![CI](https://github.com/7zon-uz/7ZON-CLI/actions/workflows/ci.yml/badge.svg)](https://github.com/7zon-uz/7ZON-CLI/actions)
47
+ [![PyPI](https://img.shields.io/pypi/v/7zon-cli)](https://pypi.org/project/7zon-cli/)
47
48
  ![Python](https://img.shields.io/badge/python-3.10%2B-blue)
48
49
  ![Platformalar](https://img.shields.io/badge/macOS%20·%20Linux%20·%20Windows%20·%20Termux-ishlaydi-orange)
49
50
  ![License](https://img.shields.io/badge/license-MIT-green)
@@ -86,12 +87,12 @@ brew install python
86
87
  brew install pipx && pipx ensurepath
87
88
  ```
88
89
  ```bash
89
- pipx install https://github.com/7zon-uz/7ZON-CLI/archive/refs/heads/main.zip
90
+ pipx install 7zon-cli
90
91
  ```
91
92
  <details><summary>pipx'siz o'rnatish</summary>
92
93
 
93
94
  ```bash
94
- python3 -m pip install --user https://github.com/7zon-uz/7ZON-CLI/archive/refs/heads/main.zip
95
+ python3 -m pip install --user 7zon-cli
95
96
  ```
96
97
  </details>
97
98
 
@@ -118,7 +119,7 @@ pipx ensurepath
118
119
 
119
120
  **2. 7ZON'ni o'rnating:**
120
121
  ```bash
121
- pipx install https://github.com/7zon-uz/7ZON-CLI/archive/refs/heads/main.zip
122
+ pipx install 7zon-cli
122
123
  ```
123
124
 
124
125
  **3. Terminalni qayta oching** va tekshiring:
@@ -141,7 +142,7 @@ winget install --id Python.Python.3.13 -e
141
142
 
142
143
  **2. PowerShell'ni yopib, qayta oching** va 7ZON'ni o'rnating:
143
144
  ```bash
144
- py -m pip install --user https://github.com/7zon-uz/7ZON-CLI/archive/refs/heads/main.zip
145
+ py -m pip install --user 7zon-cli
145
146
  ```
146
147
 
147
148
  **3. Tekshiring:**
@@ -163,7 +164,7 @@ py -m pip install --user https://github.com/7zon-uz/7ZON-CLI/archive/refs/heads/
163
164
  pkg update -y && pkg install -y python
164
165
  ```
165
166
  ```bash
166
- pip install https://github.com/7zon-uz/7ZON-CLI/archive/refs/heads/main.zip
167
+ pip install 7zon-cli
167
168
  ```
168
169
 
169
170
  Yoki tayyor skript bilan o'rnating:
@@ -190,6 +191,8 @@ curl -fsSL https://raw.githubusercontent.com/7zon-uz/7ZON-CLI/main/install-termu
190
191
  7zon config set-key
191
192
  ```
192
193
 
194
+ > 💡 Bu buyruq **terminalning o'zida** (PowerShell, Terminal, Termux) yoziladi, `Siz ›` chatining ichida emas. Agar 7ZON ochiq bo'lsa, kalit yo'qligida u o'zi so'raydi. Chat ichida istalgan vaqtda **`/key`** deb yozib kalitni almashtirish ham mumkin.
195
+
193
196
  Yoki muhit o'zgaruvchisi orqali bering:
194
197
 
195
198
  | Tizim | Buyruq |
@@ -246,6 +249,7 @@ Ruxsat berasizmi? (↑/↓ tanlash, Enter tasdiqlash)
246
249
  | `/compress` | Uzun suhbatni qisqa xulosaga aylantirish (bu avtomatik ham bajariladi) |
247
250
  | `/memory` | Eslab qolingan ma'lumotlar (`7ZON.md`) |
248
251
  | `/clear` | Suhbatni tozalash |
252
+ | `/key` | API kalitni kiritish yoki almashtirish (yashirin) |
249
253
  | `/yolo` | Oddiy amallar uchun ruxsat so'ramaslik |
250
254
  | `/exit` | Chiqish |
251
255
 
@@ -290,9 +294,9 @@ Ruxsat berasizmi? (↑/↓ tanlash, Enter tasdiqlash)
290
294
 
291
295
  | | Yangilash | O'chirish |
292
296
  |---|---|---|
293
- | pipx (macOS / Linux) | `pipx install --force https://github.com/7zon-uz/7ZON-CLI/archive/refs/heads/main.zip` | `pipx uninstall 7zon-cli` |
294
- | Windows | `py -m pip install --user --upgrade https://github.com/7zon-uz/7ZON-CLI/archive/refs/heads/main.zip` | `py -m pip uninstall 7zon-cli` |
295
- | Termux | `pip install --upgrade https://github.com/7zon-uz/7ZON-CLI/archive/refs/heads/main.zip` | `pip uninstall 7zon-cli` |
297
+ | pipx (macOS / Linux) | `pipx upgrade 7zon-cli` | `pipx uninstall 7zon-cli` |
298
+ | Windows | `py -m pip install --user --upgrade 7zon-cli` | `py -m pip uninstall 7zon-cli` |
299
+ | Termux | `pip install --upgrade 7zon-cli` | `pip uninstall 7zon-cli` |
296
300
 
297
301
  Sozlamalar `~/.config/7zon/` papkasida, ishchi fayllar esa `~/.7zon/` papkasida turadi. 7ZON'ni butunlay o'chirish uchun bu papkalarni ham o'chiring.
298
302
 
@@ -330,7 +334,7 @@ Xato topsangiz yoki taklifingiz bo'lsa, [Issue oching](https://github.com/7zon-u
330
334
  **7ZON CLI** is an AI agent for your terminal. Describe a task in plain words (Uzbek, English or Russian) and it runs commands, writes and edits files, searches your project, looks at images and PDFs, and fixes errors. It asks before every action using an arrow-key menu, and secrets are typed into a hidden prompt the AI never sees. It works on macOS, Linux, Windows (PowerShell) and Android (Termux), and needs only pure-Python dependencies.
331
335
 
332
336
  ```bash
333
- pipx install https://github.com/7zon-uz/7ZON-CLI/archive/refs/heads/main.zip # Windows: py -m pip install --user <same URL>
337
+ pipx install 7zon-cli # Windows: py -m pip install --user 7zon-cli
334
338
  7zon config set-key # free Gemini key: https://aistudio.google.com/apikey
335
339
  7zon config set lang en
336
340
  7zon # start the agent
@@ -18,6 +18,7 @@ Vazifani oddiy so'z bilan ayting: 7ZON buyruqlarni ishga tushiradi, fayl yozadi
18
18
  loyiha bo'ylab qidiradi, rasm va PDF'larni ko'radi, xatolarni tuzatadi. Har bir amaldan oldin ruxsat so'raydi.
19
19
 
20
20
  [![CI](https://github.com/7zon-uz/7ZON-CLI/actions/workflows/ci.yml/badge.svg)](https://github.com/7zon-uz/7ZON-CLI/actions)
21
+ [![PyPI](https://img.shields.io/pypi/v/7zon-cli)](https://pypi.org/project/7zon-cli/)
21
22
  ![Python](https://img.shields.io/badge/python-3.10%2B-blue)
22
23
  ![Platformalar](https://img.shields.io/badge/macOS%20·%20Linux%20·%20Windows%20·%20Termux-ishlaydi-orange)
23
24
  ![License](https://img.shields.io/badge/license-MIT-green)
@@ -60,12 +61,12 @@ brew install python
60
61
  brew install pipx && pipx ensurepath
61
62
  ```
62
63
  ```bash
63
- pipx install https://github.com/7zon-uz/7ZON-CLI/archive/refs/heads/main.zip
64
+ pipx install 7zon-cli
64
65
  ```
65
66
  <details><summary>pipx'siz o'rnatish</summary>
66
67
 
67
68
  ```bash
68
- python3 -m pip install --user https://github.com/7zon-uz/7ZON-CLI/archive/refs/heads/main.zip
69
+ python3 -m pip install --user 7zon-cli
69
70
  ```
70
71
  </details>
71
72
 
@@ -92,7 +93,7 @@ pipx ensurepath
92
93
 
93
94
  **2. 7ZON'ni o'rnating:**
94
95
  ```bash
95
- pipx install https://github.com/7zon-uz/7ZON-CLI/archive/refs/heads/main.zip
96
+ pipx install 7zon-cli
96
97
  ```
97
98
 
98
99
  **3. Terminalni qayta oching** va tekshiring:
@@ -115,7 +116,7 @@ winget install --id Python.Python.3.13 -e
115
116
 
116
117
  **2. PowerShell'ni yopib, qayta oching** va 7ZON'ni o'rnating:
117
118
  ```bash
118
- py -m pip install --user https://github.com/7zon-uz/7ZON-CLI/archive/refs/heads/main.zip
119
+ py -m pip install --user 7zon-cli
119
120
  ```
120
121
 
121
122
  **3. Tekshiring:**
@@ -137,7 +138,7 @@ py -m pip install --user https://github.com/7zon-uz/7ZON-CLI/archive/refs/heads/
137
138
  pkg update -y && pkg install -y python
138
139
  ```
139
140
  ```bash
140
- pip install https://github.com/7zon-uz/7ZON-CLI/archive/refs/heads/main.zip
141
+ pip install 7zon-cli
141
142
  ```
142
143
 
143
144
  Yoki tayyor skript bilan o'rnating:
@@ -164,6 +165,8 @@ curl -fsSL https://raw.githubusercontent.com/7zon-uz/7ZON-CLI/main/install-termu
164
165
  7zon config set-key
165
166
  ```
166
167
 
168
+ > 💡 Bu buyruq **terminalning o'zida** (PowerShell, Terminal, Termux) yoziladi, `Siz ›` chatining ichida emas. Agar 7ZON ochiq bo'lsa, kalit yo'qligida u o'zi so'raydi. Chat ichida istalgan vaqtda **`/key`** deb yozib kalitni almashtirish ham mumkin.
169
+
167
170
  Yoki muhit o'zgaruvchisi orqali bering:
168
171
 
169
172
  | Tizim | Buyruq |
@@ -220,6 +223,7 @@ Ruxsat berasizmi? (↑/↓ tanlash, Enter tasdiqlash)
220
223
  | `/compress` | Uzun suhbatni qisqa xulosaga aylantirish (bu avtomatik ham bajariladi) |
221
224
  | `/memory` | Eslab qolingan ma'lumotlar (`7ZON.md`) |
222
225
  | `/clear` | Suhbatni tozalash |
226
+ | `/key` | API kalitni kiritish yoki almashtirish (yashirin) |
223
227
  | `/yolo` | Oddiy amallar uchun ruxsat so'ramaslik |
224
228
  | `/exit` | Chiqish |
225
229
 
@@ -264,9 +268,9 @@ Ruxsat berasizmi? (↑/↓ tanlash, Enter tasdiqlash)
264
268
 
265
269
  | | Yangilash | O'chirish |
266
270
  |---|---|---|
267
- | pipx (macOS / Linux) | `pipx install --force https://github.com/7zon-uz/7ZON-CLI/archive/refs/heads/main.zip` | `pipx uninstall 7zon-cli` |
268
- | Windows | `py -m pip install --user --upgrade https://github.com/7zon-uz/7ZON-CLI/archive/refs/heads/main.zip` | `py -m pip uninstall 7zon-cli` |
269
- | Termux | `pip install --upgrade https://github.com/7zon-uz/7ZON-CLI/archive/refs/heads/main.zip` | `pip uninstall 7zon-cli` |
271
+ | pipx (macOS / Linux) | `pipx upgrade 7zon-cli` | `pipx uninstall 7zon-cli` |
272
+ | Windows | `py -m pip install --user --upgrade 7zon-cli` | `py -m pip uninstall 7zon-cli` |
273
+ | Termux | `pip install --upgrade 7zon-cli` | `pip uninstall 7zon-cli` |
270
274
 
271
275
  Sozlamalar `~/.config/7zon/` papkasida, ishchi fayllar esa `~/.7zon/` papkasida turadi. 7ZON'ni butunlay o'chirish uchun bu papkalarni ham o'chiring.
272
276
 
@@ -304,7 +308,7 @@ Xato topsangiz yoki taklifingiz bo'lsa, [Issue oching](https://github.com/7zon-u
304
308
  **7ZON CLI** is an AI agent for your terminal. Describe a task in plain words (Uzbek, English or Russian) and it runs commands, writes and edits files, searches your project, looks at images and PDFs, and fixes errors. It asks before every action using an arrow-key menu, and secrets are typed into a hidden prompt the AI never sees. It works on macOS, Linux, Windows (PowerShell) and Android (Termux), and needs only pure-Python dependencies.
305
309
 
306
310
  ```bash
307
- pipx install https://github.com/7zon-uz/7ZON-CLI/archive/refs/heads/main.zip # Windows: py -m pip install --user <same URL>
311
+ pipx install 7zon-cli # Windows: py -m pip install --user 7zon-cli
308
312
  7zon config set-key # free Gemini key: https://aistudio.google.com/apikey
309
313
  7zon config set lang en
310
314
  7zon # start the agent
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "7zon-cli"
7
- version = "0.2.2"
7
+ version = "0.2.4"
8
8
  description = "7ZON — terminalda ishlaydigan AI yordamchi: buyruq yozadi, xatolarni tuzatadi, tushuntiradi."
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -0,0 +1 @@
1
+ __version__ = "0.2.4"
@@ -298,6 +298,49 @@ def _headless(task: str, yolo: bool) -> None:
298
298
  _fail(str(e))
299
299
 
300
300
 
301
+ KEY_ENV = {"gemini": ("GEMINI_API_KEY", "GOOGLE_API_KEY"), "claude": ("ANTHROPIC_API_KEY",)}
302
+ KEY_URL = {"gemini": "https://aistudio.google.com/apikey", "claude": "https://console.anthropic.com"}
303
+
304
+
305
+ def _has_key(cfg: dict[str, Any]) -> bool:
306
+ name = cfg.get("provider", "gemini")
307
+ if any(os.environ.get(e) for e in KEY_ENV.get(name, ())):
308
+ return True
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 ""))
311
+
312
+
313
+ def _is_set_key_line(line: str) -> bool:
314
+ """Chat ichida yozilgan '7zon config set-key' yoki '/key' ni taniydi."""
315
+ words = line.strip().lower().split()
316
+ return words[:1] == ["/key"] or words[:3] == ["7zon", "config", "set-key"]
317
+
318
+
319
+ def _prompt_key(cfg: dict[str, Any], name: str | None = None) -> bool:
320
+ """Kalitni yashirin so'raydi va saqlaydi. Saqlansa True."""
321
+ name = name or cfg.get("provider", "gemini")
322
+ field = config.KEY_FIELDS[name]
323
+ console.print(f"[bold]{name.capitalize()} API kalit[/] kerak. Olish: [cyan]{KEY_URL[name]}[/]\n"
324
+ "[dim]Kalitni qo'ying (Ctrl+V yoki sichqonchaning o'ng tugmasi) va Enter bosing. "
325
+ "Kalit ekranda ochiq ko'rinmaydi, bu normal.[/]")
326
+ try:
327
+ key = config.clean_key(menu.read_secret(f"{name.capitalize()} API kalit: "))
328
+ except (EOFError, KeyboardInterrupt):
329
+ console.print()
330
+ return False
331
+ if not key:
332
+ console.print("[yellow]Kalit kiritilmadi.[/]")
333
+ return False
334
+ problem = config.key_problem(key)
335
+ if problem:
336
+ err.print(f"[bold red]Xato:[/] {problem} Qayta urinish: [cyan]/key[/]")
337
+ return False
338
+ config.set_value(field, key)
339
+ cfg[field] = key
340
+ console.print(f"[green]✓ Kalit saqlandi:[/] {config.config_path()}")
341
+ return True
342
+
343
+
301
344
  def _chat_session(yolo: bool = False) -> None:
302
345
  cfg = config.load()
303
346
  try:
@@ -306,6 +349,8 @@ def _chat_session(yolo: bool = False) -> None:
306
349
  _fail(str(e))
307
350
  banner.render(console, __version__, cfg, prov)
308
351
  banner.tips(console)
352
+ if not _has_key(cfg) and menu.is_interactive():
353
+ _prompt_key(cfg)
309
354
  agent, runner = _build_agent(cfg, yolo=yolo)
310
355
  if yolo:
311
356
  console.print("[yellow]⚡ YOLO rejimi: oddiy amallar so'ralmaydi (xavfli amallar baribir so'raladi).[/]")
@@ -327,9 +372,18 @@ def _chat_session(yolo: bool = False) -> None:
327
372
  continue
328
373
  if question.lower() in EXIT_WORDS or question.lower() in ("/exit", "/quit"):
329
374
  break
375
+ if _is_set_key_line(question):
376
+ # Foydalanuvchi buyruqni chat ichiga yozdi: kalitni shu yerning o'zida yashirin so'raymiz
377
+ which = "claude" if "claude" in question.lower() else None
378
+ if _prompt_key(cfg, which):
379
+ agent, runner = _build_agent(cfg, yolo=yolo)
380
+ continue
330
381
  if question.startswith("/"):
331
382
  _slash_command(question, agent, runner, thinking)
332
383
  continue
384
+ if not _has_key(cfg):
385
+ err.print("[bold red]Xato:[/] API kalit hali kiritilmagan. Shu yerga [cyan]/key[/] deb yozing.")
386
+ continue
333
387
  console.print(prefix)
334
388
  try:
335
389
  agent.send(question, runner, on_text, thinking)
@@ -346,6 +400,7 @@ SLASH_HELP = """[bold]Buyruqlar:[/]
346
400
  [cyan]/compress[/] uzun suhbatni qisqa xulosaga aylantirish
347
401
  [cyan]/memory[/] eslab qolingan faktlar va loyiha qoidalari (7ZON.md)
348
402
  [cyan]/undo[/] 7ZON qilgan oxirgi fayl o'zgarishini qaytarish
403
+ [cyan]/key[/] API kalitni kiritish yoki almashtirish (yashirin)
349
404
  [cyan]/yolo[/] ruxsat so'rashni yoqish/o'chirish (xavfli amallar baribir so'raladi)
350
405
  [cyan]/exit[/] chiqish"""
351
406
 
@@ -430,9 +485,10 @@ def config_set_key(
430
485
  name = provider or cfg["provider"]
431
486
  if name not in config.KEY_FIELDS:
432
487
  _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.")
488
+ key = config.clean_key(menu.read_secret(f"{name.capitalize()} API kalit (Ctrl+V yoki o'ng tugma bilan joylang, keyin Enter): "))
489
+ problem = config.key_problem(key)
490
+ if problem:
491
+ _fail(problem)
436
492
  config.set_value(config.KEY_FIELDS[name], key)
437
493
  console.print(f"[green]✓ Saqlandi:[/] {config.config_path()} (faqat sizga o'qish ruxsati bilan)")
438
494
 
@@ -446,10 +502,9 @@ def secret_add(name: str = typer.Argument(..., help="Masalan: INSTAGRAM_PASSWORD
446
502
  key = vault.normalize(name)
447
503
  except vault.SecretError as e:
448
504
  _fail(str(e))
449
- import getpass
450
505
 
451
506
  try:
452
- value = getpass.getpass(f"{key} (ekranda ko'rinmaydi): ")
507
+ value = menu.read_secret(f"{key} (ekranda ko'rinmaydi): ")
453
508
  except (KeyboardInterrupt, EOFError):
454
509
  console.print("\n[dim]Bekor qilindi.[/]")
455
510
  raise typer.Exit(130)
@@ -74,6 +74,32 @@ def set_value(key: str, value: str) -> None:
74
74
  save(data)
75
75
 
76
76
 
77
+ _INVISIBLE = {"\u200b", "\u200c", "\u200d", "\u2060", "\ufeff", "\xa0"}
78
+
79
+
80
+ def clean_key(value: str) -> str:
81
+ """Joylangan API kalitdan ortiqcha narsalarni olib tashlaydi.
82
+
83
+ Windows'da Ctrl+V ba'zan ko'rinmas belgi (\\x16) qoldiradi; odamlar kalitni qo'shtirnoq
84
+ yoki "GEMINI_API_KEY=" bilan birga joylashi ham mumkin. Bunday kalitni Google rad etadi.
85
+ """
86
+ key = "".join(ch for ch in value if ch.isprintable() and ch not in _INVISIBLE and not ch.isspace())
87
+ if "=" in key and key.split("=", 1)[0].isupper():
88
+ key = key.split("=", 1)[1] # GEMINI_API_KEY=... -> ...
89
+ return key.strip("\"'`")
90
+
91
+
92
+ def key_problem(key: str) -> str | None:
93
+ """Kalit yaroqsiz ko'rinsa, sababini qaytaradi."""
94
+ if not key:
95
+ return "Kalit bo'sh."
96
+ if not key.isascii():
97
+ return "Kalitda lotin harflari va raqamlardan boshqa belgilar bor. Kalitni qaytadan nusxalang."
98
+ if len(key) < 20:
99
+ return "Kalit juda qisqa. To'liq nusxalanganini tekshiring."
100
+ return None
101
+
102
+
77
103
  def mask(secret: str | None) -> str:
78
104
  if not secret:
79
105
  return "—"
@@ -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)
@@ -18,6 +18,7 @@ from contextlib import contextmanager
18
18
  from pathlib import Path
19
19
  from typing import Any
20
20
 
21
+ from zon7 import config
21
22
  from zon7.common import COMMAND_SCHEMA, AIError
22
23
 
23
24
  API_BASE = "https://generativelanguage.googleapis.com/v1beta/models"
@@ -33,7 +34,7 @@ FALLBACK_MODELS = (
33
34
  )
34
35
  TIMEOUT = 90 # soniya
35
36
  ENV_KEYS = ("GEMINI_API_KEY", "GOOGLE_API_KEY")
36
- KEY_HINT = "Kalitni https://aistudio.google.com/apikey dan oling va kiriting: 7zon config set-key"
37
+ KEY_HINT = "Kalitni https://aistudio.google.com/apikey dan oling va kiriting: 7zon config set-key (7ZON chatining ichida: /key)"
37
38
  BLOCK_REASONS = ("SAFETY", "PROHIBITED", "BLOCKLIST", "SPII")
38
39
 
39
40
 
@@ -90,7 +91,8 @@ def _api_key(cfg: dict[str, Any]) -> str:
90
91
  for name in ENV_KEYS:
91
92
  if os.environ.get(name):
92
93
  return os.environ[name]
93
- key = cfg.get("gemini_api_key")
94
+ # Eski versiyada ortiqcha belgilar bilan saqlangan kalitlar ham ishlasin
95
+ key = config.clean_key(cfg.get("gemini_api_key") or "")
94
96
  if not key:
95
97
  raise AIError(f"Gemini API kalit topilmadi. {KEY_HINT}")
96
98
  return key
@@ -121,6 +123,10 @@ def friendly_errors() -> Iterator[None]:
121
123
  text = f"{e.status} {e.message}"
122
124
  if e.code in (401, 403) or "API_KEY" in text or "API key" in text:
123
125
  raise AIError(f"Gemini API kalit noto'g'ri yoki ruxsat yo'q. {KEY_HINT}") from None
126
+ if e.code == 400 and "<html" in e.message.lower():
127
+ # Google sarlavhadagi kalitni o'qiy olmasa JSON emas, HTML qaytaradi
128
+ raise AIError("API kalit noto'g'ri formatda saqlangan (ortiqcha belgilar bor). "
129
+ "Chat ichida /key deb yozib, kalitni qaytadan kiriting.") from None
124
130
  if e.code == 404:
125
131
  raise AIError("Model topilmadi. Tekshiring: 7zon config show") from None
126
132
  if e.code == 429:
@@ -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
@@ -263,14 +262,14 @@ class ToolRunner:
263
262
  console: Console,
264
263
  ask: Callable[[str], str],
265
264
  cwd: Path | None = None,
266
- secret_input: Callable[[str], str] = getpass.getpass,
265
+ secret_input: Callable[[str], str] | None = None,
267
266
  load_saved_secrets: bool = True,
268
267
  headless: bool = False,
269
268
  ) -> None:
270
269
  self.headless = headless # -p rejimi: savol berib bo'lmaydi
271
270
  self.console = console
272
271
  self.ask = ask # oddiy qator kiritish (menyu terminal bo'lmaganda ishlatadi)
273
- self.secret_input = secret_input # yashirin kiritish: yozilgan belgilar ekranda ko'rinmaydi
272
+ self.secret_input = secret_input or menu.read_secret # yashirin kiritish: yozilgan belgilar ekranda ko'rinmaydi
274
273
  self.cwd = (cwd or Path.cwd()).resolve()
275
274
  self.auto_approve = False # "Barchasiga ruxsat" tanlangandan keyin xavfli bo'lmagan amallar so'ralmaydi
276
275
  # Maxfiy qiymatlar: faqat shu jarayon xotirasida va buyruqlar muhitida, AI'ga hech qachon bormaydi
@@ -1,7 +1,7 @@
1
1
  import pytest
2
2
  from typer.testing import CliRunner
3
3
 
4
- from zon7 import cli
4
+ from zon7 import cli, config
5
5
 
6
6
  runner = CliRunner()
7
7
 
@@ -149,6 +149,7 @@ class FakeAgent:
149
149
 
150
150
 
151
151
  def test_chat_one_turn(monkeypatch):
152
+ monkeypatch.setenv("GEMINI_API_KEY", "test-key")
152
153
  monkeypatch.setattr(cli.ai, "make_agent", lambda *a, **k: FakeAgent())
153
154
  result = runner.invoke(cli.app, ["chat"], input="salom\nexit\n")
154
155
  assert result.exit_code == 0
@@ -221,3 +222,76 @@ def test_headless_prompt(monkeypatch):
221
222
  assert agent.sent == ["papka yarat"] and "Javob" in result.output
222
223
  assert "████" not in result.output # logo chiqmaydi
223
224
  assert "Headless mode" in made["system"]
225
+
226
+
227
+ # ---------------------------------------------------------------- kalitni chat ichida kiritish
228
+
229
+ @pytest.mark.parametrize("line,expected", [
230
+ ("7zon config set-key", True),
231
+ ('7zon config set-key "abc"', True),
232
+ ("7ZON Config Set-Key --provider claude", True),
233
+ ("/key", True),
234
+ ("config set-key", False),
235
+ ("kalitni qanday olaman?", False),
236
+ ])
237
+ def test_is_set_key_line(line, expected):
238
+ assert cli._is_set_key_line(line) is expected
239
+
240
+
241
+ def test_has_key(monkeypatch):
242
+ for e in ("GEMINI_API_KEY", "GOOGLE_API_KEY"):
243
+ monkeypatch.delenv(e, raising=False)
244
+ assert cli._has_key({"provider": "gemini"}) is False
245
+ assert cli._has_key({"provider": "gemini", "gemini_api_key": "x"}) is True
246
+ monkeypatch.setenv("GEMINI_API_KEY", "y")
247
+ assert cli._has_key({"provider": "gemini"}) is True
248
+
249
+
250
+ def test_prompt_key_saves_hidden(monkeypatch):
251
+ import getpass
252
+
253
+ monkeypatch.setattr(cli.menu, "read_secret", lambda prompt="": " SECRET123_long_test_key_000 ")
254
+ cfg = {"provider": "gemini"}
255
+ assert cli._prompt_key(cfg) is True
256
+ assert cfg["gemini_api_key"] == "SECRET123_long_test_key_000"
257
+ assert config.load()["gemini_api_key"] == "SECRET123_long_test_key_000"
258
+
259
+
260
+ def test_prompt_key_empty(monkeypatch):
261
+ import getpass
262
+
263
+ monkeypatch.setattr(cli.menu, "read_secret", lambda prompt="": "")
264
+ cfg = {"provider": "gemini"}
265
+ assert cli._prompt_key(cfg) is False
266
+ assert "gemini_api_key" not in cfg
267
+
268
+
269
+ def test_chat_without_key_points_to_key_command(monkeypatch):
270
+ for e in ("GEMINI_API_KEY", "GOOGLE_API_KEY"):
271
+ monkeypatch.delenv(e, raising=False)
272
+ monkeypatch.setattr(cli.ai, "make_agent", lambda *a, **k: FakeAgent())
273
+ result = runner.invoke(cli.app, ["chat"], input="salom\nexit\n")
274
+ assert result.exit_code == 0
275
+ assert "/key" in result.output
276
+ assert "Javob" not in result.output
277
+
278
+
279
+ def test_set_key_typed_inside_chat(monkeypatch):
280
+ import getpass
281
+
282
+ for e in ("GEMINI_API_KEY", "GOOGLE_API_KEY"):
283
+ monkeypatch.delenv(e, raising=False)
284
+ monkeypatch.setattr(cli.menu, "read_secret", lambda prompt="": "NEWKEY_long_test_key_00000")
285
+ monkeypatch.setattr(cli.ai, "make_agent", lambda *a, **k: FakeAgent())
286
+ result = runner.invoke(cli.app, ["chat"], input="7zon config set-key\nsalom\nexit\n")
287
+ assert result.exit_code == 0
288
+ assert "Kalit saqlandi" in result.output
289
+ assert "Javob" in result.output
290
+ assert "NEWKEY_long_test_key_00000" not in result.output
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
@@ -49,3 +49,33 @@ def test_legacy_api_key_migrates():
49
49
  config.config_path().parent.mkdir(parents=True, exist_ok=True)
50
50
  config.config_path().write_text('{"api_key": "sk-ant-old"}')
51
51
  assert config.load()["anthropic_api_key"] == "sk-ant-old"
52
+
53
+
54
+ # ---------------------------------------------------------------- joylangan kalitni tozalash
55
+
56
+ import pytest # noqa: E402
57
+
58
+ from zon7 import config as _cfg # noqa: E402
59
+
60
+ GOOD = "AQ.Ab8Rtest_KEY-1234567890abcdef"
61
+
62
+
63
+ @pytest.mark.parametrize("raw", [
64
+ GOOD,
65
+ f" {GOOD} \r\n",
66
+ f'"{GOOD}"',
67
+ f"'{GOOD}'",
68
+ f"\x16{GOOD}", # Windows Ctrl+V qoldig'i
69
+ f"{GOOD}​", # ko'rinmas belgilar
70
+ f"GEMINI_API_KEY={GOOD}",
71
+ f'GEMINI_API_KEY="{GOOD}"',
72
+ ])
73
+ def test_clean_key(raw):
74
+ assert _cfg.clean_key(raw) == GOOD
75
+ assert _cfg.key_problem(_cfg.clean_key(raw)) is None
76
+
77
+
78
+ def test_key_problem():
79
+ assert _cfg.key_problem("") is not None
80
+ assert _cfg.key_problem("short") is not None
81
+ assert _cfg.key_problem("AIzaкалит1234567890abcdef") is not None
@@ -210,3 +210,12 @@ def test_compress_replaces_history(monkeypatch):
210
210
  assert agent.compress()
211
211
  assert len(agent.contents) == 2 and "Xulosa: papka yaratildi." in agent.contents[0]["parts"][0]["text"]
212
212
  assert agent.size() < 200
213
+
214
+
215
+ def test_html_400_means_bad_key():
216
+ from zon7.common import AIError
217
+ from zon7.providers import gemini
218
+
219
+ with pytest.raises(AIError, match="/key"):
220
+ with gemini.friendly_errors():
221
+ raise gemini.GeminiError(400, "", "<html><title>Error 400 (Bad Request)!!1</title></html> []")
@@ -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"])
@@ -1 +0,0 @@
1
- __version__ = "0.2.2"
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