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/tools.py ADDED
@@ -0,0 +1,855 @@
1
+ """Agent asboblari: buyruq bajarish, fayl o'qish/yozish, papkani ko'rish.
2
+
3
+ Har bir o'zgartiruvchi amal (buyruq, fayl yozish) foydalanuvchi tasdig'idan keyin bajariladi.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import difflib
9
+ import getpass
10
+ import html
11
+ import os
12
+ import re
13
+ import subprocess
14
+ import sys
15
+ import urllib.error
16
+ import urllib.request
17
+ from collections.abc import Callable
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from rich.console import Console
22
+ from rich.panel import Panel
23
+ from rich.syntax import Syntax
24
+
25
+ from zon7 import instagram as ig
26
+ from zon7 import memory, menu, safety, shell
27
+ from zon7 import secrets as vault
28
+
29
+ MAX_OUTPUT_CHARS = 20_000
30
+ MAX_READ_BYTES = 200_000
31
+ MAX_FETCH_BYTES = 2_000_000
32
+ SKIP_DIRS = {".git", "node_modules", ".venv", "venv", "__pycache__", ".mypy_cache", ".pytest_cache",
33
+ "dist", "build", ".next", ".nuxt", "target", ".gradle", ".idea", ".tox", "Pods", ".dart_tool"}
34
+ MAX_RESULTS = 200
35
+ MAX_GREP_FILE = 2_000_000
36
+ MAX_ATTACH_BYTES = 15_000_000
37
+ VIEWABLE = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif",
38
+ ".webp": "image/webp", ".pdf": "application/pdf"}
39
+ FETCH_TIMEOUT = 20
40
+ CWD_MARKER = "__7ZON_CWD__"
41
+ # Rang va kursor kodlari: ekranda axlat bo'lib ko'rinmasin va AI'ga bormasin
42
+ ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(\x07|\x1b\\)")
43
+
44
+ TOOL_SPECS: list[dict[str, Any]] = [
45
+ {
46
+ "name": "run_command",
47
+ "description": (
48
+ "Run a shell command on the user's computer in the current working directory and return its "
49
+ "exit code and output. Use it to create folders, run scripts, install packages, use git, and so on. "
50
+ "The working directory persists between calls, so `cd` works. The user confirms each command."
51
+ ),
52
+ "parameters": {
53
+ "type": "object",
54
+ "properties": {
55
+ "command": {"type": "string", "description": "The exact shell command to run."},
56
+ "reason": {"type": "string", "description": "One short sentence, in the user's language, on what this does."},
57
+ "interactive": {
58
+ "type": "boolean",
59
+ "description": (
60
+ "true for commands the user must interact with: sign-in flows that open the browser or show a "
61
+ "one-time code (gh auth login --web, gcloud auth login, vercel login, npm login), prompts, "
62
+ "or editors. The command gets the user's terminal and its output is not captured. "
63
+ "false for everything else."
64
+ ),
65
+ },
66
+ },
67
+ "required": ["command", "reason", "interactive"],
68
+ "additionalProperties": False,
69
+ },
70
+ },
71
+ {
72
+ "name": "read_file",
73
+ "description": "Read a text file and return its contents. Paths may be relative to the working directory or start with ~.",
74
+ "parameters": {
75
+ "type": "object",
76
+ "properties": {"path": {"type": "string"}},
77
+ "required": ["path"],
78
+ "additionalProperties": False,
79
+ },
80
+ },
81
+ {
82
+ "name": "write_file",
83
+ "description": (
84
+ "Create or overwrite a text file with the given full contents. Parent folders are created. "
85
+ "The user confirms before the file is written."
86
+ ),
87
+ "parameters": {
88
+ "type": "object",
89
+ "properties": {
90
+ "path": {"type": "string"},
91
+ "content": {"type": "string", "description": "The complete new file contents."},
92
+ },
93
+ "required": ["path", "content"],
94
+ "additionalProperties": False,
95
+ },
96
+ },
97
+ {
98
+ "name": "request_secret",
99
+ "description": (
100
+ "Ask the user to type a password, passphrase, API token, 2FA code or other secret in a hidden prompt. "
101
+ "You never see the value. It becomes an environment variable for run_command: refer to it as $NAME "
102
+ "(for example in a script read os.environ[\"NAME\"], or `printf %s \"$NAME\" | docker login -u USER --password-stdin`). "
103
+ "Any occurrence of the value in tool output is replaced with ****. If a secret with this name is already "
104
+ "available, it is reused without asking."
105
+ ),
106
+ "parameters": {
107
+ "type": "object",
108
+ "properties": {
109
+ "name": {"type": "string", "description": "UPPER_SNAKE_CASE variable name, e.g. INSTAGRAM_PASSWORD."},
110
+ "prompt": {"type": "string", "description": "Short label shown to the user, in their language, e.g. \"Instagram paroli\"."},
111
+ "remember": {"type": "boolean", "description": "true to save it in the system keychain for later sessions (tokens, passwords); false for one-time codes."},
112
+ },
113
+ "required": ["name", "prompt", "remember"],
114
+ "additionalProperties": False,
115
+ },
116
+ },
117
+ {
118
+ "name": "edit_file",
119
+ "description": (
120
+ "Change part of an existing text file: replace old_text (copied exactly from the file, unique in it) "
121
+ "with new_text. Read the file first. The user sees the diff and confirms."
122
+ ),
123
+ "parameters": {
124
+ "type": "object",
125
+ "properties": {
126
+ "path": {"type": "string"},
127
+ "old_text": {"type": "string", "description": "Exact text to replace; must appear exactly once."},
128
+ "new_text": {"type": "string"},
129
+ },
130
+ "required": ["path", "old_text", "new_text"],
131
+ "additionalProperties": False,
132
+ },
133
+ },
134
+ {
135
+ "name": "instagram",
136
+ "description": (
137
+ "Work with the user's Instagram professional account through Instagram's official API. Actions: "
138
+ "profile (username, followers, media count); media (recent posts with ids, likes, comments); "
139
+ "insights (target_id=media id, text=optional comma-separated metrics); comments (target_id=media id); "
140
+ "reply (target_id=comment id, text=reply); publish (kind=image|reel|story_image|story_video, "
141
+ "source=local file path or public URL, caption); publishing_limit; refresh_token (extend the token 60 days). "
142
+ "Needs the secret INSTAGRAM_ACCESS_TOKEN; if it is missing the result explains how to get it. "
143
+ "Use empty strings for parameters an action does not need."
144
+ ),
145
+ "parameters": {
146
+ "type": "object",
147
+ "properties": {
148
+ "action": {"type": "string", "enum": [
149
+ "profile", "media", "insights", "comments", "reply", "publish", "publishing_limit", "refresh_token",
150
+ ]},
151
+ "kind": {"type": "string", "enum": ["", "image", "reel", "story_image", "story_video"]},
152
+ "source": {"type": "string"},
153
+ "caption": {"type": "string"},
154
+ "target_id": {"type": "string"},
155
+ "text": {"type": "string"},
156
+ },
157
+ "required": ["action", "kind", "source", "caption", "target_id", "text"],
158
+ "additionalProperties": False,
159
+ },
160
+ },
161
+ {
162
+ "name": "fetch_url",
163
+ "description": (
164
+ "Download a public web page or HTTP API (GET) and return its text. HTML is converted to plain text. "
165
+ "Use it for documentation, public APIs such as https://api.github.com/..., or checking a site."
166
+ ),
167
+ "parameters": {
168
+ "type": "object",
169
+ "properties": {"url": {"type": "string", "description": "Full http(s) URL."}},
170
+ "required": ["url"],
171
+ "additionalProperties": False,
172
+ },
173
+ },
174
+ {
175
+ "name": "glob",
176
+ "description": (
177
+ "Find files by name pattern, newest first, e.g. \"**/*.py\", \"src/**/*.tsx\", \"*.md\". "
178
+ "Skips .git, node_modules, virtualenvs, caches and build folders."
179
+ ),
180
+ "parameters": {
181
+ "type": "object",
182
+ "properties": {
183
+ "pattern": {"type": "string"},
184
+ "path": {"type": "string", "description": "Folder to search in; \".\" for the working directory."},
185
+ },
186
+ "required": ["pattern", "path"],
187
+ "additionalProperties": False,
188
+ },
189
+ },
190
+ {
191
+ "name": "grep",
192
+ "description": (
193
+ "Search file contents with a regular expression and return matching lines as file:line: text. "
194
+ "Use it to find where something is defined or used. Skips binary files and the same folders as glob."
195
+ ),
196
+ "parameters": {
197
+ "type": "object",
198
+ "properties": {
199
+ "pattern": {"type": "string", "description": "Regular expression (Python syntax)."},
200
+ "path": {"type": "string", "description": "Folder or file; \".\" for the working directory."},
201
+ "file_glob": {"type": "string", "description": "Only files matching this, e.g. \"*.py\"; empty for all."},
202
+ "ignore_case": {"type": "boolean"},
203
+ },
204
+ "required": ["pattern", "path", "file_glob", "ignore_case"],
205
+ "additionalProperties": False,
206
+ },
207
+ },
208
+ {
209
+ "name": "save_memory",
210
+ "description": (
211
+ "Remember a lasting fact or preference for future sessions (for example the user's name, preferred "
212
+ "language or tools, project conventions). scope=global for facts about the user, project for this "
213
+ "project's rules. Save only when the user asks you to remember something or states a clear lasting preference."
214
+ ),
215
+ "parameters": {
216
+ "type": "object",
217
+ "properties": {
218
+ "fact": {"type": "string", "description": "One short sentence."},
219
+ "scope": {"type": "string", "enum": ["global", "project"]},
220
+ },
221
+ "required": ["fact", "scope"],
222
+ "additionalProperties": False,
223
+ },
224
+ },
225
+ {
226
+ "name": "view_file",
227
+ "description": (
228
+ "Look at an image (png, jpg, gif, webp) or a PDF so you can see it: screenshots, designs, photos, "
229
+ "scanned documents, error screenshots. The file is attached to the tool result for you to read."
230
+ ),
231
+ "parameters": {
232
+ "type": "object",
233
+ "properties": {"path": {"type": "string"}},
234
+ "required": ["path"],
235
+ "additionalProperties": False,
236
+ },
237
+ },
238
+ {
239
+ "name": "list_directory",
240
+ "description": "List files and folders in a directory (default: the working directory).",
241
+ "parameters": {
242
+ "type": "object",
243
+ "properties": {"path": {"type": "string", "description": "Directory path; use \".\" for the working directory."}},
244
+ "required": ["path"],
245
+ "additionalProperties": False,
246
+ },
247
+ },
248
+ ]
249
+
250
+
251
+ def _trim(text: str) -> str:
252
+ if len(text) <= MAX_OUTPUT_CHARS:
253
+ return text
254
+ head, tail = text[: MAX_OUTPUT_CHARS // 4], text[-(MAX_OUTPUT_CHARS * 3 // 4):]
255
+ return f"{head}\n[... {len(text) - len(head) - len(tail)} chars omitted ...]\n{tail}"
256
+
257
+
258
+ class ToolRunner:
259
+ """Asboblarni bajaradi va foydalanuvchidan ruxsat so'raydi."""
260
+
261
+ def __init__(
262
+ self,
263
+ console: Console,
264
+ ask: Callable[[str], str],
265
+ cwd: Path | None = None,
266
+ secret_input: Callable[[str], str] = getpass.getpass,
267
+ load_saved_secrets: bool = True,
268
+ headless: bool = False,
269
+ ) -> None:
270
+ self.headless = headless # -p rejimi: savol berib bo'lmaydi
271
+ self.console = console
272
+ self.ask = ask # oddiy qator kiritish (menyu terminal bo'lmaganda ishlatadi)
273
+ self.secret_input = secret_input # yashirin kiritish: yozilgan belgilar ekranda ko'rinmaydi
274
+ self.cwd = (cwd or Path.cwd()).resolve()
275
+ self.auto_approve = False # "Barchasiga ruxsat" tanlangandan keyin xavfli bo'lmagan amallar so'ralmaydi
276
+ # Maxfiy qiymatlar: faqat shu jarayon xotirasida va buyruqlar muhitida, AI'ga hech qachon bormaydi
277
+ self.secrets: dict[str, str] = vault.load_all() if load_saved_secrets else {}
278
+ self.checkpoints: list[tuple[Path, bytes | None]] = [] # /undo uchun: (fayl, oldingi holati yoki None)
279
+ self.attachments: list[tuple[str, bytes, str]] = [] # (mime, baytlar, yo'l) — model ko'radigan fayllar
280
+ self.instagram_http: Any = ig.default_http # testlarda almashtiriladi
281
+ self.temp_upload: Any = ig.upload_temp
282
+
283
+ @staticmethod
284
+ def prepare_workspace(home: Path | None = None) -> Path:
285
+ """~/.7zon: yordamchi skriptlar va login sessiyalari uchun (sessiyalar faqat egasiga ochiq)."""
286
+ root = (home or Path.home()) / ".7zon"
287
+ for sub in ("scripts", "sessions"):
288
+ (root / sub).mkdir(parents=True, exist_ok=True)
289
+ try:
290
+ os.chmod(root, 0o700)
291
+ os.chmod(root / "sessions", 0o700)
292
+ except OSError:
293
+ pass
294
+ return root
295
+
296
+ def _env(self) -> dict[str, str]:
297
+ env = dict(os.environ)
298
+ env.update(self.secrets)
299
+ return env
300
+
301
+ def redact(self, text: str) -> str:
302
+ for value in sorted(self.secrets.values(), key=len, reverse=True):
303
+ if len(value) >= 3:
304
+ text = text.replace(value, "****")
305
+ return text
306
+
307
+ def _redact_obj(self, obj: Any) -> Any:
308
+ if isinstance(obj, str):
309
+ return self.redact(obj)
310
+ if isinstance(obj, dict):
311
+ return {k: self._redact_obj(v) for k, v in obj.items()}
312
+ if isinstance(obj, list):
313
+ return [self._redact_obj(v) for v in obj]
314
+ return obj
315
+
316
+ # ------------------------------------------------------------------ helpers
317
+
318
+ def _path(self, raw: str) -> Path:
319
+ p = Path(os.path.expanduser(raw or "."))
320
+ return (p if p.is_absolute() else self.cwd / p).resolve()
321
+
322
+ def _confirm(self, level: str, allow_always: bool = True) -> bool:
323
+ if self.headless:
324
+ # Odam yo'q: faqat --yolo bilan, faqat xavfsiz/ehtiyotli amallar bajariladi
325
+ ok = self.auto_approve and allow_always and level != "danger"
326
+ if not ok:
327
+ self.console.print("[yellow]⏭ Headless rejim: bu amal ruxsatsiz bajarilmadi.[/]")
328
+ return ok
329
+ if level == "danger":
330
+ # Xavfli amal: "doim ruxsat" yo'q, standart tanlov — rad etish
331
+ choice = menu.choose(
332
+ "XAVFLI amal. Bajarilsinmi?",
333
+ [("Ruxsat (xavfli!)", {"ha", "yes"}), ("Ruxsat emas", {"n", "no", "yo'q"})],
334
+ default=1, ask=self.ask, danger=True,
335
+ )
336
+ return choice == 0
337
+ if self.auto_approve and allow_always:
338
+ return True
339
+ options = [("Ruxsat", {"y", "yes", "ha", "h"})]
340
+ if allow_always:
341
+ options.append(("Barchasiga ruxsat, boshqa so'rama", {"a", "always", "doim"}))
342
+ options.append(("Ruxsat emas", {"n", "no", "yo'q"}))
343
+ choice = menu.choose("Ruxsat berasizmi?", options, default=0, ask=self.ask)
344
+ label = options[choice][0]
345
+ if label.startswith("Barchasiga"):
346
+ self.auto_approve = True
347
+ return True
348
+ return label == "Ruxsat"
349
+
350
+ # ------------------------------------------------------------------ dispatch
351
+
352
+ def __call__(self, name: str, args: dict[str, Any]) -> dict[str, Any]:
353
+ handler = {
354
+ "run_command": self.run_command,
355
+ "read_file": self.read_file,
356
+ "write_file": self.write_file,
357
+ "list_directory": self.list_directory,
358
+ "fetch_url": self.fetch_url,
359
+ "edit_file": self.edit_file,
360
+ "request_secret": self.request_secret,
361
+ "instagram": self.instagram,
362
+ "glob": self.glob,
363
+ "grep": self.grep,
364
+ "save_memory": self.save_memory,
365
+ "view_file": self.view_file,
366
+ }.get(name)
367
+ if handler is None:
368
+ return {"error": f"Unknown tool: {name}"}
369
+ try:
370
+ result = handler(**args)
371
+ except TypeError as e:
372
+ result = {"error": f"Bad arguments for {name}: {e}"}
373
+ except OSError as e:
374
+ result = {"error": f"{type(e).__name__}: {e}"}
375
+ # AI'ga qaytadigan hamma narsadan maxfiy qiymatlarni olib tashlaymiz
376
+ return self._redact_obj(result)
377
+
378
+ # ------------------------------------------------------------------ tools
379
+
380
+ def run_command(self, command: str, reason: str = "", interactive: bool = False) -> dict[str, Any]:
381
+ command = command.strip()
382
+ if not command:
383
+ return {"error": "Empty command."}
384
+ level, reasons = safety.assess(command)
385
+ color = {"safe": "green", "caution": "yellow", "danger": "red"}[level]
386
+ self.console.print(Panel(
387
+ Syntax(command, "bash", theme="ansi_dark", word_wrap=True),
388
+ title="[bold]⚡ Buyruq[/]", subtitle=reason or None, border_style=color,
389
+ ))
390
+ if reasons:
391
+ self.console.print(f"[{color}]⚠ {'; '.join(reasons)}[/]")
392
+ if interactive:
393
+ self.console.print(
394
+ "[cyan]🔐 Brauzer ochilishi yoki parol so'ralishi mumkin. Parolni shu terminalga yozasiz: "
395
+ "u ekranda ko'rinmaydi va faqat shu dasturga boradi, 7ZON'ga yuborilmaydi.[/]"
396
+ )
397
+ if not self._confirm(level):
398
+ return {"declined": True, "message": "The user declined to run this command. Ask what they want instead."}
399
+ if interactive:
400
+ self.console.print("[dim]↳ Interaktiv rejim: brauzerda yoki shu yerda davom eting.[/]")
401
+ code, output = self._execute_interactive(command)
402
+ status = "[green]✓[/]" if code == 0 else f"[red]✗ kod {code}[/]"
403
+ self.console.print(f"{status} [dim]{self.cwd}[/]")
404
+ return {"exit_code": code, "output": _trim(output), "cwd": str(self.cwd), "interactive": True}
405
+ code, output = self._execute(command)
406
+ status = "[green]✓[/]" if code == 0 else f"[red]✗ kod {code}[/]"
407
+ self.console.print(f"{status} [dim]{self.cwd}[/]")
408
+ return {"exit_code": code, "output": _trim(output), "cwd": str(self.cwd)}
409
+
410
+ def _execute_interactive(self, command: str) -> tuple[int, str]:
411
+ """Buyruqni foydalanuvchi terminaliga ulaydi (parol, savollar, brauzer) va chiqishini ham yozib oladi.
412
+
413
+ POSIX'da psevdo-terminal (pty) ishlatiladi: dastur haqiqiy terminalni ko'radi, yashirin parol
414
+ so'rovlari ishlaydi, chiqish esa AI uchun ham yig'iladi (maxfiy qiymatlar yashirilgan holda).
415
+ """
416
+ if shell.is_windows():
417
+ # Windows'da pty yo'q: dastur konsolga to'g'ridan-to'g'ri ulanadi, chiqish yig'ilmaydi
418
+ code = subprocess.run(shell.argv(command, interactive=True), cwd=self.cwd, env=self._env()).returncode
419
+ return code, "(Windows: the output was shown to the user in the console but not captured)"
420
+
421
+ import fcntl
422
+ import pty
423
+ import select
424
+ import termios
425
+ import tty
426
+
427
+ args = shell.argv(command, interactive=True)
428
+ env = self._env()
429
+ pid, master = pty.fork()
430
+ if pid == 0: # bola jarayon
431
+ try:
432
+ os.chdir(self.cwd)
433
+ os.execve(args[0], args, env)
434
+ finally:
435
+ os._exit(127)
436
+
437
+ def _fileno(stream: Any) -> int:
438
+ try:
439
+ return stream.fileno()
440
+ except (AttributeError, ValueError, OSError):
441
+ return -1
442
+
443
+ stdin_fd = _fileno(sys.stdin)
444
+ is_tty = stdin_fd >= 0 and os.isatty(stdin_fd)
445
+ old_attrs = None
446
+ if is_tty:
447
+ try: # bolaning terminal o'lchamini bizniki bilan tenglashtiramiz
448
+ size = fcntl.ioctl(stdin_fd, termios.TIOCGWINSZ, b"\0" * 8)
449
+ fcntl.ioctl(master, termios.TIOCSWINSZ, size)
450
+ except OSError:
451
+ pass
452
+ old_attrs = termios.tcgetattr(stdin_fd)
453
+ tty.setraw(stdin_fd)
454
+ chunks: list[bytes] = []
455
+ out_fd = _fileno(sys.stdout)
456
+ try:
457
+ while True:
458
+ watch = [master, stdin_fd] if is_tty else [master]
459
+ ready, _, _ = select.select(watch, [], [], 0.1)
460
+ if master in ready:
461
+ try:
462
+ data = os.read(master, 4096)
463
+ except OSError:
464
+ break
465
+ if not data:
466
+ break
467
+ chunks.append(data)
468
+ shown = self.redact(data.decode("utf-8", "replace"))
469
+ if out_fd >= 0:
470
+ os.write(out_fd, shown.encode())
471
+ else:
472
+ sys.stdout.write(shown)
473
+ if is_tty and stdin_fd in ready:
474
+ data = os.read(stdin_fd, 1024)
475
+ if data:
476
+ os.write(master, data)
477
+ finally:
478
+ if old_attrs is not None:
479
+ termios.tcsetattr(stdin_fd, termios.TCSADRAIN, old_attrs)
480
+ os.close(master)
481
+ _, status = os.waitpid(pid, 0)
482
+ code = os.waitstatus_to_exitcode(status)
483
+ text = b"".join(chunks).decode("utf-8", "replace")
484
+ text = ANSI_RE.sub("", text).replace("\r\n", "\n").replace("\r", "\n")
485
+ return code, self.redact(text)
486
+
487
+ def _execute(self, command: str) -> tuple[int, str]:
488
+ # Buyruqdan keyingi joriy papkani bilib olamiz, shunda `cd` keyingi buyruqlarga ham ta'sir qiladi
489
+ proc = subprocess.Popen(shell.argv(command, marker=CWD_MARKER), cwd=self.cwd, env=self._env(),
490
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
491
+ text=True, encoding="utf-8", errors="replace")
492
+ lines: list[str] = []
493
+ assert proc.stdout is not None
494
+ for line in proc.stdout:
495
+ idx = line.find(CWD_MARKER)
496
+ if idx >= 0:
497
+ # Belgi oxirgi qatorga yopishib qolishi mumkin (chiqish \n bilan tugamasa)
498
+ new_cwd = Path(line[idx + len(CWD_MARKER):].strip())
499
+ if new_cwd.is_dir():
500
+ self.cwd = new_cwd
501
+ line = line[:idx]
502
+ if not line:
503
+ continue
504
+ line = self.redact(ANSI_RE.sub("", line))
505
+ self.console.print(line.rstrip("\n"), style="dim", markup=False, highlight=False)
506
+ lines.append(line)
507
+ code = proc.wait()
508
+ return code, "".join(lines)
509
+
510
+ def read_file(self, path: str) -> dict[str, Any]:
511
+ target = self._path(path)
512
+ if not target.is_file():
513
+ return {"error": f"File not found: {target}"}
514
+ data = target.read_bytes()[:MAX_READ_BYTES]
515
+ self.console.print(f"[dim]📄 o'qildi: {target}[/]")
516
+ text = data.decode("utf-8", errors="replace")
517
+ truncated = target.stat().st_size > MAX_READ_BYTES
518
+ return {"path": str(target), "content": text, "truncated": truncated}
519
+
520
+ def write_file(self, path: str, content: str) -> dict[str, Any]:
521
+ target = self._path(path)
522
+ exists = target.exists()
523
+ lines = content.count("\n") + (0 if content.endswith("\n") or not content else 1)
524
+ preview = "\n".join(content.splitlines()[:15])
525
+ if lines > 15:
526
+ preview += f"\n… (+{lines - 15} qator)"
527
+ action = "Faylni qayta yozish" if exists else "Yangi fayl"
528
+ self.console.print(Panel(
529
+ Syntax(preview or " ", Syntax.guess_lexer(str(target), preview), theme="ansi_dark", word_wrap=True),
530
+ title=f"[bold]📝 {action}: {target}[/]", border_style="yellow" if exists else "green",
531
+ ))
532
+ if not self._confirm("caution" if exists else "safe"):
533
+ return {"declined": True, "message": "The user declined to write this file."}
534
+ self._checkpoint(target)
535
+ target.parent.mkdir(parents=True, exist_ok=True)
536
+ # newline="": qator oxirlari aynan berilgandek yoziladi (Windows'da \n → \r\n ga aylanmaydi)
537
+ with open(target, "w", encoding="utf-8", newline="") as fh:
538
+ fh.write(content)
539
+ self.console.print(f"[green]✓ yozildi[/] [dim]{target}[/]")
540
+ return {"path": str(target), "written": True, "lines": lines}
541
+
542
+ def list_directory(self, path: str = ".") -> dict[str, Any]:
543
+ target = self._path(path)
544
+ if not target.is_dir():
545
+ return {"error": f"Not a directory: {target}"}
546
+ entries = []
547
+ for child in sorted(target.iterdir(), key=lambda c: (not c.is_dir(), c.name.lower()))[:300]:
548
+ entries.append(child.name + ("/" if child.is_dir() else ""))
549
+ self.console.print(f"[dim]📁 ko'rildi: {target}[/]")
550
+ return {"path": str(target), "entries": entries}
551
+
552
+ def fetch_url(self, url: str) -> dict[str, Any]:
553
+ url = url.strip()
554
+ if not re.match(r"^https?://", url, re.IGNORECASE):
555
+ return {"error": "Only http(s) URLs are supported."}
556
+ self.console.print(f"[bold]🌐 Sahifani o'qish:[/] [cyan]{url}[/]")
557
+ if not self._confirm("safe"):
558
+ return {"declined": True, "message": "The user declined to open this URL."}
559
+ request = urllib.request.Request(url, headers={"User-Agent": "7zon-cli", "Accept": "*/*"})
560
+ try:
561
+ with urllib.request.urlopen(request, timeout=FETCH_TIMEOUT) as resp:
562
+ raw = resp.read(MAX_FETCH_BYTES)
563
+ status = resp.status
564
+ ctype = resp.headers.get("Content-Type", "")
565
+ except urllib.error.HTTPError as e:
566
+ return {"error": f"HTTP {e.code}", "body": _trim(e.read(20_000).decode("utf-8", "replace"))}
567
+ except (urllib.error.URLError, TimeoutError) as e:
568
+ return {"error": f"Could not open URL: {getattr(e, 'reason', e)}"}
569
+ charset = "utf-8"
570
+ m = re.search(r"charset=([\w-]+)", ctype)
571
+ if m:
572
+ charset = m.group(1)
573
+ text = raw.decode(charset, errors="replace")
574
+ if "html" in ctype.lower():
575
+ text = html_to_text(text)
576
+ self.console.print(f"[dim]✓ {status}, {len(text)} belgi[/]")
577
+ return {"url": url, "status": status, "content_type": ctype, "text": _trim(text)}
578
+
579
+
580
+ def edit_file(self, path: str, old_text: str, new_text: str) -> dict[str, Any]:
581
+ target = self._path(path)
582
+ if not target.is_file():
583
+ return {"error": f"File not found: {target}"}
584
+ # Asl qator oxirlarini (LF yoki CRLF) saqlab qolamiz, butun fayl o'zgarib ketmasin
585
+ with open(target, encoding="utf-8", newline="") as fh:
586
+ original = fh.read()
587
+ if "\r\n" in original and "\r\n" not in old_text:
588
+ old_text = old_text.replace("\n", "\r\n")
589
+ new_text = new_text.replace("\n", "\r\n")
590
+ count = original.count(old_text) if old_text else 0
591
+ if count == 0:
592
+ return {"error": "old_text was not found in the file. Read the file again and copy the text exactly."}
593
+ if count > 1:
594
+ return {"error": f"old_text appears {count} times. Include more surrounding lines so it is unique."}
595
+ updated = original.replace(old_text, new_text, 1)
596
+ diff = "".join(difflib.unified_diff(
597
+ original.splitlines(keepends=True), updated.splitlines(keepends=True),
598
+ fromfile=str(target), tofile=str(target), n=2,
599
+ ))
600
+ self.console.print(Panel(
601
+ Syntax(diff or " ", "diff", theme="ansi_dark", word_wrap=True),
602
+ title=f"[bold]✏️ Tahrir: {target}[/]", border_style="yellow",
603
+ ))
604
+ if not self._confirm("safe"):
605
+ return {"declined": True, "message": "The user declined this edit."}
606
+ self._checkpoint(target)
607
+ with open(target, "w", encoding="utf-8", newline="") as fh:
608
+ fh.write(updated)
609
+ self.console.print(f"[green]✓ o'zgartirildi[/] [dim]{target}[/]")
610
+ return {"path": str(target), "edited": True}
611
+
612
+
613
+ def request_secret(self, name: str, prompt: str, remember: bool = False) -> dict[str, Any]:
614
+ try:
615
+ key = vault.normalize(name)
616
+ except vault.SecretError as e:
617
+ return {"error": str(e)}
618
+ if key not in self.secrets and os.environ.get(key):
619
+ self.secrets[key] = os.environ[key] # CI: muhit o'zgaruvchisidan
620
+ if key in self.secrets:
621
+ self.console.print(f"[dim]🔐 {key} allaqachon bor, qayta so'ralmadi.[/]")
622
+ return {"name": key, "available": True, "usage": f"Use ${key} in run_command."}
623
+ if self.headless:
624
+ return {"declined": True, "message": f"Headless mode: set the environment variable {key} and run again."}
625
+ self.console.print(
626
+ f"[bold cyan]🔐 {prompt}[/]\n[dim]Yozganingiz ekranda ko'rinmaydi va AI'ga yuborilmaydi. "
627
+ "Yozib bo'lgach Enter bosing (bekor qilish: Ctrl+C).[/]"
628
+ )
629
+ try:
630
+ value = self.secret_input(" › ")
631
+ except (KeyboardInterrupt, EOFError):
632
+ self.console.print("[dim]Bekor qilindi.[/]")
633
+ return {"declined": True, "message": "The user cancelled entering the secret."}
634
+ if not value:
635
+ return {"declined": True, "message": "The user entered nothing."}
636
+ self.secrets[key] = value
637
+ saved = vault.save(key, value) if remember else ""
638
+ where = {"keychain": "tizim omborida (Keychain) saqlandi",
639
+ "file": "~/.7zon/secrets.json ga saqlandi, faqat sizga ochiq"}.get(saved, "faqat shu suhbat uchun")
640
+ self.console.print(f"[green]✓ {key} qabul qilindi[/] [dim]({where})[/]")
641
+ return {
642
+ "name": key,
643
+ "available": True,
644
+ "remembered": bool(saved),
645
+ "usage": f"The value is in environment variable ${key} for run_command. Never print it.",
646
+ }
647
+
648
+
649
+ def instagram(self, action: str, kind: str = "", source: str = "", caption: str = "",
650
+ target_id: str = "", text: str = "") -> dict[str, Any]:
651
+ token = self.secrets.get(ig.TOKEN_SECRET)
652
+ if not token:
653
+ return {
654
+ "error": "INSTAGRAM_ACCESS_TOKEN is not set.",
655
+ "how_to_get_it": [
656
+ "The Instagram account must be Professional (Business or Creator): in the Instagram app, "
657
+ "Settings > Account type and tools > Switch to professional account.",
658
+ "Open https://developers.facebook.com/apps for the user (run_command open), create an app of type "
659
+ "Business, add the Instagram product.",
660
+ "In the app: Instagram > API setup with Instagram business login > Generate token next to the "
661
+ "account, sign in to Instagram, copy the token.",
662
+ "Then call request_secret with name INSTAGRAM_ACCESS_TOKEN and remember=true, and retry.",
663
+ ],
664
+ }
665
+ client = ig.Instagram(token, http=self.instagram_http)
666
+ try:
667
+ if action == "profile":
668
+ data = client.profile()
669
+ self.console.print(f"[dim]📸 Instagram: @{data.get('username', '?')}[/]")
670
+ return data
671
+ if action == "media":
672
+ return client.media()
673
+ if action == "insights":
674
+ if not target_id:
675
+ return {"error": "target_id (media id) is required."}
676
+ return client.insights(target_id, text)
677
+ if action == "comments":
678
+ if not target_id:
679
+ return {"error": "target_id (media id) is required."}
680
+ return client.comments(target_id)
681
+ if action == "publishing_limit":
682
+ return client.publishing_limit()
683
+ if action == "refresh_token":
684
+ new = client.refresh_token()
685
+ self.secrets[ig.TOKEN_SECRET] = new
686
+ saved = vault.save(ig.TOKEN_SECRET, new)
687
+ self.console.print("[green]✓ Instagram tokeni yana 60 kunga uzaytirildi.[/]")
688
+ return {"refreshed": True, "saved": saved}
689
+ if action == "reply":
690
+ if not target_id or not text:
691
+ return {"error": "target_id (comment id) and text are required."}
692
+ self.console.print(Panel(text, title=f"[bold]💬 Izohga javob ({target_id})[/]", border_style="magenta"))
693
+ if not self._confirm("safe", allow_always=False):
694
+ return {"declined": True, "message": "The user declined this reply."}
695
+ return client.reply(target_id, text)
696
+ if action == "publish":
697
+ return self._instagram_publish(client, kind, source, caption)
698
+ return {"error": f"Unknown action: {action}"}
699
+ except ig.InstagramError as e:
700
+ return {"error": str(e)}
701
+
702
+ def _instagram_publish(self, client: Any, kind: str, source: str, caption: str) -> dict[str, Any]:
703
+ if kind not in ("image", "reel", "story_image", "story_video"):
704
+ return {"error": "kind must be image, reel, story_image or story_video."}
705
+ if not source:
706
+ return {"error": "source (local file path or public URL) is required."}
707
+ url, local = ig.resolve_source(source, kind, self.cwd)
708
+ names = {"image": "Rasm post", "reel": "Reels", "story_image": "Story (rasm)", "story_video": "Story (video)"}
709
+ lines = [f"[bold]{names[kind]}[/]", f"Fayl: {local or url}"]
710
+ if caption and not kind.startswith("story"):
711
+ lines.append(f"Matn: {caption}")
712
+ if local:
713
+ lines.append(
714
+ "[yellow]Instagram API faqat ochiq havoladan oladi: fayl 1 soatga vaqtinchalik "
715
+ "litterbox.catbox.moe ga yuklanadi, keyin o'chadi.[/]"
716
+ )
717
+ self.console.print(Panel("\n".join(lines), title="[bold]📸 Instagram'ga joylash[/]", border_style="magenta"))
718
+ # Ommaga ko'rinadigan amal: har doim alohida so'raladi
719
+ if not self._confirm("safe", allow_always=False):
720
+ return {"declined": True, "message": "The user declined publishing."}
721
+ if local:
722
+ self.console.print("[dim]↑ fayl yuklanmoqda...[/]")
723
+ url = self.temp_upload(local)
724
+ self.console.print("[dim]⏳ Instagram qayta ishlayapti...[/]")
725
+ result = client.publish(kind, url, caption)
726
+ self.console.print(f"[green]✓ Joylandi:[/] {result.get('permalink') or result.get('media_id')}")
727
+ return {"published": True, **result}
728
+
729
+
730
+ # ------------------------------------------------------------------ qidiruv
731
+
732
+ def _walk_files(self, root: Path) -> Any:
733
+ if root.is_file():
734
+ yield root
735
+ return
736
+ for dirpath, dirnames, filenames in os.walk(root):
737
+ dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS and not d.endswith(".egg-info")]
738
+ for name in filenames:
739
+ yield Path(dirpath) / name
740
+
741
+ def glob(self, pattern: str, path: str = ".") -> dict[str, Any]:
742
+ import fnmatch
743
+
744
+ root = self._path(path)
745
+ if not root.exists():
746
+ return {"error": f"Not found: {root}"}
747
+ pat = pattern.strip() or "*"
748
+ # "**/" qism nomlarni har qanday chuqurlikda moslaydi; aks holda faqat nom bo'yicha
749
+ found = []
750
+ for f in self._walk_files(root):
751
+ rel = f.relative_to(root).as_posix() if root.is_dir() else f.name
752
+ if fnmatch.fnmatch(rel, pat) or ("/" not in pat and fnmatch.fnmatch(f.name, pat)) \
753
+ or (pat.startswith("**/") and fnmatch.fnmatch(rel, pat[3:])):
754
+ found.append(f)
755
+ found.sort(key=lambda f: f.stat().st_mtime if f.exists() else 0, reverse=True)
756
+ self.console.print(f"[dim]🔎 {pattern}: {len(found)} ta fayl[/]")
757
+ shown = [f.relative_to(root).as_posix() if root.is_dir() else str(f) for f in found[:MAX_RESULTS]]
758
+ return {"root": str(root), "files": shown, "total": len(found), "truncated": len(found) > MAX_RESULTS}
759
+
760
+ def grep(self, pattern: str, path: str = ".", file_glob: str = "", ignore_case: bool = False) -> dict[str, Any]:
761
+ import fnmatch
762
+
763
+ try:
764
+ rx = re.compile(pattern, re.IGNORECASE if ignore_case else 0)
765
+ except re.error as e:
766
+ return {"error": f"Bad regular expression: {e}"}
767
+ root = self._path(path)
768
+ if not root.exists():
769
+ return {"error": f"Not found: {root}"}
770
+ matches: list[str] = []
771
+ files_hit = 0
772
+ for f in self._walk_files(root):
773
+ if file_glob and not fnmatch.fnmatch(f.name, file_glob):
774
+ continue
775
+ try:
776
+ if f.stat().st_size > MAX_GREP_FILE:
777
+ continue
778
+ data = f.read_bytes()
779
+ except OSError:
780
+ continue
781
+ if b"\0" in data[:8000]:
782
+ continue # ikkilik fayl
783
+ hit = False
784
+ for no, line in enumerate(data.decode("utf-8", "replace").splitlines(), 1):
785
+ if rx.search(line):
786
+ rel = f.relative_to(root).as_posix() if root.is_dir() else f.name
787
+ matches.append(f"{rel}:{no}: {line.strip()[:300]}")
788
+ hit = True
789
+ if len(matches) >= MAX_RESULTS:
790
+ break
791
+ files_hit += hit
792
+ if len(matches) >= MAX_RESULTS:
793
+ break
794
+ self.console.print(f"[dim]🔎 /{pattern}/: {len(matches)} ta moslik, {files_hit} ta faylda[/]")
795
+ return {"root": str(root), "matches": matches, "truncated": len(matches) >= MAX_RESULTS}
796
+
797
+
798
+ def save_memory(self, fact: str, scope: str = "project") -> dict[str, Any]:
799
+ if not fact.strip():
800
+ return {"error": "Empty fact."}
801
+ if any(v in fact for v in self.secrets.values() if len(v) >= 3):
802
+ return {"error": "Do not store secrets in memory."}
803
+ path = memory.save(fact, "global" if scope == "global" else "project", self.cwd)
804
+ self.console.print(f"[dim]🧠 eslab qolindi: {path}[/]")
805
+ return {"saved": True, "file": str(path)}
806
+
807
+
808
+ def view_file(self, path: str) -> dict[str, Any]:
809
+ target = self._path(path)
810
+ if not target.is_file():
811
+ return {"error": f"File not found: {target}"}
812
+ mime = VIEWABLE.get(target.suffix.lower())
813
+ if mime is None:
814
+ return {"error": f"Unsupported type {target.suffix}. Supported: {', '.join(VIEWABLE)}. Use read_file for text."}
815
+ size = target.stat().st_size
816
+ if size > MAX_ATTACH_BYTES:
817
+ return {"error": f"File is too large ({size // 1_000_000} MB, limit 15 MB)."}
818
+ self.attachments.append((mime, target.read_bytes(), str(target)))
819
+ self.console.print(f"[dim]🖼️ ko'rildi: {target}[/]")
820
+ return {"path": str(target), "mime_type": mime, "attached": True}
821
+
822
+ def pop_attachments(self) -> list[tuple[str, bytes, str]]:
823
+ items, self.attachments = self.attachments, []
824
+ return items
825
+
826
+
827
+ # ------------------------------------------------------------------ checkpoint / undo
828
+
829
+ def _checkpoint(self, target: Path) -> None:
830
+ before = target.read_bytes() if target.exists() else None
831
+ self.checkpoints.append((target, before))
832
+
833
+ def undo(self) -> str | None:
834
+ """Oxirgi fayl o'zgarishini qaytaradi. Qaytarilgan fayl yo'lini yoki None ni beradi."""
835
+ if not self.checkpoints:
836
+ return None
837
+ target, before = self.checkpoints.pop()
838
+ if before is None:
839
+ if target.exists():
840
+ target.unlink()
841
+ else:
842
+ target.parent.mkdir(parents=True, exist_ok=True)
843
+ target.write_bytes(before)
844
+ return str(target)
845
+
846
+
847
+ def html_to_text(page: str) -> str:
848
+ """Oddiy HTML → matn: skript/stillarni olib tashlaydi, teglarni qatorlarga aylantiradi."""
849
+ page = re.sub(r"(?is)<(script|style|noscript|svg|head)[^>]*>.*?</\1>", " ", page)
850
+ page = re.sub(r"(?i)<br\s*/?>|</(p|div|li|h[1-6]|tr|section|article)>", "\n", page)
851
+ page = re.sub(r"(?s)<[^>]+>", " ", page)
852
+ page = html.unescape(page)
853
+ page = re.sub(r"[ \t\r\f\v]+", " ", page)
854
+ page = re.sub(r"\n\s*\n+", "\n\n", page)
855
+ return page.strip()