7zon-cli 0.2.5__tar.gz → 0.2.6__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.5 → 7zon_cli-0.2.6}/PKG-INFO +1 -1
  2. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/pyproject.toml +1 -1
  3. 7zon_cli-0.2.6/src/zon7/__init__.py +1 -0
  4. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/src/zon7/cli.py +8 -0
  5. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/src/zon7/prompts.py +1 -1
  6. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/src/zon7/providers/gemini.py +41 -0
  7. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/src/zon7/tools.py +54 -0
  8. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/tests/test_gemini.py +31 -0
  9. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/tests/test_tools.py +34 -0
  10. 7zon_cli-0.2.5/src/zon7/__init__.py +0 -1
  11. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/.github/workflows/ci.yml +0 -0
  12. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/.github/workflows/publish.yml +0 -0
  13. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/.gitignore +0 -0
  14. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/LICENSE +0 -0
  15. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/README.md +0 -0
  16. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/install-termux.sh +0 -0
  17. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/src/zon7/__main__.py +0 -0
  18. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/src/zon7/ai.py +0 -0
  19. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/src/zon7/banner.py +0 -0
  20. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/src/zon7/common.py +0 -0
  21. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/src/zon7/config.py +0 -0
  22. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/src/zon7/context.py +0 -0
  23. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/src/zon7/instagram.py +0 -0
  24. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/src/zon7/memory.py +0 -0
  25. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/src/zon7/menu.py +0 -0
  26. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/src/zon7/providers/__init__.py +0 -0
  27. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/src/zon7/providers/claude.py +0 -0
  28. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/src/zon7/safety.py +0 -0
  29. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/src/zon7/secrets.py +0 -0
  30. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/src/zon7/shell.py +0 -0
  31. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/tests/test_cli.py +0 -0
  32. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/tests/test_config.py +0 -0
  33. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/tests/test_context.py +0 -0
  34. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/tests/test_instagram.py +0 -0
  35. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/tests/test_memory.py +0 -0
  36. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/tests/test_menu.py +0 -0
  37. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/tests/test_powershell_real.py +0 -0
  38. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/tests/test_safety.py +0 -0
  39. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/tests/test_secrets.py +0 -0
  40. {7zon_cli-0.2.5 → 7zon_cli-0.2.6}/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.5
3
+ Version: 0.2.6
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
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "7zon-cli"
7
- version = "0.2.5"
7
+ version = "0.2.6"
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.6"
@@ -269,6 +269,10 @@ def chat() -> None:
269
269
 
270
270
  def _build_agent(cfg: dict, headless: bool = False, yolo: bool = False) -> tuple[Any, Any]:
271
271
  runner = tools.ToolRunner(console, console.input, headless=headless)
272
+ if _gemini_key_available(cfg):
273
+ from zon7.providers import gemini as _gemini
274
+
275
+ runner.image_generator = lambda prompt, ratio: _gemini.generate_image(cfg, prompt, ratio)
272
276
  runner.auto_approve = yolo
273
277
  try:
274
278
  tools.ToolRunner.prepare_workspace()
@@ -310,6 +314,10 @@ def _has_key(cfg: dict[str, Any]) -> bool:
310
314
  return bool(config.clean_key(cfg.get(config.KEY_FIELDS.get(name, "")) or ""))
311
315
 
312
316
 
317
+ def _gemini_key_available(cfg: dict[str, Any]) -> bool:
318
+ return _has_key({**cfg, "provider": "gemini"})
319
+
320
+
313
321
  def _is_set_key_line(line: str) -> bool:
314
322
  """Chat ichida yozilgan '7zon config set-key' yoki '/key' ni taniydi."""
315
323
  words = line.strip().lower().split()
@@ -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. 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.
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. To make a new picture (logo, icon, banner, illustration, anything realistic, 3D or premium), use generate_image with a rich, specific prompt, then look at the result and improve it if needed; do not imitate such pictures with shapes drawn in Python, SVG or HTML. 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
 
