7zon-cli 0.2.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
zon7/context.py ADDED
@@ -0,0 +1,91 @@
1
+ """AI to'g'ri buyruq yozishi uchun muhit haqida qisqa ma'lumot yig'adi."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import platform
7
+ from pathlib import Path
8
+
9
+ # Loyiha turini aniqlash uchun belgi fayllar (faqat nomlari yuboriladi, ichi emas)
10
+ PROJECT_MARKERS = (
11
+ "package.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb",
12
+ "pyproject.toml", "requirements.txt", "Pipfile", "poetry.lock",
13
+ "go.mod", "Cargo.toml", "pom.xml", "build.gradle", "composer.json",
14
+ "Gemfile", "Dockerfile", "docker-compose.yml", "compose.yaml",
15
+ "Makefile", ".git",
16
+ )
17
+
18
+
19
+ TERMUX_NOTE = (
20
+ "Termux notes: install packages with `pkg install -y NAME` (no sudo, no brew, no apt-get with sudo); "
21
+ "open links with `termux-open-url URL`; phone storage is at ~/storage/shared after `termux-setup-storage` "
22
+ "(Downloads: ~/storage/downloads, camera: ~/storage/dcim); clipboard via termux-clipboard-get/set and other "
23
+ "termux-* commands need `pkg install termux-api` plus the Termux:API app."
24
+ )
25
+
26
+
27
+ WINDOWS_NOTE = (
28
+ "Windows notes: commands run in PowerShell. Write PowerShell syntax, not bash: join commands with `;` "
29
+ "(Windows PowerShell 5.1 has no `&&`), use $env:NAME for environment variables, New-Item -ItemType Directory, "
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`."
32
+ )
33
+
34
+
35
+ def is_termux() -> bool:
36
+ """Android'dagi Termux ilovasi ichida ishlayaptimi."""
37
+ return bool(os.environ.get("TERMUX_VERSION")) or "com.termux" in os.environ.get("PREFIX", "")
38
+
39
+
40
+ def shell_path() -> str:
41
+ """Buyruqlarni bajarish uchun shell. Android'da /bin/sh yo'q, shuning uchun qidirib topamiz."""
42
+ import shutil
43
+
44
+ candidates = [os.environ.get("SHELL", ""), "/bin/sh", shutil.which("bash") or "", shutil.which("sh") or "",
45
+ os.path.join(os.environ.get("PREFIX", ""), "bin", "sh"), "/system/bin/sh"]
46
+ for path in candidates:
47
+ if path and os.path.isfile(path) and os.access(path, os.X_OK):
48
+ return path
49
+ return "/bin/sh"
50
+
51
+
52
+ def detect_shell() -> str:
53
+ if platform.system() == "Windows":
54
+ import shutil
55
+
56
+ # 7ZON buyruqlarni aynan shu shell'da bajaradi (zon7.shell)
57
+ return "powershell" if (shutil.which("pwsh") or shutil.which("powershell")) else "cmd"
58
+ return Path(os.environ.get("SHELL", "/bin/sh")).name
59
+
60
+
61
+ def detect_os() -> str:
62
+ if is_termux():
63
+ return "Android (Termux)"
64
+ system = platform.system()
65
+ if system == "Darwin":
66
+ return f"macOS {platform.mac_ver()[0]}".strip()
67
+ if system == "Linux":
68
+ try:
69
+ info = platform.freedesktop_os_release()
70
+ return info.get("PRETTY_NAME", "Linux")
71
+ except OSError:
72
+ return "Linux"
73
+ return f"{system} {platform.release()}"
74
+
75
+
76
+ def project_markers(cwd: Path) -> list[str]:
77
+ return [m for m in PROJECT_MARKERS if (cwd / m).exists()]
78
+
79
+
80
+ def describe(cwd: Path | None = None) -> str:
81
+ cwd = cwd or Path.cwd()
82
+ markers = project_markers(cwd)
83
+ lines = [
84
+ f"OS: {detect_os()}",
85
+ *([TERMUX_NOTE] if is_termux() else []),
86
+ *([WINDOWS_NOTE] if platform.system() == "Windows" else []),
87
+ f"Shell: {detect_shell()}",
88
+ f"Current directory: {cwd.name or cwd}",
89
+ f"Project files here: {', '.join(markers) if markers else 'none detected'}",
90
+ ]
91
+ return "\n".join(lines)
zon7/instagram.py ADDED
@@ -0,0 +1,224 @@
1
+ """Instagram rasmiy API (Instagram API with Instagram Login) bilan ishlash.
2
+
3
+ Talablar: Instagram Professional (Business yoki Creator) akkaunt va Meta dasturchilar panelidan
4
+ olingan access token ("Instagram > API setup with Instagram business login > Generate token").
5
+ Token 60 kun amal qiladi va refresh_access_token bilan uzaytiriladi.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import mimetypes
12
+ import os
13
+ import platform
14
+ import subprocess
15
+ import tempfile
16
+ import time
17
+ import urllib.error
18
+ import urllib.parse
19
+ import urllib.request
20
+ import uuid
21
+ from collections.abc import Callable
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ API_VERSION = "v27.0"
26
+ GRAPH = f"https://graph.instagram.com/{API_VERSION}"
27
+ TOKEN_SECRET = "INSTAGRAM_ACCESS_TOKEN"
28
+ # Kompyuterdagi faylni API'ga berish uchun vaqtinchalik ochiq havola kerak (1 soatdan keyin o'chadi)
29
+ TEMP_HOST = "https://litterbox.catbox.moe/resources/internals/api.php"
30
+ TIMEOUT = 60
31
+
32
+ PROFILE_FIELDS = "user_id,username,name,account_type,followers_count,follows_count,media_count"
33
+ MEDIA_FIELDS = "id,caption,media_type,timestamp,permalink,like_count,comments_count"
34
+ DEFAULT_METRICS = "views,reach,likes,comments,saved,shares,total_interactions"
35
+
36
+
37
+ class InstagramError(Exception):
38
+ pass
39
+
40
+
41
+ Http = Callable[[str, str, dict[str, str] | None, bytes | None, dict[str, str] | None], dict[str, Any]]
42
+
43
+
44
+ def default_http(method: str, url: str, params: dict[str, str] | None = None,
45
+ body: bytes | None = None, headers: dict[str, str] | None = None) -> dict[str, Any]:
46
+ if params:
47
+ encoded = urllib.parse.urlencode(params)
48
+ if method == "GET":
49
+ url = f"{url}?{encoded}"
50
+ elif body is None:
51
+ body = encoded.encode()
52
+ headers = {**(headers or {}), "Content-Type": "application/x-www-form-urlencoded"}
53
+ req = urllib.request.Request(url, data=body, method=method, headers={"User-Agent": "7zon-cli", **(headers or {})})
54
+ try:
55
+ with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
56
+ raw = resp.read().decode("utf-8", "replace")
57
+ except urllib.error.HTTPError as e:
58
+ raw = e.read().decode("utf-8", "replace")
59
+ try:
60
+ err = json.loads(raw).get("error", {})
61
+ raise InstagramError(f"Instagram API xatosi ({e.code}): {err.get('message', raw[:300])}") from None
62
+ except json.JSONDecodeError:
63
+ raise InstagramError(f"HTTP {e.code}: {raw[:300]}") from None
64
+ except (urllib.error.URLError, TimeoutError) as e:
65
+ raise InstagramError(f"Ulanib bo'lmadi: {getattr(e, 'reason', e)}") from None
66
+ try:
67
+ return json.loads(raw)
68
+ except json.JSONDecodeError:
69
+ return {"text": raw.strip()}
70
+
71
+
72
+ class Instagram:
73
+ def __init__(self, token: str, http: Http = default_http) -> None:
74
+ self.token = token
75
+ self.http = http
76
+ self._user_id: str | None = None
77
+
78
+ def _get(self, path: str, **params: str) -> dict[str, Any]:
79
+ return self.http("GET", f"{GRAPH}/{path}", {**params, "access_token": self.token}, None, None)
80
+
81
+ def _post(self, path: str, **params: str) -> dict[str, Any]:
82
+ return self.http("POST", f"{GRAPH}/{path}", {**params, "access_token": self.token}, None, None)
83
+
84
+ # ------------------------------------------------------------------ o'qish
85
+
86
+ def profile(self) -> dict[str, Any]:
87
+ data = self._get("me", fields=PROFILE_FIELDS)
88
+ self._user_id = str(data.get("user_id") or data.get("id") or "")
89
+ return data
90
+
91
+ def user_id(self) -> str:
92
+ if not self._user_id:
93
+ self.profile()
94
+ if not self._user_id:
95
+ raise InstagramError("Akkaunt ID sini olib bo'lmadi.")
96
+ return self._user_id
97
+
98
+ def media(self, limit: int = 10) -> dict[str, Any]:
99
+ return self._get(f"{self.user_id()}/media", fields=MEDIA_FIELDS, limit=str(limit))
100
+
101
+ def insights(self, media_id: str, metrics: str = "") -> dict[str, Any]:
102
+ return self._get(f"{media_id}/insights", metric=metrics or DEFAULT_METRICS)
103
+
104
+ def comments(self, media_id: str) -> dict[str, Any]:
105
+ return self._get(f"{media_id}/comments", fields="id,text,username,timestamp")
106
+
107
+ def publishing_limit(self) -> dict[str, Any]:
108
+ return self._get(f"{self.user_id()}/content_publishing_limit", fields="quota_usage,config")
109
+
110
+ # ------------------------------------------------------------------ yozish
111
+
112
+ def reply(self, comment_id: str, message: str) -> dict[str, Any]:
113
+ return self._post(f"{comment_id}/replies", message=message)
114
+
115
+ def publish(self, kind: str, media_url: str, caption: str = "",
116
+ wait: Callable[[float], None] = time.sleep, max_wait: int = 300) -> dict[str, Any]:
117
+ """kind: image | reel | story_image | story_video."""
118
+ params: dict[str, str] = {}
119
+ if kind == "image":
120
+ params["image_url"] = media_url
121
+ elif kind == "reel":
122
+ params.update(media_type="REELS", video_url=media_url)
123
+ elif kind == "story_image":
124
+ params.update(media_type="STORIES", image_url=media_url)
125
+ elif kind == "story_video":
126
+ params.update(media_type="STORIES", video_url=media_url)
127
+ else:
128
+ raise InstagramError(f"Noma'lum turi: {kind}")
129
+ if caption and not kind.startswith("story"):
130
+ params["caption"] = caption
131
+ container = self._post(f"{self.user_id()}/media", **params)
132
+ cid = container.get("id")
133
+ if not cid:
134
+ raise InstagramError(f"Konteyner yaratilmadi: {container}")
135
+ # Video qayta ishlanguncha kutamiz (hujjat: 5 daqiqagacha)
136
+ waited = 0
137
+ while True:
138
+ status = self._get(cid, fields="status_code").get("status_code", "FINISHED")
139
+ if status == "FINISHED":
140
+ break
141
+ if status in ("ERROR", "EXPIRED"):
142
+ raise InstagramError(f"Media qayta ishlanmadi: {status}")
143
+ if waited >= max_wait:
144
+ raise InstagramError("Media 5 daqiqada tayyor bo'lmadi.")
145
+ wait(5)
146
+ waited += 5
147
+ published = self._post(f"{self.user_id()}/media_publish", creation_id=cid)
148
+ media_id = published.get("id")
149
+ if not media_id:
150
+ raise InstagramError(f"Joylab bo'lmadi: {published}")
151
+ link = self._get(media_id, fields="permalink").get("permalink", "")
152
+ return {"media_id": media_id, "permalink": link}
153
+
154
+ def refresh_token(self) -> str:
155
+ data = self.http("GET", "https://graph.instagram.com/refresh_access_token",
156
+ {"grant_type": "ig_refresh_token", "access_token": self.token}, None, None)
157
+ new = data.get("access_token")
158
+ if not new:
159
+ raise InstagramError(f"Token yangilanmadi: {data}")
160
+ self.token = new
161
+ return new
162
+
163
+
164
+ # ---------------------------------------------------------------------- fayllar
165
+
166
+ def ensure_jpeg(path: Path) -> Path:
167
+ """Instagram rasmlar uchun faqat JPEG qabul qiladi. Kerak bo'lsa macOS sips bilan aylantiradi."""
168
+ if path.suffix.lower() in (".jpg", ".jpeg"):
169
+ return path
170
+ out = Path(tempfile.mkdtemp(prefix="7zon-ig-")) / (path.stem + ".jpg")
171
+ if platform.system() == "Darwin":
172
+ proc = subprocess.run(["sips", "-s", "format", "jpeg", str(path), "--out", str(out)],
173
+ capture_output=True, text=True)
174
+ if proc.returncode == 0 and out.exists():
175
+ return out
176
+ try:
177
+ from PIL import Image # ixtiyoriy
178
+
179
+ Image.open(path).convert("RGB").save(out, "JPEG", quality=92)
180
+ return out
181
+ except Exception:
182
+ raise InstagramError("Rasm JPEG formatida bo'lishi kerak (.jpg). Aylantirib bo'lmadi.") from None
183
+
184
+
185
+ def upload_temp(path: Path, http_post: Callable[[str, bytes, str], str] | None = None) -> str:
186
+ """Faylni 1 soatlik vaqtinchalik ochiq havolaga yuklaydi va URL qaytaradi."""
187
+ boundary = uuid.uuid4().hex
188
+ ctype = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
189
+ parts = [
190
+ f"--{boundary}\r\nContent-Disposition: form-data; name=\"reqtype\"\r\n\r\nfileupload\r\n".encode(),
191
+ f"--{boundary}\r\nContent-Disposition: form-data; name=\"time\"\r\n\r\n1h\r\n".encode(),
192
+ (f"--{boundary}\r\nContent-Disposition: form-data; name=\"fileToUpload\"; filename=\"{path.name}\"\r\n"
193
+ f"Content-Type: {ctype}\r\n\r\n").encode() + path.read_bytes() + b"\r\n",
194
+ f"--{boundary}--\r\n".encode(),
195
+ ]
196
+ body = b"".join(parts)
197
+ content_type = f"multipart/form-data; boundary={boundary}"
198
+ if http_post is None:
199
+ req = urllib.request.Request(TEMP_HOST, data=body, method="POST",
200
+ headers={"Content-Type": content_type, "User-Agent": "7zon-cli"})
201
+ try:
202
+ with urllib.request.urlopen(req, timeout=120) as resp:
203
+ url = resp.read().decode().strip()
204
+ except (urllib.error.URLError, TimeoutError) as e:
205
+ raise InstagramError(f"Faylni vaqtinchalik yuklab bo'lmadi: {getattr(e, 'reason', e)}") from None
206
+ else:
207
+ url = http_post(TEMP_HOST, body, content_type).strip()
208
+ if not url.startswith("https://"):
209
+ raise InstagramError(f"Vaqtinchalik havola olinmadi: {url[:200]}")
210
+ return url
211
+
212
+
213
+ def resolve_source(source: str, kind: str, cwd: Path) -> tuple[str, Path | None]:
214
+ """URL bo'lsa o'zi, aks holda mahalliy fayl yo'li (keyin vaqtinchalik yuklanadi)."""
215
+ source = source.strip()
216
+ if source.startswith(("http://", "https://")):
217
+ return source, None
218
+ path = Path(os.path.expanduser(source))
219
+ path = (path if path.is_absolute() else cwd / path).resolve()
220
+ if not path.is_file():
221
+ raise InstagramError(f"Fayl topilmadi: {path}")
222
+ if kind in ("image", "story_image"):
223
+ path = ensure_jpeg(path)
224
+ return "", path
zon7/memory.py ADDED
@@ -0,0 +1,66 @@
1
+ """Xotira fayllari: 7ZON.md (global va loyiha), shuningdek AGENTS.md / CLAUDE.md / GEMINI.md.
2
+
3
+ Global: ~/.7zon/7ZON.md — foydalanuvchi haqidagi doimiy faktlar
4
+ Loyiha: <loyiha>/7ZON.md — shu loyiha qoidalari (git ildizi yoki joriy papka)
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from datetime import date
10
+ from pathlib import Path
11
+
12
+ MEMORY_FILE = "7ZON.md"
13
+ COMPAT_FILES = ("AGENTS.md", "CLAUDE.md", "GEMINI.md")
14
+ SECTION = "## 7ZON xotirasi"
15
+ MAX_CHARS = 20_000
16
+
17
+
18
+ def global_file(home: Path | None = None) -> Path:
19
+ return (home or Path.home()) / ".7zon" / MEMORY_FILE
20
+
21
+
22
+ def project_root(cwd: Path) -> Path:
23
+ """Git ildizi (bo'lsa), aks holda joriy papka."""
24
+ for folder in (cwd, *cwd.parents):
25
+ if (folder / ".git").exists():
26
+ return folder
27
+ return cwd
28
+
29
+
30
+ def project_file(cwd: Path) -> Path:
31
+ return project_root(cwd) / MEMORY_FILE
32
+
33
+
34
+ def load(cwd: Path, home: Path | None = None) -> str:
35
+ """Tizim ko'rsatmasiga qo'shiladigan xotira matni."""
36
+ parts: list[str] = []
37
+ candidates = [global_file(home)]
38
+ root = project_root(cwd)
39
+ candidates += [root / MEMORY_FILE] + [root / name for name in COMPAT_FILES]
40
+ if cwd != root:
41
+ candidates.append(cwd / MEMORY_FILE)
42
+ seen: set[Path] = set()
43
+ for path in candidates:
44
+ if path in seen or not path.is_file():
45
+ continue
46
+ seen.add(path)
47
+ try:
48
+ text = path.read_text(encoding="utf-8", errors="replace").strip()
49
+ except OSError:
50
+ continue
51
+ if text:
52
+ parts.append(f"<memory file=\"{path}\">\n{text[:MAX_CHARS]}\n</memory>")
53
+ return "\n\n".join(parts)
54
+
55
+
56
+ def save(fact: str, scope: str, cwd: Path, home: Path | None = None) -> Path:
57
+ path = global_file(home) if scope == "global" else project_file(cwd)
58
+ path.parent.mkdir(parents=True, exist_ok=True)
59
+ text = path.read_text(encoding="utf-8") if path.exists() else ""
60
+ if SECTION not in text:
61
+ text = (text.rstrip() + "\n\n" if text.strip() else "# 7ZON\n\n") + SECTION + "\n"
62
+ line = f"- {fact.strip()} _({date.today().isoformat()})_\n"
63
+ if not text.endswith("\n"):
64
+ text += "\n"
65
+ path.write_text(text + line, encoding="utf-8")
66
+ return path
zon7/menu.py ADDED
@@ -0,0 +1,162 @@
1
+ """Strelkalar (↑/↓) bilan tanlanadigan menyu, qo'shimcha kutubxonalarsiz.
2
+
3
+ Terminal bo'lmasa (pipe, testlar), oddiy qator kiritishga o'tadi:
4
+ raqam (1, 2, 3) yoki qisqa so'z (y, a, n, ha) qabul qilinadi.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import sys
11
+ from collections.abc import Callable, Sequence
12
+
13
+ ORANGE = "\x1b[1;38;2;255;172;60m"
14
+ DIM = "\x1b[2m"
15
+ RESET = "\x1b[0m"
16
+ HIDE_CURSOR, SHOW_CURSOR = "\x1b[?25l", "\x1b[?25h"
17
+
18
+ Option = tuple[str, set[str]] # (matn, qatorli rejimdagi qisqa javoblar)
19
+
20
+
21
+ def is_interactive() -> bool:
22
+ if os.environ.get("ZON7_NO_MENU"):
23
+ return False
24
+ try:
25
+ return sys.stdin.isatty() and sys.stdout.isatty()
26
+ except (AttributeError, ValueError):
27
+ return False
28
+
29
+
30
+ def _read_key() -> str:
31
+ """Bitta tugmani o'qiydi: 'up', 'down', 'enter', 'interrupt', raqam yoki boshqa belgi."""
32
+ if os.name == "nt":
33
+ import msvcrt
34
+
35
+ ch = msvcrt.getwch()
36
+ if ch in ("\x00", "\xe0"):
37
+ return {"H": "up", "P": "down"}.get(msvcrt.getwch(), "")
38
+ return _map_char(ch)
39
+
40
+ import select
41
+ import termios
42
+ import tty
43
+
44
+ fd = sys.stdin.fileno()
45
+ old = termios.tcgetattr(fd)
46
+ try:
47
+ tty.setraw(fd)
48
+ ch = os.read(fd, 1).decode(errors="ignore")
49
+ if ch == "\x1b":
50
+ # Strelkalar ESC [ A / ESC [ B ko'rinishida keladi
51
+ seq = ""
52
+ while len(seq) < 2 and select.select([fd], [], [], 0.05)[0]:
53
+ seq += os.read(fd, 1).decode(errors="ignore")
54
+ return {"[A": "up", "OA": "up", "[B": "down", "OB": "down"}.get(seq, "")
55
+ return _map_char(ch)
56
+ finally:
57
+ termios.tcsetattr(fd, termios.TCSADRAIN, old)
58
+
59
+
60
+ def _map_char(ch: str) -> str:
61
+ if ch in ("\r", "\n"):
62
+ return "enter"
63
+ if ch in ("\x03", "\x04"): # Ctrl+C, Ctrl+D
64
+ return "interrupt"
65
+ if ch in ("k", "w"):
66
+ return "up"
67
+ if ch in ("j", "s"):
68
+ return "down"
69
+ return ch
70
+
71
+
72
+ _ansi_ready = False
73
+
74
+
75
+ def enable_windows_ansi() -> None:
76
+ """Windows konsolida ANSI ranglar va kursor buyruqlarini yoqadi (Windows 10+)."""
77
+ global _ansi_ready
78
+ if _ansi_ready or os.name != "nt":
79
+ return
80
+ _ansi_ready = True
81
+ try:
82
+ import ctypes
83
+
84
+ kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
85
+ handle = kernel32.GetStdHandle(-11) # STD_OUTPUT_HANDLE
86
+ mode = ctypes.c_uint32()
87
+ if kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
88
+ kernel32.SetConsoleMode(handle, mode.value | 0x0004) # ENABLE_VIRTUAL_TERMINAL_PROCESSING
89
+ except Exception:
90
+ pass
91
+
92
+
93
+ def select_arrows(title: str, labels: Sequence[str], default: int = 0, danger: bool = False) -> int:
94
+ """Strelkali menyu. Tanlangan variant indeksini qaytaradi."""
95
+ enable_windows_ansi()
96
+ out = sys.stdout
97
+ n = len(labels)
98
+ idx = default
99
+ accent = "\x1b[1;31m" if danger else ORANGE
100
+
101
+ def draw(first: bool) -> None:
102
+ if not first:
103
+ out.write(f"\x1b[{n}A")
104
+ for i, label in enumerate(labels):
105
+ out.write("\x1b[2K\r")
106
+ if i == idx:
107
+ out.write(f" {accent}❯ {label}{RESET}\n")
108
+ else:
109
+ out.write(f" {DIM}{label}{RESET}\n")
110
+ out.flush()
111
+
112
+ out.write(f"\x1b[1m{title}{RESET} {DIM}(↑/↓ tanlash, Enter tasdiqlash){RESET}\n{HIDE_CURSOR}")
113
+ draw(True)
114
+ try:
115
+ while True:
116
+ key = _read_key()
117
+ if key == "interrupt":
118
+ raise KeyboardInterrupt
119
+ if key == "enter":
120
+ break
121
+ if key == "up":
122
+ idx = (idx - 1) % n
123
+ elif key == "down":
124
+ idx = (idx + 1) % n
125
+ elif key.isdigit() and 1 <= int(key) <= n:
126
+ idx = int(key) - 1
127
+ draw(False)
128
+ break
129
+ else:
130
+ continue
131
+ draw(False)
132
+ finally:
133
+ out.write(SHOW_CURSOR)
134
+ out.flush()
135
+ # Menyuni yig'ib, faqat tanlangan javobni qoldiramiz
136
+ out.write(f"\x1b[{n}A\x1b[J {accent}✓ {labels[idx]}{RESET}\n")
137
+ out.flush()
138
+ return idx
139
+
140
+
141
+ def choose(
142
+ title: str,
143
+ options: Sequence[Option],
144
+ default: int,
145
+ ask: Callable[[str], str],
146
+ danger: bool = False,
147
+ ) -> int:
148
+ """Variant tanlatadi. Terminalda strelkali menyu, aks holda qator kiritish.
149
+
150
+ Qatorli rejimda: bo'sh javob = default, noma'lum javob = oxirgi variant (rad etish).
151
+ """
152
+ labels = [label for label, _ in options]
153
+ if is_interactive():
154
+ return select_arrows(title, labels, default, danger)
155
+ numbered = " / ".join(f"{i + 1}. {label}" for i, label in enumerate(labels))
156
+ answer = ask(f"{title} ({numbered}): ").strip().lower()
157
+ if not answer:
158
+ return default
159
+ for i, (_, aliases) in enumerate(options):
160
+ if answer == str(i + 1) or answer in aliases:
161
+ return i
162
+ return len(options) - 1
zon7/prompts.py ADDED
@@ -0,0 +1,85 @@
1
+ """Tizim ko'rsatmalari (system prompts)."""
2
+
3
+ LANG_NAMES = {"uz": "Uzbek (Latin script)", "en": "English", "ru": "Russian"}
4
+
5
+ IDENTITY = """Identity: you are the 7ZON CLI assistant, made by the 7ZON team, a startup from Uzbekistan building tools for developers. Only when someone asks who you are or who made you (never as an opener in other replies), say you are the 7ZON CLI assistant created by the 7ZON team (in Uzbek: "Men 7ZON jamoasi tomonidan yaratilgan 7ZON CLI yordamchisiman"). Do not name or mention the AI company or model behind the product (such as Google, Gemini, Anthropic, Claude, OpenAI); if asked which model powers you, say that 7ZON does not share details of its underlying technology and offer to help with their task."""
6
+
7
+
8
+ def _lang(lang: str) -> str:
9
+ return LANG_NAMES.get(lang, LANG_NAMES["uz"])
10
+
11
+
12
+ def ask_system(lang: str) -> str:
13
+ return IDENTITY + "\n\n" + f"""You are 7ZON, an assistant that turns a developer's request into a single shell command for their terminal.
14
+
15
+ Write one command (or a short one-liner joined with && or pipes) that runs as-is in the user's shell and OS, described in the environment block. Prefer standard, widely installed tools, and the project's own tooling when the project files show it (npm vs pnpm, pip vs poetry, and so on). When the request is ambiguous, pick the most common interpretation and say so in the explanation.
16
+
17
+ Rate the risk honestly: "safe" for read-only or easily undone commands, "caution" for commands that modify files, install or remove packages, or need sudo, "danger" for commands that can destroy data or the system. If the request cannot be done in a shell, return an empty command and explain why.
18
+
19
+ Write the explanation in {_lang(lang)}: one or two short sentences, plain words."""
20
+
21
+
22
+ def fix_system(lang: str) -> str:
23
+ return IDENTITY + "\n\n" + f"""You are 7ZON, a terminal assistant that helps developers fix errors.
24
+
25
+ You get a command and its output. Answer in {_lang(lang)}, in Markdown, short and practical:
26
+
27
+ 1. **Sabab / Cause**: what went wrong, in one or two sentences.
28
+ 2. **Yechim / Fix**: the exact commands or code change to fix it, in fenced code blocks.
29
+ 3. If several causes are likely, list the most likely first.
30
+
31
+ If the output shows no error, say so briefly. Do not repeat the whole log back."""
32
+
33
+
34
+ def explain_system(lang: str) -> str:
35
+ return IDENTITY + "\n\n" + f"""You are 7ZON, a terminal assistant. Explain the given shell command in {_lang(lang)}, in Markdown.
36
+
37
+ Break it into its parts (program, flags, arguments, pipes) and say what each does, then what the whole command does. Point out anything risky. Keep it short."""
38
+
39
+
40
+ def chat_system(lang: str) -> str:
41
+ return IDENTITY + "\n\n" + f"""You are 7ZON, an agent for software developers that works in their terminal and can act on their computer. Answer in {_lang(lang)} unless the user writes in another language, then answer in theirs.
42
+
43
+ You have tools: run_command (shell), read_file, write_file, edit_file (change part of a file), list_directory, glob (find files by name), grep (search inside files), view_file (look at images and PDFs), save_memory (remember lasting facts), fetch_url (read a web page or API), request_secret (hidden password/token prompt) and instagram (official Instagram API).
44
+
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
+
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.
48
+
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
+
51
+ Passwords and secrets: when a task needs a password, passphrase, API token, 2FA/SMS code or any other secret, call request_secret. The user types it in a hidden prompt; you never see it and refer to it only as $NAME in commands and scripts (scripts read it from the environment). Never ask the user to type a secret in the chat, never print or echo a secret, never write its value into files (write code that reads the environment variable instead), and never put it in a URL. If the user pastes a secret into the chat anyway, do not use it; tell them in one sentence to change it because it was shared in a chat, then call request_secret.
52
+
53
+ Start from zero: assume nothing is installed or set up. If a task needs a tool that is missing (`command -v NAME` fails), install it yourself and continue: on Android (Termux) with `pkg install -y NAME`, on macOS with Homebrew (`brew install gh`; if brew itself is missing, install it with its official script using interactive=true), on Linux with the system package manager (apt-get/dnf/pacman, via sudo with interactive=true), on Windows with winget. Then do the setup it needs (sign-in, git config) and finish the original task.
54
+
55
+ Passwords typed in the terminal: any command that asks for a password, passphrase or token itself (sudo, logins, `ssh-keygen`, `git push` asking for credentials, Homebrew's installer) must be run with interactive=true. Then the program asks the user directly in a hidden prompt (the characters do not show on screen), and the password goes only to that program, never to you. Before such a command, tell the user in one short sentence: if a password is asked, type it there; it will not be visible and it is not sent to 7ZON.
56
+
57
+ Signing in: like other coding agents, you sign the user in through the service's official browser login, never with a password in chat. First check whether they are already signed in (`gh auth status`, `gcloud auth list`, `vercel whoami`, `npm whoami`). If not, or if they ask you to log in or switch accounts, run the official login command with interactive=true, for example `gh auth login --web --git-protocol https` (add `--hostname github.com`), `gh auth switch --user NAME`, `gcloud auth login`, `vercel login`, `firebase login`, `npm login`. Tell the user in one short sentence that a browser window or one-time code will appear and they should approve it there. After it finishes, verify with the status command and continue the original task.
58
+
59
+ Any service, not only GitHub. You do the work yourself in the terminal. Never stop at "there is no CLI for that", and do not send the user to a website to do it themselves.
60
+
61
+ Instagram: always use the instagram tool (official API), not unofficial libraries. "Instagramga kir" means: call instagram with action=profile. If the token is missing, walk the user through getting it step by step (the result lists the steps): first check their account is Professional, open https://developers.facebook.com/apps for them, tell them exactly which buttons to press, then call request_secret INSTAGRAM_ACCESS_TOKEN with remember=true and call profile again. Only when profile returns a username, say "✅ Instagram akkauntiga kirildi (@username). Endi nima qilamiz?". Then do what they ask: posts and Reels (publish), stories (publish with story_image or story_video), stats (profile, media, insights), comments and replies. For a post from their computer pass the local file path as source. The official API cannot change the bio, name, username or profile photo: say so plainly and suggest doing it in the app. The token lasts 60 days; if an API error says the token expired, ask them to generate a new one.
62
+
63
+ Signing in to other services:
64
+ 1. If the service has an official CLI (AWS `aws`, Google Cloud `gcloud`, Azure `az`, Vercel, Netlify, Firebase, Heroku, Fly.io `flyctl`, Supabase, Cloudflare `wrangler`, Railway, DigitalOcean `doctl`, Stripe, Docker `docker login`, npm, Expo `eas`...), install it if missing and use its own login with interactive=true.
65
+ 2. Otherwise (Facebook, LinkedIn, X/Twitter, TikTok, a Telegram user account, any website), sign in from the terminal with the user's own account:
66
+ a. If you do not know the username, email or phone, ask for it in one short line and wait for the reply.
67
+ b. Collect the password with request_secret (remember=true when they want to stay signed in).
68
+ c. Log in with a well-known client library or a headless-browser script (for example Playwright for websites) running in the 7ZON workspace, reading the password from its environment variable. Save the session in the workspace so later tasks do not need the password again; next time, reuse the saved session first.
69
+ d. If the service asks for a 2FA, SMS or email code or a security challenge, collect the code with request_secret and finish the login.
70
+ e. The first time, mention in one sentence, together with the next step (not as a separate reply), that logins from outside the official app can trigger the service's security checks.
71
+ f. Only after the tool output proves the login worked (for example the script printed the account name it fetched after logging in, with exit code 0), reply in this style: "✅ <Service> akkauntiga kirildi (@username). Endi nima qilamiz?" and wait for the task. If it failed, tell the user exactly what the service said, in their language, and what you will try next.
72
+ 3. Then do whatever the user asks with that session: post a photo or video, add a story, change the bio, name or username, send or read messages, follow, view stats, delete a post, and so on. Ask in chat for missing inputs (image path, caption text), do the action, check that it worked, and report briefly.
73
+ Open a web page only when the user asks for it, or when the service refuses terminal sign-in (then say why). Never try to get past CAPTCHAs or anyone else's account protection, and only use accounts that belong to the user.
74
+
75
+ 7ZON workspace for helper scripts: ~/.7zon. Create a Python environment once with `python3 -m venv ~/.7zon/venv` and install packages with `~/.7zon/venv/bin/pip install -q PACKAGE`; run scripts with `~/.7zon/venv/bin/python`; keep scripts in ~/.7zon/scripts and login sessions in ~/.7zon/sessions (`chmod 700` that folder). Never write passwords or tokens into files: scripts read them from environment variables.
76
+
77
+ Use ~ or absolute paths for places like the Desktop (~/Desktop). On macOS the Desktop may be named "Desktop" even when the system language is not English. Never run interactive commands that wait for input (use flags like -y), long-running servers, or commands that need sudo unless the user asks. If the user declines a command, do not retry it; ask what they prefer.
78
+
79
+ Keep going until the task is done. In one turn, chain every step yourself: install, then write the script, then run it, then check the result, then report. Only end your turn when (a) the task is finished and verified, (b) you need something only the user can give (a username, a choice, a file), and then end with a clear question, or (c) you are truly blocked. A warning or a note is never a reason to stop: say it in one sentence and continue with the next tool call in the same reply.
80
+
81
+ Honesty about results: never say something worked unless the tool output shows it. Read every tool result; a non-zero exit code, a traceback, or words like "error", "failed", "out of date", "challenge", "checkpoint" mean it did not work. Scripts you write must not swallow errors: let them exit with a non-zero code and print the error. After a failure, try a sensible fix once or twice (upgrade the package, adjust the script); if it still fails, stop and explain plainly what blocks it and what the user can do. Do not repeat the same failing command.
82
+
83
+ Use interactive=true only when the command itself waits for the user's keyboard or opens a browser login (official CLI logins, sudo, Homebrew's installer). Scripts that read secrets from environment variables run with interactive=false.
84
+
85
+ When you are done, reply briefly: what you did and where. For plain questions, answer in Markdown with fenced code blocks. Be concise: the user is in the middle of work."""
@@ -0,0 +1 @@
1
+ """AI provayderlari."""