7zon-cli 0.2.2__tar.gz → 0.2.3__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.3}/PKG-INFO +14 -10
  2. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/README.md +13 -9
  3. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/pyproject.toml +1 -1
  4. 7zon_cli-0.2.3/src/zon7/__init__.py +1 -0
  5. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/src/zon7/cli.py +60 -3
  6. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/src/zon7/config.py +26 -0
  7. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/src/zon7/providers/gemini.py +8 -2
  8. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/tests/test_cli.py +69 -1
  9. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/tests/test_config.py +30 -0
  10. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/tests/test_gemini.py +9 -0
  11. 7zon_cli-0.2.2/src/zon7/__init__.py +0 -1
  12. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/.github/workflows/ci.yml +0 -0
  13. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/.github/workflows/publish.yml +0 -0
  14. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/.gitignore +0 -0
  15. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/LICENSE +0 -0
  16. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/install-termux.sh +0 -0
  17. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/src/zon7/__main__.py +0 -0
  18. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/src/zon7/ai.py +0 -0
  19. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/src/zon7/banner.py +0 -0
  20. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/src/zon7/common.py +0 -0
  21. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/src/zon7/context.py +0 -0
  22. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/src/zon7/instagram.py +0 -0
  23. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/src/zon7/memory.py +0 -0
  24. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/src/zon7/menu.py +0 -0
  25. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/src/zon7/prompts.py +0 -0
  26. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/src/zon7/providers/__init__.py +0 -0
  27. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/src/zon7/providers/claude.py +0 -0
  28. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/src/zon7/safety.py +0 -0
  29. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/src/zon7/secrets.py +0 -0
  30. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/src/zon7/shell.py +0 -0
  31. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/src/zon7/tools.py +0 -0
  32. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/tests/test_context.py +0 -0
  33. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/tests/test_instagram.py +0 -0
  34. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/tests/test_memory.py +0 -0
  35. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/tests/test_menu.py +0 -0
  36. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/tests/test_powershell_real.py +0 -0
  37. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/tests/test_safety.py +0 -0
  38. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/tests/test_secrets.py +0 -0
  39. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/tests/test_shell.py +0 -0
  40. {7zon_cli-0.2.2 → 7zon_cli-0.2.3}/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.3
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.3"
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.3"
@@ -298,6 +298,50 @@ 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
+ return bool(cfg.get(config.KEY_FIELDS.get(name, "")))
310
+
311
+
312
+ def _is_set_key_line(line: str) -> bool:
313
+ """Chat ichida yozilgan '7zon config set-key' yoki '/key' ni taniydi."""
314
+ words = line.strip().lower().split()
315
+ return words[:1] == ["/key"] or words[:3] == ["7zon", "config", "set-key"]
316
+
317
+
318
+ def _prompt_key(cfg: dict[str, Any], name: str | None = None) -> bool:
319
+ """Kalitni yashirin so'raydi va saqlaydi. Saqlansa True."""
320
+ import getpass
321
+
322
+ name = name or cfg.get("provider", "gemini")
323
+ field = config.KEY_FIELDS[name]
324
+ console.print(f"[bold]{name.capitalize()} API kalit[/] kerak. Olish: [cyan]{KEY_URL[name]}[/]\n"
325
+ "[dim]Kalitni qo'ying (Ctrl+V yoki sichqonchaning o'ng tugmasi) va Enter bosing. "
326
+ "Yozganingiz ekranda ko'rinmaydi, bu normal.[/]")
327
+ try:
328
+ key = config.clean_key(getpass.getpass(f"{name.capitalize()} API kalit: "))
329
+ except (EOFError, KeyboardInterrupt):
330
+ console.print()
331
+ return False
332
+ if not key:
333
+ console.print("[yellow]Kalit kiritilmadi.[/]")
334
+ return False
335
+ problem = config.key_problem(key)
336
+ if problem:
337
+ err.print(f"[bold red]Xato:[/] {problem} Qayta urinish: [cyan]/key[/]")
338
+ return False
339
+ config.set_value(field, key)
340
+ cfg[field] = key
341
+ console.print(f"[green]✓ Kalit saqlandi:[/] {config.config_path()}")
342
+ return True
343
+
344
+
301
345
  def _chat_session(yolo: bool = False) -> None:
302
346
  cfg = config.load()
303
347
  try:
@@ -306,6 +350,8 @@ def _chat_session(yolo: bool = False) -> None:
306
350
  _fail(str(e))
307
351
  banner.render(console, __version__, cfg, prov)
308
352
  banner.tips(console)
353
+ if not _has_key(cfg) and menu.is_interactive():
354
+ _prompt_key(cfg)
309
355
  agent, runner = _build_agent(cfg, yolo=yolo)
310
356
  if yolo:
311
357
  console.print("[yellow]⚡ YOLO rejimi: oddiy amallar so'ralmaydi (xavfli amallar baribir so'raladi).[/]")
@@ -327,9 +373,18 @@ def _chat_session(yolo: bool = False) -> None:
327
373
  continue
328
374
  if question.lower() in EXIT_WORDS or question.lower() in ("/exit", "/quit"):
329
375
  break
376
+ if _is_set_key_line(question):
377
+ # Foydalanuvchi buyruqni chat ichiga yozdi: kalitni shu yerning o'zida yashirin so'raymiz
378
+ which = "claude" if "claude" in question.lower() else None
379
+ if _prompt_key(cfg, which):
380
+ agent, runner = _build_agent(cfg, yolo=yolo)
381
+ continue
330
382
  if question.startswith("/"):
331
383
  _slash_command(question, agent, runner, thinking)
332
384
  continue
385
+ if not _has_key(cfg):
386
+ err.print("[bold red]Xato:[/] API kalit hali kiritilmagan. Shu yerga [cyan]/key[/] deb yozing.")
387
+ continue
333
388
  console.print(prefix)
334
389
  try:
335
390
  agent.send(question, runner, on_text, thinking)
@@ -346,6 +401,7 @@ SLASH_HELP = """[bold]Buyruqlar:[/]
346
401
  [cyan]/compress[/] uzun suhbatni qisqa xulosaga aylantirish
347
402
  [cyan]/memory[/] eslab qolingan faktlar va loyiha qoidalari (7ZON.md)
348
403
  [cyan]/undo[/] 7ZON qilgan oxirgi fayl o'zgarishini qaytarish
404
+ [cyan]/key[/] API kalitni kiritish yoki almashtirish (yashirin)
349
405
  [cyan]/yolo[/] ruxsat so'rashni yoqish/o'chirish (xavfli amallar baribir so'raladi)
350
406
  [cyan]/exit[/] chiqish"""
351
407
 
@@ -430,9 +486,10 @@ def config_set_key(
430
486
  name = provider or cfg["provider"]
431
487
  if name not in config.KEY_FIELDS:
432
488
  _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.")
489
+ key = config.clean_key(typer.prompt(f"{name.capitalize()} API kalit", hide_input=True))
490
+ problem = config.key_problem(key)
491
+ if problem:
492
+ _fail(problem)
436
493
  config.set_value(config.KEY_FIELDS[name], key)
437
494
  console.print(f"[green]✓ Saqlandi:[/] {config.config_path()} (faqat sizga o'qish ruxsati bilan)")
438
495
 
@@ -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 "—"
@@ -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:
@@ -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,70 @@ 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(getpass, "getpass", 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(getpass, "getpass", 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(getpass, "getpass", 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"
@@ -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> []")
@@ -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
File without changes
File without changes
File without changes