@@ -385,3 +385,44 @@ class Agent:
385
385
  # Xato yoki Ctrl+C: tarixni so'rovdan oldingi holatga qaytaramiz
386
386
  del self.contents[start:]
387
387
  raise
388
+
389
+
390
+ # --------------------------------------------------------------------------- rasm yaratish
391
+
392
+ IMAGE_MODELS = ("gemini-3-pro-image", "gemini-3.1-flash-image", "gemini-2.5-flash-image")
393
+ BILLING_HINT = (
394
+ "Rasm yaratish Google'ning bepul tarifida yopiq (limit 0). Yoqish uchun: https://aistudio.google.com "
395
+ "→ Billing → loyihangizga to'lov kartasini ulang (har bir rasm pullik, narxi AI Studio'da ko'rsatiladi)."
396
+ )
397
+
398
+
399
+ def generate_image(cfg: dict[str, Any], prompt: str, aspect_ratio: str = "1:1") -> tuple[bytes, str, str]:
400
+ """Gemini rasm modeli bilan rasm yaratadi: (baytlar, mime, model). Eng sifatli modeldan boshlanadi."""
401
+ key = _api_key(cfg)
402
+ body = {
403
+ "contents": [{"role": "user", "parts": [{"text": prompt}]}],
404
+ "generationConfig": {"responseModalities": ["IMAGE", "TEXT"], "imageConfig": {"aspectRatio": aspect_ratio}},
405
+ }
406
+ quota_blocked = False
407
+ last: GeminiError | None = None
408
+ for model in IMAGE_MODELS:
409
+ try:
410
+ data = _http_post(f"{API_BASE}/{model}:generateContent", key, body)
411
+ except GeminiError as e:
412
+ last = e
413
+ if e.code == 429:
414
+ quota_blocked = True
415
+ continue
416
+ if e.code in (404, 500, 502, 503, 504):
417
+ continue
418
+ raise
419
+ for cand in data.get("candidates", []):
420
+ for part in (cand.get("content") or {}).get("parts", []):
421
+ inline = part.get("inlineData")
422
+ if inline and inline.get("data"):
423
+ return base64.b64decode(inline["data"]), inline.get("mimeType", "image/png"), model
424
+ reason = (data.get("candidates") or [{}])[0].get("finishReason", "") or "sabab noma'lum"
425
+ raise AIError(f"Model rasm qaytarmadi ({reason}). So'rovni boshqacha yozib ko'ring.")
426
+ if quota_blocked:
427
+ raise AIError(BILLING_HINT)
428
+ raise AIError(f"Rasm yaratib bo'lmadi: {last}")
@@ -24,6 +24,7 @@ from rich.syntax import Syntax
24
24
  from zon7 import instagram as ig
25
25
  from zon7 import memory, menu, safety, shell
26
26
  from zon7 import secrets as vault
27
+ from zon7.common import AIError
27
28
 
28
29
  MAX_OUTPUT_CHARS = 20_000
29
30
  MAX_READ_BYTES = 200_000
@@ -192,6 +193,28 @@ TOOL_SPECS: list[dict[str, Any]] = [
192
193
  "additionalProperties": False,
193
194
  },
194
195
  },
