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.
- 7zon_cli-0.2.2.dist-info/METADATA +341 -0
- 7zon_cli-0.2.2.dist-info/RECORD +24 -0
- 7zon_cli-0.2.2.dist-info/WHEEL +4 -0
- 7zon_cli-0.2.2.dist-info/entry_points.txt +2 -0
- 7zon_cli-0.2.2.dist-info/licenses/LICENSE +21 -0
- zon7/__init__.py +1 -0
- zon7/__main__.py +3 -0
- zon7/ai.py +45 -0
- zon7/banner.py +74 -0
- zon7/cli.py +517 -0
- zon7/common.py +16 -0
- zon7/config.py +80 -0
- zon7/context.py +91 -0
- zon7/instagram.py +224 -0
- zon7/memory.py +66 -0
- zon7/menu.py +162 -0
- zon7/prompts.py +85 -0
- zon7/providers/__init__.py +1 -0
- zon7/providers/claude.py +220 -0
- zon7/providers/gemini.py +381 -0
- zon7/safety.py +61 -0
- zon7/secrets.py +133 -0
- zon7/shell.py +61 -0
- zon7/tools.py +855 -0
zon7/providers/claude.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""Claude (Anthropic) provayderi."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
from collections.abc import Callable, Iterator
|
|
9
|
+
from contextlib import contextmanager
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
import anthropic
|
|
13
|
+
|
|
14
|
+
from zon7.common import COMMAND_SCHEMA, AIError
|
|
15
|
+
|
|
16
|
+
DEFAULT_MODEL = "claude-opus-5-5"
|
|
17
|
+
ENV_KEYS = ("ANTHROPIC_API_KEY",)
|
|
18
|
+
FALLBACK_BETA = "server-side-fallback-2026-07-01"
|
|
19
|
+
|
|
20
|
+
def make_client(cfg: dict[str, Any]) -> anthropic.Anthropic:
|
|
21
|
+
# Muhit o'zgaruvchisi config'dagi kalitdan ustun turadi
|
|
22
|
+
key = os.environ.get("ANTHROPIC_API_KEY") or cfg.get("anthropic_api_key")
|
|
23
|
+
return anthropic.Anthropic(api_key=key) if key else anthropic.Anthropic()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _common(cfg: dict[str, Any]) -> dict[str, Any]:
|
|
27
|
+
return {
|
|
28
|
+
"model": cfg["model"] or DEFAULT_MODEL,
|
|
29
|
+
# Xavfsizlik filtri so'rovni rad etsa, server tavsiya etilgan modelda qayta urinadi
|
|
30
|
+
"betas": [FALLBACK_BETA],
|
|
31
|
+
"fallbacks": "default",
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@contextmanager
|
|
36
|
+
def friendly_errors() -> Iterator[None]:
|
|
37
|
+
try:
|
|
38
|
+
yield
|
|
39
|
+
except anthropic.AuthenticationError:
|
|
40
|
+
raise AIError("API kalit noto'g'ri yoki muddati o'tgan. Yangilash: 7zon config set-key --provider claude") from None
|
|
41
|
+
except anthropic.PermissionDeniedError:
|
|
42
|
+
raise AIError("Bu API kalitga ushbu model uchun ruxsat yo'q.") from None
|
|
43
|
+
except anthropic.NotFoundError:
|
|
44
|
+
raise AIError("Model topilmadi. Tekshiring: 7zon config show") from None
|
|
45
|
+
except anthropic.RateLimitError:
|
|
46
|
+
raise AIError("So'rovlar limiti tugadi. Bir oz kutib, qayta urinib ko'ring.") from None
|
|
47
|
+
except anthropic.BadRequestError as e:
|
|
48
|
+
raise AIError(f"So'rov noto'g'ri: {e.message}") from None
|
|
49
|
+
except anthropic.APIStatusError as e:
|
|
50
|
+
raise AIError(f"Server xatosi ({e.status_code}). Keyinroq qayta urinib ko'ring.") from None
|
|
51
|
+
except anthropic.APIConnectionError:
|
|
52
|
+
raise AIError("Internetga ulanib bo'lmadi. Tarmoqni tekshiring.") from None
|
|
53
|
+
except TypeError as e:
|
|
54
|
+
# SDK hech qanday kalit topa olmaganda TypeError beradi
|
|
55
|
+
if "authentication" in str(e).lower():
|
|
56
|
+
raise AIError("API kalit topilmadi. Sozlash: 7zon config set-key --provider claude") from None
|
|
57
|
+
raise
|
|
58
|
+
except anthropic.AnthropicError as e:
|
|
59
|
+
msg = str(e)
|
|
60
|
+
if "api_key" in msg.lower() or "credential" in msg.lower() or "auth" in msg.lower():
|
|
61
|
+
raise AIError("API kalit topilmadi. Sozlash: 7zon config set-key --provider claude") from None
|
|
62
|
+
raise AIError(msg) from None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _check_stop(message: Any) -> None:
|
|
66
|
+
if message.stop_reason == "refusal":
|
|
67
|
+
raise AIError("Bu so'rov xavfsizlik qoidalari sabab bajarilmadi.")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def suggest_command(request: str, env: str, system: str, cfg: dict[str, Any]) -> dict[str, str]:
|
|
71
|
+
"""So'rovdan bitta shell buyrug'ini yaratadi: {command, explanation, risk}."""
|
|
72
|
+
with friendly_errors():
|
|
73
|
+
client = make_client(cfg)
|
|
74
|
+
message = client.beta.messages.create(
|
|
75
|
+
**_common(cfg),
|
|
76
|
+
max_tokens=16000,
|
|
77
|
+
output_config={
|
|
78
|
+
"effort": cfg["effort"],
|
|
79
|
+
"format": {"type": "json_schema", "schema": COMMAND_SCHEMA},
|
|
80
|
+
},
|
|
81
|
+
system=system,
|
|
82
|
+
messages=[{"role": "user", "content": f"<environment>\n{env}\n</environment>\n\n{request}"}],
|
|
83
|
+
)
|
|
84
|
+
_check_stop(message)
|
|
85
|
+
text = next((b.text for b in message.content if b.type == "text"), "")
|
|
86
|
+
try:
|
|
87
|
+
data = json.loads(text)
|
|
88
|
+
except json.JSONDecodeError:
|
|
89
|
+
raise AIError("AI javobini o'qib bo'lmadi. Qayta urinib ko'ring.") from None
|
|
90
|
+
return {k: str(data.get(k, "")) for k in ("command", "explanation", "risk")}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def stream_answer(
|
|
94
|
+
system: str,
|
|
95
|
+
messages: list[dict[str, Any]],
|
|
96
|
+
cfg: dict[str, Any],
|
|
97
|
+
on_text: Callable[[str], None],
|
|
98
|
+
) -> str:
|
|
99
|
+
"""Javobni oqim (stream) ko'rinishida qaytaradi va to'liq matnni beradi."""
|
|
100
|
+
with friendly_errors():
|
|
101
|
+
client = make_client(cfg)
|
|
102
|
+
with client.beta.messages.stream(
|
|
103
|
+
**_common(cfg),
|
|
104
|
+
max_tokens=64000,
|
|
105
|
+
output_config={"effort": cfg["effort"]},
|
|
106
|
+
system=system,
|
|
107
|
+
messages=messages,
|
|
108
|
+
) as stream:
|
|
109
|
+
for text in stream.text_stream:
|
|
110
|
+
on_text(text)
|
|
111
|
+
final = stream.get_final_message()
|
|
112
|
+
_check_stop(final)
|
|
113
|
+
return "".join(b.text for b in final.content if b.type == "text")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
# --------------------------------------------------------------------------- agent
|
|
117
|
+
|
|
118
|
+
MAX_STEPS = 25
|
|
119
|
+
AUTO_COMPRESS_CHARS = 400_000
|
|
120
|
+
SUMMARY_PROMPT = "Summarize our conversation so far for your own future reference: the user's goals and preferences, decisions made, files and paths you touched, commands you ran and their results, accounts or services connected, and what is still left to do. Plain text, under 400 words. Do not call any tool."
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class Agent:
|
|
124
|
+
"""Suhbat davomida asboblardan foydalanadigan agent (Claude tool use, qo'lda yozilgan tsikl)."""
|
|
125
|
+
|
|
126
|
+
def __init__(self, system: str, cfg: dict[str, Any], tool_specs: list[dict[str, Any]]) -> None:
|
|
127
|
+
self.cfg = cfg
|
|
128
|
+
self.system = system
|
|
129
|
+
self.client = None
|
|
130
|
+
self.messages: list[dict[str, Any]] = []
|
|
131
|
+
self.tools = [
|
|
132
|
+
{"name": t["name"], "description": t["description"], "input_schema": t["parameters"], "strict": True}
|
|
133
|
+
for t in tool_specs
|
|
134
|
+
]
|
|
135
|
+
|
|
136
|
+
def size(self) -> int:
|
|
137
|
+
return len(json.dumps(self.messages, default=str, ensure_ascii=False))
|
|
138
|
+
|
|
139
|
+
def clear(self) -> None:
|
|
140
|
+
self.messages = []
|
|
141
|
+
|
|
142
|
+
def compress(self) -> bool:
|
|
143
|
+
if len(self.messages) < 4:
|
|
144
|
+
return False
|
|
145
|
+
with friendly_errors():
|
|
146
|
+
if self.client is None:
|
|
147
|
+
self.client = make_client(self.cfg)
|
|
148
|
+
response = self.client.beta.messages.create(
|
|
149
|
+
**_common(self.cfg),
|
|
150
|
+
max_tokens=4000,
|
|
151
|
+
output_config={"effort": "low"},
|
|
152
|
+
system=self.system,
|
|
153
|
+
tools=self.tools,
|
|
154
|
+
messages=[*self.messages, {"role": "user", "content": SUMMARY_PROMPT}],
|
|
155
|
+
)
|
|
156
|
+
_check_stop(response)
|
|
157
|
+
summary = "".join(b.text for b in response.content if b.type == "text").strip()
|
|
158
|
+
if not summary:
|
|
159
|
+
return False
|
|
160
|
+
self.messages = [
|
|
161
|
+
{"role": "user", "content": f"Summary of our earlier conversation:\n{summary}"},
|
|
162
|
+
{"role": "assistant", "content": "Tushunarli, shu asosda davom etamiz."},
|
|
163
|
+
]
|
|
164
|
+
return True
|
|
165
|
+
|
|
166
|
+
def send(
|
|
167
|
+
self,
|
|
168
|
+
text: str,
|
|
169
|
+
run_tool: Callable[[str, dict[str, Any]], dict[str, Any]],
|
|
170
|
+
on_text: Callable[[str], None],
|
|
171
|
+
thinking: Callable[[], Any],
|
|
172
|
+
) -> None:
|
|
173
|
+
if self.size() > AUTO_COMPRESS_CHARS:
|
|
174
|
+
with thinking():
|
|
175
|
+
self.compress()
|
|
176
|
+
start = len(self.messages)
|
|
177
|
+
self.messages.append({"role": "user", "content": text})
|
|
178
|
+
try:
|
|
179
|
+
for _ in range(MAX_STEPS):
|
|
180
|
+
with friendly_errors(), thinking():
|
|
181
|
+
if self.client is None:
|
|
182
|
+
self.client = make_client(self.cfg)
|
|
183
|
+
response = self.client.beta.messages.create(
|
|
184
|
+
**_common(self.cfg),
|
|
185
|
+
max_tokens=16000,
|
|
186
|
+
output_config={"effort": self.cfg["effort"]},
|
|
187
|
+
system=self.system,
|
|
188
|
+
tools=self.tools,
|
|
189
|
+
messages=self.messages,
|
|
190
|
+
)
|
|
191
|
+
_check_stop(response)
|
|
192
|
+
self.messages.append({"role": "assistant", "content": response.content})
|
|
193
|
+
said = "".join(b.text for b in response.content if b.type == "text" and b.text)
|
|
194
|
+
if said.strip():
|
|
195
|
+
on_text(said)
|
|
196
|
+
tool_uses = [b for b in response.content if b.type == "tool_use"]
|
|
197
|
+
if response.stop_reason != "tool_use" or not tool_uses:
|
|
198
|
+
return
|
|
199
|
+
results = []
|
|
200
|
+
for block in tool_uses:
|
|
201
|
+
result = run_tool(block.name, dict(block.input))
|
|
202
|
+
content: list[dict[str, Any]] = [{"type": "text", "text": json.dumps(result, ensure_ascii=False)}]
|
|
203
|
+
pop = getattr(run_tool, "pop_attachments", None)
|
|
204
|
+
for mime, data, _path in (pop() if pop else []):
|
|
205
|
+
kind = "document" if mime == "application/pdf" else "image"
|
|
206
|
+
content.append({"type": kind, "source": {
|
|
207
|
+
"type": "base64", "media_type": mime, "data": base64.b64encode(data).decode(),
|
|
208
|
+
}})
|
|
209
|
+
results.append({
|
|
210
|
+
"type": "tool_result",
|
|
211
|
+
"tool_use_id": block.id,
|
|
212
|
+
"content": content,
|
|
213
|
+
"is_error": "error" in result,
|
|
214
|
+
})
|
|
215
|
+
# Barcha natijalar bitta user xabarida qaytariladi
|
|
216
|
+
self.messages.append({"role": "user", "content": results})
|
|
217
|
+
on_text("_(Juda ko'p qadam bo'ldi, to'xtatdim. Davom etishni xohlasangiz, yozing.)_")
|
|
218
|
+
except BaseException:
|
|
219
|
+
del self.messages[start:]
|
|
220
|
+
raise
|
zon7/providers/gemini.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
"""Google Gemini provayderi (standart).
|
|
2
|
+
|
|
3
|
+
SDK'siz, Python'ning o'z urllib moduli orqali Gemini REST API bilan ishlaydi. Shuning uchun
|
|
4
|
+
kompilyatsiya qilinadigan paketlar (pydantic-core, cryptography) kerak emas va 7ZON Termux
|
|
5
|
+
(Android), Raspberry Pi va boshqa joylarda ham oson o'rnatiladi.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import base64
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import time
|
|
14
|
+
import urllib.error
|
|
15
|
+
import urllib.request
|
|
16
|
+
from collections.abc import Callable, Iterator
|
|
17
|
+
from contextlib import contextmanager
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from zon7.common import COMMAND_SCHEMA, AIError
|
|
22
|
+
|
|
23
|
+
API_BASE = "https://generativelanguage.googleapis.com/v1beta/models"
|
|
24
|
+
DEFAULT_MODEL = "gemini-3.6-flash"
|
|
25
|
+
# Standart model band (5xx) yoki uning limiti tugagan (429) bo'lsa, navbat bilan shu modellarda urinamiz.
|
|
26
|
+
# Bepul tarifda limit har bir model uchun alohida, shuning uchun bir nechta model kunlik limitni oshiradi.
|
|
27
|
+
FALLBACK_MODELS = (
|
|
28
|
+
"gemini-3.7-flash",
|
|
29
|
+
"gemini-3.5-flash",
|
|
30
|
+
"gemini-3.8-flash",
|
|
31
|
+
"gemini-3.5-flash-lite",
|
|
32
|
+
"gemini-3.1-flash-lite",
|
|
33
|
+
)
|
|
34
|
+
TIMEOUT = 90 # soniya
|
|
35
|
+
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
|
+
BLOCK_REASONS = ("SAFETY", "PROHIBITED", "BLOCKLIST", "SPII")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class GeminiError(Exception):
|
|
41
|
+
"""Gemini API'dan kelgan HTTP xato."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, code: int, status: str = "", message: str = "") -> None:
|
|
44
|
+
super().__init__(f"{code} {status} {message}")
|
|
45
|
+
self.code = code
|
|
46
|
+
self.status = status
|
|
47
|
+
self.message = message
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# --------------------------------------------------------------------------- transport
|
|
51
|
+
|
|
52
|
+
def _http_post(url: str, key: str, body: dict[str, Any], stream: bool = False) -> Any:
|
|
53
|
+
"""POST so'rov. stream=False: javob dict; stream=True: SSE bo'laklari iteratori."""
|
|
54
|
+
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
|
55
|
+
req = urllib.request.Request(url, data=data, method="POST", headers={
|
|
56
|
+
"Content-Type": "application/json",
|
|
57
|
+
"x-goog-api-key": key,
|
|
58
|
+
"User-Agent": "7zon-cli",
|
|
59
|
+
})
|
|
60
|
+
try:
|
|
61
|
+
resp = urllib.request.urlopen(req, timeout=TIMEOUT)
|
|
62
|
+
except urllib.error.HTTPError as e:
|
|
63
|
+
raw = e.read().decode("utf-8", "replace")
|
|
64
|
+
try:
|
|
65
|
+
err = json.loads(raw).get("error", {})
|
|
66
|
+
except json.JSONDecodeError:
|
|
67
|
+
err = {}
|
|
68
|
+
# Kvota tafsilotlari (masalan GenerateRequestsPerDay...) xabarga qo'shiladi
|
|
69
|
+
details = json.dumps(err.get("details", []))[:2000]
|
|
70
|
+
raise GeminiError(e.code, err.get("status", ""), f"{err.get('message', raw[:300])} {details}") from None
|
|
71
|
+
except (urllib.error.URLError, TimeoutError, OSError) as e:
|
|
72
|
+
raise ConnectionError(str(getattr(e, "reason", e))) from None
|
|
73
|
+
if not stream:
|
|
74
|
+
with resp:
|
|
75
|
+
return json.loads(resp.read().decode("utf-8"))
|
|
76
|
+
return _sse(resp)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _sse(resp: Any) -> Iterator[dict[str, Any]]:
|
|
80
|
+
with resp:
|
|
81
|
+
for raw in resp:
|
|
82
|
+
line = raw.decode("utf-8", "replace").strip()
|
|
83
|
+
if line.startswith("data:"):
|
|
84
|
+
payload = line[5:].strip()
|
|
85
|
+
if payload:
|
|
86
|
+
yield json.loads(payload)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _api_key(cfg: dict[str, Any]) -> str:
|
|
90
|
+
for name in ENV_KEYS:
|
|
91
|
+
if os.environ.get(name):
|
|
92
|
+
return os.environ[name]
|
|
93
|
+
key = cfg.get("gemini_api_key")
|
|
94
|
+
if not key:
|
|
95
|
+
raise AIError(f"Gemini API kalit topilmadi. {KEY_HINT}")
|
|
96
|
+
return key
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _call(cfg: dict[str, Any], model: str, body: dict[str, Any], stream: bool = False) -> Any:
|
|
100
|
+
method = "streamGenerateContent?alt=sse" if stream else "generateContent"
|
|
101
|
+
return _http_post(f"{API_BASE}/{model}:{method}", _api_key(cfg), body, stream=stream)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _models(cfg: dict[str, Any]) -> list[str]:
|
|
105
|
+
"""Urinish tartibi: foydalanuvchi modeli bo'lsa faqat o'sha, aks holda standart + zaxira."""
|
|
106
|
+
if cfg.get("model"):
|
|
107
|
+
return [cfg["model"]]
|
|
108
|
+
return [DEFAULT_MODEL, *FALLBACK_MODELS]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _overloaded(e: GeminiError) -> bool:
|
|
112
|
+
"""Boshqa modelda urinib ko'rishga arziydimi: band (5xx) yoki shu modelning limiti tugagan (429)."""
|
|
113
|
+
return e.code in (429, 500, 502, 503, 504)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@contextmanager
|
|
117
|
+
def friendly_errors() -> Iterator[None]:
|
|
118
|
+
try:
|
|
119
|
+
yield
|
|
120
|
+
except GeminiError as e:
|
|
121
|
+
text = f"{e.status} {e.message}"
|
|
122
|
+
if e.code in (401, 403) or "API_KEY" in text or "API key" in text:
|
|
123
|
+
raise AIError(f"Gemini API kalit noto'g'ri yoki ruxsat yo'q. {KEY_HINT}") from None
|
|
124
|
+
if e.code == 404:
|
|
125
|
+
raise AIError("Model topilmadi. Tekshiring: 7zon config show") from None
|
|
126
|
+
if e.code == 429:
|
|
127
|
+
if "PerDay" in text or "per day" in text.lower() or "quota" in text.lower():
|
|
128
|
+
raise AIError(
|
|
129
|
+
"Gemini bepul tarifining kunlik limiti barcha modellarda tugadi. Ertaga qayta urinib ko'ring "
|
|
130
|
+
"yoki AI Studio'da billing ulang: https://aistudio.google.com/usage"
|
|
131
|
+
) from None
|
|
132
|
+
raise AIError("So'rovlar limiti tugadi. Bir daqiqa kutib, qayta urinib ko'ring.") from None
|
|
133
|
+
if e.code in (503, 504):
|
|
134
|
+
raise AIError(f"Gemini serveri hozir band ({e.code}). Bir daqiqadan keyin qayta urinib ko'ring.") from None
|
|
135
|
+
if e.code >= 500:
|
|
136
|
+
raise AIError(f"Gemini server xatosi ({e.code}). Keyinroq qayta urinib ko'ring.") from None
|
|
137
|
+
raise AIError(f"So'rov noto'g'ri ({e.code}): {e.message[:300]}") from None
|
|
138
|
+
except ConnectionError:
|
|
139
|
+
raise AIError("Internetga ulanib bo'lmadi. Tarmoqni tekshiring.") from None
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# --------------------------------------------------------------------------- javobni o'qish
|
|
143
|
+
|
|
144
|
+
def _candidate_content(response: dict[str, Any]) -> dict[str, Any] | None:
|
|
145
|
+
candidates = response.get("candidates") or []
|
|
146
|
+
return candidates[0].get("content") if candidates else None
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _text(response: dict[str, Any]) -> str:
|
|
150
|
+
content = _candidate_content(response) or {}
|
|
151
|
+
return "".join(p.get("text", "") for p in content.get("parts", []) if not p.get("thought"))
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _blocked(response: dict[str, Any]) -> bool:
|
|
155
|
+
if (response.get("promptFeedback") or {}).get("blockReason"):
|
|
156
|
+
return True
|
|
157
|
+
for cand in response.get("candidates") or []:
|
|
158
|
+
if any(r in str(cand.get("finishReason", "")) for r in BLOCK_REASONS):
|
|
159
|
+
return True
|
|
160
|
+
return False
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _schema_for_gemini(schema: dict[str, Any]) -> dict[str, Any]:
|
|
164
|
+
return {k: v for k, v in schema.items() if k != "additionalProperties"}
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _user(text: str) -> dict[str, Any]:
|
|
168
|
+
return {"role": "user", "parts": [{"text": text}]}
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _generate_with_fallback(cfg: dict[str, Any], body: dict[str, Any]) -> dict[str, Any]:
|
|
172
|
+
models = _models(cfg)
|
|
173
|
+
for i, model in enumerate(models):
|
|
174
|
+
try:
|
|
175
|
+
return _call(cfg, model, body)
|
|
176
|
+
except GeminiError as e:
|
|
177
|
+
if not (_overloaded(e) and i + 1 < len(models)):
|
|
178
|
+
raise
|
|
179
|
+
raise AssertionError("unreachable")
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
# --------------------------------------------------------------------------- ask / fix / explain
|
|
183
|
+
|
|
184
|
+
def suggest_command(request: str, env: str, system: str, cfg: dict[str, Any]) -> dict[str, str]:
|
|
185
|
+
body = {
|
|
186
|
+
"systemInstruction": {"parts": [{"text": system}]},
|
|
187
|
+
"contents": [_user(f"<environment>\n{env}\n</environment>\n\n{request}")],
|
|
188
|
+
"generationConfig": {
|
|
189
|
+
"responseMimeType": "application/json",
|
|
190
|
+
"responseJsonSchema": _schema_for_gemini(COMMAND_SCHEMA),
|
|
191
|
+
},
|
|
192
|
+
}
|
|
193
|
+
with friendly_errors():
|
|
194
|
+
response = _generate_with_fallback(cfg, body)
|
|
195
|
+
if _blocked(response):
|
|
196
|
+
raise AIError("Bu so'rov xavfsizlik qoidalari sabab bajarilmadi.")
|
|
197
|
+
try:
|
|
198
|
+
data = json.loads(_text(response) or "")
|
|
199
|
+
except json.JSONDecodeError:
|
|
200
|
+
raise AIError("AI javobini o'qib bo'lmadi. Qayta urinib ko'ring.") from None
|
|
201
|
+
return {k: str(data.get(k, "")) for k in ("command", "explanation", "risk")}
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def stream_answer(
|
|
205
|
+
system: str,
|
|
206
|
+
messages: list[dict[str, Any]],
|
|
207
|
+
cfg: dict[str, Any],
|
|
208
|
+
on_text: Callable[[str], None],
|
|
209
|
+
) -> str:
|
|
210
|
+
body = {
|
|
211
|
+
"systemInstruction": {"parts": [{"text": system}]},
|
|
212
|
+
"contents": [
|
|
213
|
+
{"role": "model" if m["role"] == "assistant" else "user", "parts": [{"text": m["content"]}]}
|
|
214
|
+
for m in messages
|
|
215
|
+
],
|
|
216
|
+
}
|
|
217
|
+
parts: list[str] = []
|
|
218
|
+
last: dict[str, Any] = {}
|
|
219
|
+
with friendly_errors():
|
|
220
|
+
models = _models(cfg)
|
|
221
|
+
for i, model in enumerate(models):
|
|
222
|
+
try:
|
|
223
|
+
for chunk in _call(cfg, model, body, stream=True):
|
|
224
|
+
last = chunk
|
|
225
|
+
piece = _text(chunk)
|
|
226
|
+
if piece:
|
|
227
|
+
parts.append(piece)
|
|
228
|
+
on_text(piece)
|
|
229
|
+
break
|
|
230
|
+
except GeminiError as e:
|
|
231
|
+
# Matn chiqa boshlagan bo'lsa, boshqa modelga o'tmaymiz
|
|
232
|
+
if parts or not (_overloaded(e) and i + 1 < len(models)):
|
|
233
|
+
raise
|
|
234
|
+
if not parts and _blocked(last):
|
|
235
|
+
raise AIError("Bu so'rov xavfsizlik qoidalari sabab bajarilmadi.")
|
|
236
|
+
return "".join(parts)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
# --------------------------------------------------------------------------- agent
|
|
240
|
+
|
|
241
|
+
MAX_STEPS = 25
|
|
242
|
+
RETRY_PAUSES = (0, 3, 8) # soniya: band serverga qayta urinishlar orasidagi kutish
|
|
243
|
+
AUTO_COMPRESS_CHARS = 400_000 # taxminan 100k token: shundan oshsa eski suhbat xulosaga aylantiriladi
|
|
244
|
+
SUMMARY_PROMPT = (
|
|
245
|
+
"Summarize our conversation so far for your own future reference: the user's goals and preferences, "
|
|
246
|
+
"decisions made, files and paths you touched, commands you ran and their results, accounts or services "
|
|
247
|
+
"connected, and what is still left to do. Plain text, under 400 words. Do not call any tool."
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
class Agent:
|
|
252
|
+
"""Suhbat davomida asboblardan foydalanadigan agent (Gemini function calling, REST)."""
|
|
253
|
+
|
|
254
|
+
def __init__(self, system: str, cfg: dict[str, Any], tool_specs: list[dict[str, Any]]) -> None:
|
|
255
|
+
self.cfg = cfg
|
|
256
|
+
self.model_index = 0
|
|
257
|
+
self.contents: list[dict[str, Any]] = []
|
|
258
|
+
self.system = system
|
|
259
|
+
self.tools = [{"functionDeclarations": [
|
|
260
|
+
{"name": t["name"], "description": t["description"],
|
|
261
|
+
"parametersJsonSchema": _schema_for_gemini(t["parameters"])}
|
|
262
|
+
for t in tool_specs
|
|
263
|
+
]}] if tool_specs else []
|
|
264
|
+
|
|
265
|
+
def _body(self) -> dict[str, Any]:
|
|
266
|
+
body: dict[str, Any] = {"systemInstruction": {"parts": [{"text": self.system}]}, "contents": self.contents}
|
|
267
|
+
if self.tools:
|
|
268
|
+
body["tools"] = self.tools
|
|
269
|
+
return body
|
|
270
|
+
|
|
271
|
+
def _generate(self) -> dict[str, Any]:
|
|
272
|
+
models = _models(self.cfg)
|
|
273
|
+
last_error: GeminiError | None = None
|
|
274
|
+
# Barcha modellar band bo'lsa (5xx), biroz kutib zanjirni yana aylanib chiqamiz
|
|
275
|
+
for attempt, pause in enumerate(RETRY_PAUSES):
|
|
276
|
+
if pause:
|
|
277
|
+
time.sleep(pause)
|
|
278
|
+
# Oxirgi ishlagan modeldan boshlaymiz: limiti tugagan modellarga har qadamda qayta urinmaymiz
|
|
279
|
+
start = self.model_index if attempt == 0 else 0
|
|
280
|
+
last_error = None
|
|
281
|
+
for i in range(start, len(models)):
|
|
282
|
+
try:
|
|
283
|
+
response = _call(self.cfg, models[i], self._body())
|
|
284
|
+
self.model_index = i
|
|
285
|
+
return response
|
|
286
|
+
except GeminiError as e:
|
|
287
|
+
if not _overloaded(e):
|
|
288
|
+
raise
|
|
289
|
+
last_error = e
|
|
290
|
+
# Hammasi faqat limit (429) bo'lsa, kutish foyda bermaydi
|
|
291
|
+
if last_error is not None and last_error.code == 429:
|
|
292
|
+
raise last_error
|
|
293
|
+
assert last_error is not None
|
|
294
|
+
raise last_error
|
|
295
|
+
|
|
296
|
+
def size(self) -> int:
|
|
297
|
+
"""Suhbat hajmi (belgilar soni, taxminiy; biriktirilgan fayllarsiz)."""
|
|
298
|
+
total = 0
|
|
299
|
+
for content in self.contents:
|
|
300
|
+
for part in content.get("parts", []):
|
|
301
|
+
total += len(part.get("text", ""))
|
|
302
|
+
if "functionCall" in part:
|
|
303
|
+
total += len(json.dumps(part["functionCall"].get("args", {}), ensure_ascii=False))
|
|
304
|
+
if "functionResponse" in part:
|
|
305
|
+
total += len(json.dumps(part["functionResponse"].get("response", {}), ensure_ascii=False))
|
|
306
|
+
return total
|
|
307
|
+
|
|
308
|
+
def clear(self) -> None:
|
|
309
|
+
self.contents = []
|
|
310
|
+
|
|
311
|
+
def compress(self) -> bool:
|
|
312
|
+
"""Suhbatni qisqa xulosaga aylantiradi. Muvaffaqiyatli bo'lsa True."""
|
|
313
|
+
if len(self.contents) < 4:
|
|
314
|
+
return False
|
|
315
|
+
self.contents.append(_user(SUMMARY_PROMPT))
|
|
316
|
+
try:
|
|
317
|
+
with friendly_errors():
|
|
318
|
+
response = self._generate()
|
|
319
|
+
finally:
|
|
320
|
+
self.contents.pop()
|
|
321
|
+
summary = _text(response).strip()
|
|
322
|
+
if not summary:
|
|
323
|
+
return False
|
|
324
|
+
self.contents = [
|
|
325
|
+
_user(f"Summary of our earlier conversation:\n{summary}"),
|
|
326
|
+
{"role": "model", "parts": [{"text": "Tushunarli, shu asosda davom etamiz."}]},
|
|
327
|
+
]
|
|
328
|
+
return True
|
|
329
|
+
|
|
330
|
+
def send(
|
|
331
|
+
self,
|
|
332
|
+
text: str,
|
|
333
|
+
run_tool: Callable[[str, dict[str, Any]], dict[str, Any]],
|
|
334
|
+
on_text: Callable[[str], None],
|
|
335
|
+
thinking: Callable[[], Any],
|
|
336
|
+
) -> None:
|
|
337
|
+
if self.size() > AUTO_COMPRESS_CHARS:
|
|
338
|
+
with thinking():
|
|
339
|
+
self.compress()
|
|
340
|
+
start = len(self.contents)
|
|
341
|
+
self.contents.append(_user(text))
|
|
342
|
+
try:
|
|
343
|
+
for _ in range(MAX_STEPS):
|
|
344
|
+
with friendly_errors(), thinking():
|
|
345
|
+
response = self._generate()
|
|
346
|
+
if _blocked(response) or not response.get("candidates"):
|
|
347
|
+
raise AIError("Bu so'rov xavfsizlik qoidalari sabab bajarilmadi.")
|
|
348
|
+
content = _candidate_content(response)
|
|
349
|
+
if not content or not content.get("parts"):
|
|
350
|
+
return
|
|
351
|
+
content.setdefault("role", "model")
|
|
352
|
+
# Modelning javobini to'liq saqlaymiz (thoughtSignature'lar bilan birga)
|
|
353
|
+
self.contents.append(content)
|
|
354
|
+
said = "".join(p.get("text", "") for p in content["parts"] if not p.get("thought"))
|
|
355
|
+
if said.strip():
|
|
356
|
+
on_text(said)
|
|
357
|
+
calls = [p["functionCall"] for p in content["parts"] if "functionCall" in p]
|
|
358
|
+
if not calls:
|
|
359
|
+
return
|
|
360
|
+
results = []
|
|
361
|
+
for call in calls:
|
|
362
|
+
result = run_tool(call.get("name", ""), dict(call.get("args") or {}))
|
|
363
|
+
response_part: dict[str, Any] = {"name": call.get("name", ""), "response": result}
|
|
364
|
+
if call.get("id"):
|
|
365
|
+
response_part["id"] = call["id"]
|
|
366
|
+
# view_file: rasm/PDF ni asbob natijasiga biriktiramiz, model uni ko'radi
|
|
367
|
+
pop = getattr(run_tool, "pop_attachments", None)
|
|
368
|
+
files = pop() if pop else []
|
|
369
|
+
if files:
|
|
370
|
+
response_part["parts"] = [
|
|
371
|
+
{"inlineData": {"mimeType": mime, "data": base64.b64encode(data).decode("ascii"),
|
|
372
|
+
"displayName": Path(path).name}}
|
|
373
|
+
for mime, data, path in files
|
|
374
|
+
]
|
|
375
|
+
results.append({"functionResponse": response_part})
|
|
376
|
+
self.contents.append({"role": "user", "parts": results})
|
|
377
|
+
on_text("_(Juda ko'p qadam bo'ldi, to'xtatdim. Davom etishni xohlasangiz, yozing.)_")
|
|
378
|
+
except BaseException:
|
|
379
|
+
# Xato yoki Ctrl+C: tarixni so'rovdan oldingi holatga qaytaramiz
|
|
380
|
+
del self.contents[start:]
|
|
381
|
+
raise
|
zon7/safety.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Xavfli buyruqlarni aniqlash. AI baholashiga qo'shimcha, mahalliy tekshiruv."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
LEVELS = ("safe", "caution", "danger")
|
|
8
|
+
|
|
9
|
+
DANGER_PATTERNS = [
|
|
10
|
+
(r"\brm\s+(-[a-zA-Z]*[rf][a-zA-Z]*\s+)+(/|~|\$HOME|\*|/\*)(\s|$)", "tizim yoki uy papkasini o'chirish"),
|
|
11
|
+
(r"\bmkfs(\.\w+)?\b", "diskni formatlash"),
|
|
12
|
+
(r"\bdd\b.*\bof=/dev/", "diskka to'g'ridan-to'g'ri yozish"),
|
|
13
|
+
(r">\s*/dev/(sd|nvme|disk|hd)", "diskka to'g'ridan-to'g'ri yozish"),
|
|
14
|
+
(r":\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:", "fork bomba"),
|
|
15
|
+
(r"\bchmod\s+(-R\s+)?[0-7]*777\s+/(\s|$)", "butun tizimga ruxsat ochish"),
|
|
16
|
+
(r"\b(curl|wget)\b[^|]*\|\s*(sudo\s+)?(ba|z|)sh\b", "internetdan skriptni to'g'ridan-to'g'ri ishga tushirish"),
|
|
17
|
+
(r"\bdrop\s+(database|table)\b", "ma'lumotlar bazasini o'chirish"),
|
|
18
|
+
(r"\bgit\s+push\b.*(--force\b|-f\b)", "masofaviy tarixni qayta yozish"),
|
|
19
|
+
(r"\bgit\s+reset\s+--hard\b", "saqlanmagan o'zgarishlarni yo'qotish"),
|
|
20
|
+
(r"\b(shutdown|reboot|halt|poweroff)\b", "kompyuterni o'chirish/qayta yoqish"),
|
|
21
|
+
(r"\bformat\s+[a-zA-Z]:", "diskni formatlash (Windows)"),
|
|
22
|
+
(r"\bRemove-Item\b.*-Recurse\b.*-Force\b", "rekursiv majburiy o'chirish (PowerShell)"),
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
CAUTION_PATTERNS = [
|
|
26
|
+
(r"\bsudo\b", "administrator huquqi bilan"),
|
|
27
|
+
(r"\brm\b", "fayllarni o'chiradi"),
|
|
28
|
+
(r"\bkill(all)?\b|\bpkill\b", "jarayonlarni to'xtatadi"),
|
|
29
|
+
(r"\bchmod\b|\bchown\b", "ruxsatlarni o'zgartiradi"),
|
|
30
|
+
(r"\bmv\b", "fayllarni ko'chiradi yoki ustidan yozadi"),
|
|
31
|
+
(r"(^|[^>])>(?!>)\s*\S", "faylning ustidan yozadi"),
|
|
32
|
+
(r"\b(npm|pnpm|yarn|pip|brew|apt(-get)?|dnf|pacman)\s+(uninstall|remove|purge)\b", "paketni o'chiradi"),
|
|
33
|
+
(r"\bdocker\s+(system\s+prune|rm|rmi|volume\s+rm)\b", "Docker resurslarini o'chiradi"),
|
|
34
|
+
(r"\bgit\s+(clean|checkout\s+--|restore)\b", "lokal o'zgarishlarni bekor qiladi"),
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
HARMLESS_REDIRECTS = re.compile(r"(\d*|&)>>?\s*/dev/null\b|\d*>&\d+|<\s*/dev/null\b")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def assess(command: str) -> tuple[str, list[str]]:
|
|
42
|
+
"""Buyruqni baholaydi: (daraja, sabablar)."""
|
|
43
|
+
reasons: list[str] = []
|
|
44
|
+
for pattern, reason in DANGER_PATTERNS:
|
|
45
|
+
if re.search(pattern, command, re.IGNORECASE):
|
|
46
|
+
reasons.append(reason)
|
|
47
|
+
if reasons:
|
|
48
|
+
return "danger", reasons
|
|
49
|
+
# Zararsiz yo'naltirishlar (chiqishni yashirish, stderr→stdout) faylni o'zgartirmaydi
|
|
50
|
+
harmless = HARMLESS_REDIRECTS.sub(" ", command)
|
|
51
|
+
for pattern, reason in CAUTION_PATTERNS:
|
|
52
|
+
if re.search(pattern, harmless, re.IGNORECASE):
|
|
53
|
+
reasons.append(reason)
|
|
54
|
+
return ("caution" if reasons else "safe"), reasons
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def stricter(a: str, b: str) -> str:
|
|
58
|
+
"""Ikki darajadan qattiqrog'ini qaytaradi."""
|
|
59
|
+
ia = LEVELS.index(a) if a in LEVELS else 1
|
|
60
|
+
ib = LEVELS.index(b) if b in LEVELS else 1
|
|
61
|
+
return LEVELS[max(ia, ib)]
|