196
+ {
197
+ "name": "generate_image",
198
+ "description": (
199
+ "Create a new picture with an image-generation AI and save it: logos, icons, illustrations, banners, "
200
+ "photorealistic or 3D renders. Use it whenever the user wants a picture to be made (a logo, a "
201
+ "premium/3D/realistic image); never draw such pictures with code shapes. Write a detailed English "
202
+ "prompt: subject, style (e.g. photorealistic 3D render, PBR materials, studio lighting, soft shadows, "
203
+ "reflections), colours, composition, background, and the exact text to show in quotes. After saving, "
204
+ "look at the result (it is attached for you) and regenerate with a better prompt if it is not good."
205
+ ),
206
+ "parameters": {
207
+ "type": "object",
208
+ "properties": {
209
+ "prompt": {"type": "string", "description": "Detailed English description of the picture."},
210
+ "path": {"type": "string", "description": "Where to save, e.g. ~/Desktop/app/logo.png"},
211
+ "aspect_ratio": {"type": "string", "enum": ["1:1", "16:9", "9:16", "4:3", "3:4"],
212
+ "description": "1:1 for logos and icons."},
213
+ },
214
+ "required": ["prompt", "path", "aspect_ratio"],
215
+ "additionalProperties": False,
216
+ },
217
+ },
195
218
  {
196
219
  "name": "glob",
197
220
  "description": (
@@ -300,6 +323,8 @@ class ToolRunner:
300
323
  self.attachments: list[tuple[str, bytes, str]] = [] # (mime, baytlar, yo'l) — model ko'radigan fayllar
301
324
  self.instagram_http: Any = ig.default_http # testlarda almashtiriladi
302
325
  self.temp_upload: Any = ig.upload_temp
326
+ # (prompt, nisbat) -> (baytlar, mime, model); cli Gemini kaliti bilan ulaydi
327
+ self.image_generator: Callable[[str, str], tuple[bytes, str, str]] | None = None
303
328
 
304
329
  @staticmethod
305
330
  def prepare_workspace(home: Path | None = None) -> Path:
@@ -381,6 +406,7 @@ class ToolRunner:
381
406
  "list_directory": self.list_directory,
382
407
  "fetch_url": self.fetch_url,
383
408
  "download_file": self.download_file,
409
+ "generate_image": self.generate_image,
384
410
  "edit_file": self.edit_file,
385
411
  "request_secret": self.request_secret,
386
412
  "instagram": self.instagram,
@@ -574,6 +600,34 @@ class ToolRunner:
574
600
  self.console.print(f"[dim]📁 ko'rildi: {target}[/]")
575
601
  return {"path": str(target), "entries": entries}
576
602
 
603
+ def generate_image(self, prompt: str, path: str, aspect_ratio: str = "1:1") -> dict[str, Any]:
604
+ if self.image_generator is None:
605
+ return {"error": "Image generation needs a Gemini API key (7zon config set-key --provider gemini)."}
606
+ target = self._path(path)
607
+ mime_ext = {"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp"}
608
+ exists = target.exists()
609
+ self.console.print(f"[bold]🎨 Rasm yaratish:[/] {target}\n[dim]{prompt[:300]}[/]")
610
+ if not self._confirm("caution" if exists else "safe"):
611
+ return {"declined": True, "message": "The user declined image generation."}
612
+ try:
613
+ with self.console.status("[dim]Rasm chizilmoqda (20–60 soniya)...[/]", spinner="dots"):
614
+ data, mime, model = self.image_generator(prompt, aspect_ratio)
615
+ except AIError as e:
616
+ self.console.print(f"[red]✗ {e}[/]")
617
+ return {"error": str(e), "note": "Tell the user this reason plainly. Do not fake the picture with code shapes "
618
+ "and call it realistic; you may offer a simple code-drawn version only if the user wants it."}
619
+ ext = mime_ext.get(mime)
620
+ if ext and target.suffix.lower() not in mime_ext.values():
621
+ target = target.with_suffix(ext)
622
+ target.parent.mkdir(parents=True, exist_ok=True)
623
+ if target.exists():
624
+ self._checkpoint(target)
625
+ target.write_bytes(data)
626
+ self.attachments.append((mime, data, str(target))) # model natijani ko'rib baholaydi
627
+ self.console.print(f"[green]✓ saqlandi[/] [dim]{len(data) // 1024} KB[/]")
628
+ return {"saved": str(target), "bytes": len(data), "mime": mime,
629
+ "note": "The image is attached; check it matches the request before reporting."}
630
+
577
631
  def download_file(self, url: str, path: str) -> dict[str, Any]:
578
632
  url = url.strip()
579
633
  if not re.match(r"^https?://", url, re.IGNORECASE):
@@ -219,3 +219,34 @@ def test_html_400_means_bad_key():
219
219
  with pytest.raises(AIError, match="/key"):
220
220
  with gemini.friendly_errors():
221
221
  raise gemini.GeminiError(400, "", "<html><title>Error 400 (Bad Request)!!1</title></html> []")
222
+
223
+
224
+ def test_generate_image_falls_back_and_reports_billing(monkeypatch):
225
+ from zon7.common import AIError
226
+ from zon7.providers import gemini
227
+
228
+ tried = []
229
+
230
+ def fake_post(url, key, body, stream=False):
231
+ tried.append(url.rsplit("/", 1)[1])
232
+ raise gemini.GeminiError(429, "RESOURCE_EXHAUSTED", "quota")
233
+
234
+ monkeypatch.setattr(gemini, "_http_post", fake_post)
235
+ with pytest.raises(AIError, match="Billing"):
236
+ gemini.generate_image({"gemini_api_key": "k" * 30}, "logo")
237
+ assert len(tried) == len(gemini.IMAGE_MODELS)
238
+
239
+
240
+ def test_generate_image_returns_bytes(monkeypatch):
241
+ import base64
242
+
243
+ from zon7.providers import gemini
244
+
245
+ def fake_post(url, key, body, stream=False):
246
+ assert body["generationConfig"]["imageConfig"]["aspectRatio"] == "16:9"
247
+ return {"candidates": [{"content": {"parts": [{"text": "ok"}, {"inlineData": {
248
+ "mimeType": "image/png", "data": base64.b64encode(b"IMG").decode()}}]}}]}
249
+
250
+ monkeypatch.setattr(gemini, "_http_post", fake_post)
251
+ assert gemini.generate_image({"gemini_api_key": "k" * 30}, "logo", "16:9") == (b"IMG", "image/png",
252
+ gemini.IMAGE_MODELS[0])
@@ -399,3 +399,37 @@ def test_child_python_gets_utf8(tmp_path):
399
399
  r = make_runner(tmp_path, [])
400
400
  env = r._env()
401
401
  assert env["PYTHONIOENCODING"] == "utf-8" and env["PYTHONUTF8"] == "1"
402
+
403
+
404
+ # ---------------------------------------------------------------- generate_image
405
+
406
+ def test_generate_image_saves_and_attaches(tmp_path):
407
+ r = make_runner(tmp_path, ["y"])
408
+ calls = []
409
+ r.image_generator = lambda prompt, ratio: calls.append((prompt, ratio)) or (b"\x89PNG fake", "image/png", "m")
410
+ out = r("generate_image", {"prompt": "premium 3D logo", "path": "app/logo", "aspect_ratio": "1:1"})
411
+ saved = tmp_path / "app" / "logo.png"
412
+ assert out["saved"] == str(saved.resolve())
413
+ assert saved.read_bytes() == b"\x89PNG fake"
414
+ assert calls == [("premium 3D logo", "1:1")]
415
+ assert r.pop_attachments()[0][0] == "image/png"
416
+
417
+
418
+ def test_generate_image_billing_error_is_reported(tmp_path):
419
+ from zon7.common import AIError
420
+
421
+ r = make_runner(tmp_path, ["y"])
422
+
423
+ def blocked(prompt, ratio):
424
+ raise AIError("Rasm yaratish Google'ning bepul tarifida yopiq")
425
+
426
+ r.image_generator = blocked
427
+ out = r("generate_image", {"prompt": "x", "path": "logo.png", "aspect_ratio": "1:1"})
428
+ assert "bepul tarifida" in out["error"]
429
+ assert not (tmp_path / "logo.png").exists()
430
+
431
+
432
+ def test_generate_image_without_key(tmp_path):
433
+ r = make_runner(tmp_path, [])
434
+ out = r("generate_image", {"prompt": "x", "path": "logo.png", "aspect_ratio": "1:1"})
435
+ assert "Gemini API key" in out["error"]
@@ -1 +0,0 @@
1
- __version__ = "0.2.5"
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