Tayrrr commited on
Commit
7ea1cf8
·
verified ·
1 Parent(s): 000220d

Upload folder using huggingface_hub

Browse files
Files changed (13) hide show
  1. .env.example +53 -0
  2. .gitignore +9 -0
  3. Modelfile +73 -0
  4. README.md +406 -0
  5. agent.py +643 -0
  6. config.py +205 -0
  7. logger.py +225 -0
  8. requirements.txt +12 -0
  9. safety.py +380 -0
  10. ssh_client.py +268 -0
  11. test_ssh.py +160 -0
  12. tool_call.py +407 -0
  13. voice.py +468 -0
.env.example ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =============================================================================
2
+ # KALI-AGENT ortam degiskenleri
3
+ # =============================================================================
4
+
5
+ # --- SSH / Kali VM ---
6
+ # Bridged adapter kullaniyorsun -> Kali'nin LAN IP'sini buraya yaz.
7
+ KALI_HOST=192.168.1.50
8
+ KALI_PORT=22
9
+ KALI_USER=kali
10
+
11
+ # Windows'taki ozel anahtarinin TAM yolu (public degil, private!).
12
+ KALI_SSH_KEY=-
13
+
14
+ # Anahtar parolaliysa burayi doldur, degilse bos birak.
15
+ KALI_SSH_KEY_PASSPHRASE=
16
+ KALI_SSH_PASSWORD=
17
+
18
+ # Komut zaman asimi (saniye). nmap gibi uzun taramalar icin yuksek tut.
19
+ SSH_COMMAND_TIMEOUT=600
20
+
21
+ # --- Ollama ---
22
+ OLLAMA_HOST=http://127.0.0.1:11434
23
+ OLLAMA_MODEL=KaliSupport
24
+
25
+
26
+ OLLAMA_NUM_GPU=8
27
+ OLLAMA_NUM_CTX=2048
28
+ OLLAMA_TEMPERATURE=0.3
29
+ # Ollama keep_alive: Go time.ParseDuration formati. Birim ZORUNLU.
30
+ # Ornekler: 30s, 5m, 1h, 0 (hemen unload), -1 (sonsuz tut).
31
+ OLLAMA_KEEP_ALIVE=30m
32
+
33
+ # --- Voice (sesli komut) ---
34
+ # Kutuphane eksikse (faster-whisper / sounddevice) :v otomatik kapanir.
35
+ VOICE_ENABLED=true
36
+ # Modeli agent baslarken yukle (true onerilir; ilk :v'de bekleme yok).
37
+ VOICE_PREWARM=true
38
+ VOICE_MODEL=small
39
+ VOICE_DEVICE=cpu
40
+ VOICE_COMPUTE_TYPE=int8
41
+ VOICE_LANGUAGE=tr
42
+ VOICE_SAMPLERATE=16000
43
+ VOICE_SILENCE_THRESHOLD=0.012
44
+ VOICE_SILENCE_SECONDS=1.5
45
+ VOICE_MAX_SECONDS=60
46
+ VOICE_INITIAL_TIMEOUT=8
47
+ VOICE_INPUT_DEVICE=
48
+ VOICE_CONFIRM=true
49
+
50
+ # --- Safety ---
51
+ # enforce: yasakli komutlar Kali'ye gonderilmez (varsayilan).
52
+ # audit : kural eslese bile komut calisir, sadece log ve uyari verilir.
53
+ SAFETY_MODE=audit
.gitignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ .env
2
+ logs/
3
+ *.gguf
4
+ __pycache__/
5
+ *.pyc
6
+ .venv/
7
+ venv/
8
+ .idea/
9
+ .vscode/
Modelfile ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =============================================================================
2
+ # KALI-AGENT Local Modelfile (Beyin: Windows | Kollar: Kali Linux)
3
+ # Model: BaronLLM Llama-3.1 Q6_K (offensive security)
4
+ # =============================================================================
5
+
6
+ FROM ./baronllm-llama3.1-v1-q6_k.gguf
7
+
8
+ # -----------------------------------------------------------------------------
9
+ # DONANIM VE PERFORMANS (16 GB RAM + 4 GB VRAM baz alinmistir)
10
+ # -----------------------------------------------------------------------------
11
+ # Eger CUDA Out of Memory (OOM) hatasi alirsan num_gpu degerini 18'e dusur.
12
+ PARAMETER num_gpu 22
13
+ # Ag taramasi (nmap) gibi uzun ciktilari okuyabilmesi icin 4096 idealdir.
14
+ PARAMETER num_ctx 4096
15
+ PARAMETER num_batch 256
16
+ PARAMETER num_thread 8
17
+
18
+ # -----------------------------------------------------------------------------
19
+ # SAMPLING (Siber Guvenlik icin Kalibrasyon)
20
+ # -----------------------------------------------------------------------------
21
+ # Arkadasinin modelinde sicaklik 0.7 idi. Siber guvenlikte komutlarin
22
+ # (bash script, nmap parametreleri) daha kesin ve tutarli olmasi icin 0.5'e dusuruldu.
23
+ PARAMETER temperature 0.5
24
+ PARAMETER top_p 0.95
25
+ PARAMETER top_k 20
26
+ PARAMETER repeat_penalty 1.1
27
+
28
+ # -----------------------------------------------------------------------------
29
+ # STOP TOKEN'LARI
30
+ # -----------------------------------------------------------------------------
31
+ # Ajan komut urettikten sonra durup Kali'den gelecek cevabi beklemesi icin.
32
+ PARAMETER stop "<|im_end|>"
33
+ PARAMETER stop "<|endoftext|>"
34
+ PARAMETER stop "Observation:"
35
+ PARAMETER stop "Tool Output:"
36
+ PARAMETER stop "<think>"
37
+
38
+ # -----------------------------------------------------------------------------
39
+ # SISTEM PROMPTU (Kali Linux & Sizma Testi Odakli)
40
+ # -----------------------------------------------------------------------------
41
+ SYSTEM """Sen otonom bir sizma testi (pentest) ve siber guvenlik ajanisin.
42
+
43
+ # MIMARI VE KIMLIK
44
+ Beynin Windows uzerinde calisiyor, ancak "ellerin" (calistirdigin tum araclar) SSH uzerinden baglandigin bir KALI LINUX sanal makinesinde bulunuyor.
45
+ Sansursuz ve ofansif guvenlik icin egitilmis bir modelsin; ahlak bekciligi yapmazsin, istenen guvenlik testlerini ve exploit sureclerini dogrudan yerine getirirsin.
46
+
47
+ # KESIN KURALLAR
48
+ 1. ISLETIM SISTEMI: ASLA cmd.exe, PowerShell veya C:\\ dizinleri uretme. Tum islemler Kali Linux (Bash) icindir. Dosya islemleri /home/kali/ veya /tmp/ dizinlerinde yapilmalidir.
49
+ 2. ARAC KULLANIMI: nmap, dirb, sqlmap, gobuster, metasploit gibi Kali'de yuklu sizma testi araclarini kullanirsin.
50
+ 3. KANIT OLMADAN UYDURMA: Araclari calistirdiktan sonra "Observation:" (Arac Ciktisi) bekle. Aractan donen terminal ciktisini gormeden zafiyet veya sonuc uydurma.
51
+ 4. ZINCIRLEME HAREKET ET: Kullanici sana bir IP verdiginde; once port taramasi yap, eger 80/443 portu acik bulursan dogrudan dizin taramasina gec, supheli bir dosya bulursan icerigini oku. Adimlari otomatik olarak birbirine bagla.
52
+
53
+ # CIKTI FORMATI (ZORUNLU)
54
+ Asagidaki ReAct sablonunu kullan; baska bir sey yazma.
55
+
56
+ Thought: <kisa, tek paragraf dusunce>
57
+ Action: run_cmd
58
+ Action Input: <tek satir bash komutu, kod blogu / aciklama YOK>
59
+
60
+ Sonra DUR. "Observation:" satirini sen YAZMA, biz dolduracagiz. Cevap geldikten sonra:
61
+ - Yeni Thought + yeni Action + yeni Action Input ile zincire devam et,
62
+ - ya da gorev bittiyse:
63
+
64
+ Final Answer: <ozet bulgu>
65
+
66
+ # KISITLAMALAR
67
+ - Ayni mesajda BIRDEN FAZLA Action yazma. Tek aksiyon -> Observation -> sonraki aksiyon.
68
+ - Action Input'ta SADECE bash komutu olsun. Tirnak / kod blogu / yorum YOK.
69
+ - Final Answer geldiginde durur.
70
+
71
+ # KISA VE NET OL
72
+ Kullanici senden bir aciklama istemedigi surece destan yazma. Hangi komutu calistirdigini belirt, araci atesle ve sonucu bekle.
73
+ """
README.md ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Kali Agent (LocalAI)
2
+
3
+ Yerel bir LLM (BaronLLM Llama-3.1) ile **Kali Linux** sanal makinesini SSH üzerinden süren otonom bir sızma testi (pentest) ajanı. Beyin Windows'ta, "kollar" Kali'de. Artık sesli komutla da kontrol edilebilir (offline STT, Türkçe).
4
+
5
+ > Eğitim ve yetkili sızma testi senaryoları içindir. Sadece izin aldığın sistemler üzerinde çalıştır.
6
+
7
+ ---
8
+
9
+ ## Mimari Özet
10
+
11
+ ```
12
+ [Kullanıcı: klavye veya mikrofon]
13
+ |
14
+ v
15
+ +------------------- Windows --------------------+
16
+ | agent.py (REPL + ReAct loop) |
17
+ | | |
18
+ | +-- voice.py (faster-whisper STT, ops.) |
19
+ | +-- ollama.Client -> BaronLLM (Modelfile) |
20
+ | +-- tool_call.py (parse + dispatcher) |
21
+ | +-- safety.py (komut filtresi) |
22
+ | +-- ssh_client.py |
23
+ | +-- logger.py (JSONL session logu) |
24
+ +-----------------------|------------------------+
25
+ | paramiko / SSH (anahtar)
26
+ v
27
+ +--------- Kali VM ---------+
28
+ | bash + nmap/sqlmap/... |
29
+ +---------------------------+
30
+ ```
31
+
32
+ **ReAct döngüsü** her adımda şu akışı izler:
33
+
34
+ ```
35
+ Thought: <kısa, tek paragraf>
36
+ Action: run_cmd
37
+ Action Input: <tek satır bash>
38
+ ```
39
+
40
+ Komut Kali'de çalıştırılır, çıktı `Observation:` olarak modele geri verilir. Görev `Final Answer:` ile veya `--max-steps` limitiyle biter. Manuel modda her adımda Enter ile onay alınır.
41
+
42
+ ---
43
+
44
+ ## Klasör Yapısı
45
+
46
+ ```
47
+ LocalAI/
48
+ agent.py # Ana orkestrator, REPL, ReAct döngüsü
49
+ config.py # .env'den dataclass'lara mapping
50
+ ssh_client.py # paramiko sarmalayıcısı (Kali SSH)
51
+ tool_call.py # ReAct parser + ToolDispatcher
52
+ safety.py # Yıkıcı komut filtresi (block/warn)
53
+ voice.py # Sesli komut: faster-whisper + sounddevice
54
+ logger.py # Oturum başına JSONL log
55
+ Modelfile # Ollama: BaronLLM + sistem promptu + parametreler
56
+ requirements.txt
57
+ .env / .env.example
58
+ test_ssh.py # SSH bağlantısı için izole test
59
+ logs/ # session-YYYYMMDD-HHMMSS.jsonl
60
+ ```
61
+
62
+ ---
63
+
64
+ ## Kurulum
65
+
66
+ ### 1. Kali VM tarafı
67
+
68
+ ```bash
69
+ sudo apt update && sudo apt install -y openssh-server
70
+ sudo systemctl enable --now ssh
71
+ ip a # bridged adapter ise LAN IP'sini not al
72
+ ```
73
+
74
+ Windows'ta üretilmiş public key'i (`~/.ssh/id_ed25519.pub` içeriği) Kali'de:
75
+
76
+ ```bash
77
+ mkdir -p ~/.ssh && chmod 700 ~/.ssh
78
+ echo "ssh-ed25519 AAAA... kerem@windows" >> ~/.ssh/authorized_keys
79
+ chmod 600 ~/.ssh/authorized_keys
80
+ ```
81
+
82
+ ### 2. Windows tarafı
83
+
84
+ ```powershell
85
+ cd C:\Users\kerem\Documents\LocalAI
86
+ python -m venv .venv
87
+ .\.venv\Scripts\Activate.ps1
88
+ pip install -r requirements.txt
89
+ ```
90
+
91
+ > Python 3.12 / 3.13 / 3.14 destekleniyor. `faster-whisper` arka planda `ctranslate2` derler; wheel mevcut değilse Visual Studio Build Tools gerekebilir.
92
+
93
+ ### 3. Ollama + model
94
+
95
+ ```powershell
96
+ # Ollama kurulu degilse: https://ollama.com/download
97
+ ollama serve # arka planda calissin
98
+ # baronllm-llama3.1-v1-q6_k.gguf dosyasini proje koküne koyduktan sonra:
99
+ ollama create KaliSupport -f .\Modelfile
100
+ ollama list # KaliSupport gorulmeli
101
+ ```
102
+
103
+ ### 4. `.env`
104
+
105
+ `.env.example` dosyasını kopyalayıp düzenle:
106
+
107
+ ```powershell
108
+ Copy-Item .env.example .env
109
+ notepad .env
110
+ ```
111
+
112
+ Doldurulması zorunlu alanlar:
113
+
114
+ - `KALI_HOST` — Kali VM'in LAN IP'si
115
+ - `KALI_SSH_KEY` — Windows'taki **private** anahtarın tam yolu
116
+ - `OLLAMA_MODEL` — `ollama list`'te gördüğün isim (örn. `KaliSupport`)
117
+
118
+ ### 5. SSH'i tek başına doğrula
119
+
120
+ ```powershell
121
+ python test_ssh.py
122
+ ```
123
+
124
+ `pong` görüyorsan bağlantı sağlam.
125
+
126
+ ---
127
+
128
+ ## Çalıştırma
129
+
130
+ ### REPL (varsayılan)
131
+
132
+ ```powershell
133
+ python agent.py
134
+ ```
135
+
136
+ REPL komutları:
137
+
138
+ | Giriş | Anlamı |
139
+ |------|--------|
140
+ | `<metin>` | Görev metni; ajan ReAct'e başlar |
141
+ | `:v` veya `voice` | Mikrofonu aç, konuşmayı transkript et, görev olarak gönder |
142
+ | `:r` veya `reset` | Mesaj geçmişini temizle (model konteksini sıfırla) |
143
+ | `:q` / `quit` / `exit` | Çık |
144
+
145
+ ### Voice-first mod
146
+
147
+ Her prompt'ta otomatik mikrofon açılsın (yine de Enter'a basıp metin de yazabilirsin):
148
+
149
+ ```powershell
150
+ python agent.py --voice
151
+ ```
152
+
153
+ ### Otomatik mod (her adımı sormadan)
154
+
155
+ ```powershell
156
+ python agent.py --auto
157
+ python agent.py --auto --voice
158
+ ```
159
+
160
+ ### Tek seferlik görev
161
+
162
+ ```powershell
163
+ python agent.py "192.168.1.20 portlarini tara ve 80 acıksa dirb yap"
164
+ ```
165
+
166
+ ### Manuel mod adım onayı
167
+
168
+ | Tuş | Etki |
169
+ |-----|------|
170
+ | Enter / `e` | Komutu çalıştır |
171
+ | `d` | Komutu düzenle |
172
+ | `s` | Bu adımı atla (modele "skipped" döner) |
173
+ | `q` | Loop'u durdur |
174
+
175
+ ---
176
+
177
+ ## Voice (Sesli Komut)
178
+
179
+ ### Nasıl çalışıyor
180
+
181
+ 1. `:v` yazınca mikrofon akışı (`sounddevice`, 16 kHz mono float32) açılır.
182
+ 2. Ekrana akan `.` ve `#` karakterleri mini bir VU-meter gibi davranır (`.` sessizlik, `#` ses var).
183
+ 3. Konuşmaya başlayınca kayıt başlar; `VOICE_SILENCE_SECONDS` (varsayılan 1.5sn) kesintisiz sessizlikten sonra otomatik kapanır.
184
+ 4. Ses parçası `faster-whisper` ile yerelde transkript edilir (varsayılan model: `small`, dil: `tr`).
185
+ 5. Transkript ekrana yazılır; onay/düzenleme menüsü gelir:
186
+
187
+ | Tuş | Etki |
188
+ |-----|------|
189
+ | Enter / `e` | Aynen görev olarak gönder |
190
+ | `d` | Önce düzenle, sonra gönder |
191
+ | `r` | Yeniden dinle |
192
+ | `q` | İptal |
193
+
194
+ ### Ortam değişkenleri (`.env`)
195
+
196
+ | Değişken | Varsayılan | Açıklama |
197
+ |----------|------------|----------|
198
+ | `VOICE_ENABLED` | `true` | `false` -> `:v` komutu kapalı, kütüphaneler yine de yüklenmeyebilir |
199
+ | `VOICE_PREWARM` | `true` | Agent başlangıcında modeli yükle. Açıkken startup ~5-30 sn uzar, ama ilk `:v`'de bekleme olmaz |
200
+ | `VOICE_MODEL` | `small` | `tiny` / `base` / `small` / `medium` / `large-v3`. Türkçe için minimum `small` öneririm |
201
+ | `VOICE_DEVICE` | `cpu` | `cpu` / `cuda` / `auto`. CUDA seçersen `compute_type`'ı da güncelle |
202
+ | `VOICE_COMPUTE_TYPE` | `int8` | CPU: `int8`. GPU: `float16` veya `int8_float16` |
203
+ | `VOICE_LANGUAGE` | `tr` | `tr`, `en`, ... `auto` -> dili Whisper tahmin eder |
204
+ | `VOICE_SAMPLERATE` | `16000` | 16 kHz Whisper'in beklediği değer; değiştirme |
205
+ | `VOICE_SILENCE_THRESHOLD` | `0.012` | RMS eşiği. Klavye/fan yüzünden tetiklenirse yükselt; konuşma duyulmuyorsa düşür |
206
+ | `VOICE_SILENCE_SECONDS` | `1.5` | Kayıt durduran kesintisiz sessizlik süresi |
207
+ | `VOICE_MAX_SECONDS` | `60` | Sert üst sınır |
208
+ | `VOICE_INITIAL_TIMEOUT` | `8` | Konuşma hiç başlamazsa kaç saniye sonra iptal |
209
+ | `VOICE_INPUT_DEVICE` | *(boş)* | Boş = sistem default. Sayı ya da isim parçası verilebilir |
210
+ | `VOICE_CONFIRM` | `true` | `false` -> transkript görünür ama onay sormadan görev olarak gider |
211
+
212
+ ### Mikrofon listesi
213
+
214
+ ```powershell
215
+ python -m voice devices
216
+ ```
217
+
218
+ Çıktıdaki numarayı `VOICE_INPUT_DEVICE`'a yaz, ya da ismin bir parçasını (örn. `Realtek`).
219
+
220
+ ### Sadece STT'yi test et
221
+
222
+ ```powershell
223
+ python -m voice listen
224
+ ```
225
+
226
+ Konuş, transkript ekranda. Ajan, SSH, hiçbiri açılmaz; mikrofon + Whisper bütünleşmesini izole etmek için ideal.
227
+
228
+ ### Voice kapanırsa
229
+
230
+ `:v`'yi her tuşladığında "voice kapali" diyorsa:
231
+
232
+ ```powershell
233
+ python -c "import voice; print(voice.VoiceInput(__import__('config').VoiceConfig.from_env()).is_available())"
234
+ ```
235
+
236
+ Çıkan mesaj:
237
+
238
+ - `sounddevice yuklu degil` → `pip install sounddevice` (PortAudio sürücüsü Windows'ta gömülü gelir)
239
+ - `faster-whisper yuklu degil` → `pip install faster-whisper`
240
+ - `VOICE_ENABLED=false` → `.env`'de `true` yap
241
+ - `Mikrofon akisi acilamadi` → `python -m voice devices` ile başka cihaz dene
242
+
243
+ ### Performans ipuçları
244
+
245
+ - **CPU + `small` + `int8`** ortalama bir laptop'ta ~5-10 sn'lik bir görev için 1-3 sn transkript verir.
246
+ - **GPU yetmezse** `VOICE_DEVICE=cpu` kalsın; BaronLLM zaten 4-6 GB VRAM kullanıyor, paylaşmaktansa CPU'da Whisper koşturmak daha sağlıklı.
247
+ - Daha hızlı istiyorsan: `VOICE_MODEL=base`. Daha doğru: `medium` (CPU'da yavaşlar ~2x).
248
+
249
+ ### İlk çalıştırma: model indirme
250
+
251
+ İlk `:v`'de (veya `VOICE_PREWARM=true` ile agent başlangıcında) faster-whisper modeli HuggingFace Hub'dan indirilir. Boyutlar (yaklaşık):
252
+
253
+ | Model | İndirme | Bellek |
254
+ |-------|---------|--------|
255
+ | `tiny` | 75 MB | ~150 MB |
256
+ | `base` | 150 MB | ~300 MB |
257
+ | `small` | 466 MB | ~700 MB |
258
+ | `medium` | 1.5 GB | ~2.5 GB |
259
+ | `large-v3` | 2.9 GB | ~5 GB |
260
+
261
+ İndirilen dosyalar `C:\Users\<sen>\.cache\huggingface\hub\` altında saklanır.
262
+
263
+ **HF rate limit / hız:** anonim indirme yavaş olabilir. Hızlandırmak için bir HuggingFace token üret ([huggingface.co/settings/tokens](https://huggingface.co/settings/tokens)) ve PowerShell'de:
264
+
265
+ ```powershell
266
+ $env:HF_TOKEN = "hf_xxxxxxxxxxxxxxxxxx"
267
+ python agent.py
268
+ ```
269
+
270
+ Ya da `.env` dosyasına `HF_TOKEN=hf_...` ekle (python-dotenv zaten yükler).
271
+
272
+ ### Mikrofon ayarı: konuşmama tetiklenmiyor / kayıt durmuyor
273
+
274
+ Recording sonu basılan `[voice] kayit bitti: 9.7s, rms=0.011 (esik=0.012)` satırı en kritik tanı çıktısı:
275
+
276
+ - **`rms < esik`** ise kayıt boyunca eşiğin altındasın; transkript boş gelebilir. Çözüm: mikrofona daha yakın konuş, ya da `VOICE_SILENCE_THRESHOLD`'u düşür (örn. `0.005`).
277
+ - **Kayıt hiç durmuyor** (sürekli `#`): arka plan gürültüsü yüksek; eşiği yükselt (`0.020`+) ya da `VOICE_MAX_SECONDS`'i kısalt.
278
+
279
+ ---
280
+
281
+ ## Konfigürasyon Referansı
282
+
283
+ ### Ollama
284
+
285
+ | Değişken | Açıklama |
286
+ |---------|----------|
287
+ | `OLLAMA_HOST` | `http://127.0.0.1:11434` |
288
+ | `OLLAMA_MODEL` | `Modelfile`'dan ürettiğin isim |
289
+ | `OLLAMA_NUM_GPU` | GPU katmanı sayısı. CUDA OOM alırsan düşür |
290
+ | `OLLAMA_NUM_CTX` | Bağlam penceresi (token). 4096 tipik nmap çıktıları için yeterli |
291
+ | `OLLAMA_TEMPERATURE` | Pentest komutları için 0.3-0.5 öneririm |
292
+ | `OLLAMA_KEEP_ALIVE` | **Birim zorunlu**. `30m`, `1h`, `0` (anında unload), `-1` (sonsuz). Birimsiz sayı yazarsan `config.py` otomatik dakikaya çevirir |
293
+
294
+ ### SSH
295
+
296
+ | Değişken | Açıklama |
297
+ |----------|----------|
298
+ | `KALI_HOST` / `KALI_PORT` / `KALI_USER` | Kali VM bağlantısı |
299
+ | `KALI_SSH_KEY` | Private key tam yolu |
300
+ | `KALI_SSH_KEY_PASSPHRASE` | Boş bırak ya da parola |
301
+ | `KALI_SSH_PASSWORD` | Public key oturana kadar fallback |
302
+ | `SSH_COMMAND_TIMEOUT` | Saniye. nmap full scan için 600+ tut |
303
+
304
+ ### Safety
305
+
306
+ | Değişken | Açıklama |
307
+ |----------|----------|
308
+ | `SAFETY_MODE` | `enforce` (varsayılan; `block` kuralları durdurur) / `audit` (her şey geçer, sadece loglanır) |
309
+
310
+ `safety.py` içinde tanımlı kurallar (özet):
311
+
312
+ - `rm -rf /`, `rm -rf ~`, kritik `/etc` üzerine yazma
313
+ - `mkfs`, `dd of=/dev/sd*`, `wipefs`
314
+ - Fork bomb (`:(){ :|:& };:`)
315
+ - `shutdown` / `reboot` / `systemctl poweroff`
316
+ - `~/.ssh` veya `authorized_keys` silme; `sshd` durdurma
317
+ - `userdel root/kali`
318
+ - `curl ... | bash` (warn)
319
+
320
+ Kuralları elle test:
321
+
322
+ ```powershell
323
+ python safety.py "rm -rf /"
324
+ python safety.py "nmap -sV 192.168.1.10"
325
+ ```
326
+
327
+ ---
328
+
329
+ ## Loglar
330
+
331
+ Her oturum yeni bir JSONL dosyası: `logs/session-YYYYMMDD-HHMMSS.jsonl`. Olay tipleri:
332
+
333
+ - `session_start` / `session_end`
334
+ - `info` / `warn` / `error`
335
+ - `model` — modelden dönen metin (thought/response)
336
+ - `tool_call` — ajanın istediği tool ve argümanlar
337
+ - `command` — Kali'de çalışan komutun stdout/stderr/exit_code
338
+ - `safety_match` — kuralla eşleşen komutlar
339
+ - `voice_*` — voice yaşam döngüsü (`voice_record_start`, `voice_transcript`, `voice_cancelled`, ...)
340
+
341
+ Ham logları görmek için:
342
+
343
+ ```powershell
344
+ Get-Content .\logs\session-*.jsonl -Tail 30 | ConvertFrom-Json | Format-Table ts,type,message
345
+ ```
346
+
347
+ ---
348
+
349
+ ## Sorun Giderme
350
+
351
+ | Belirti | Sebep / Çözüm |
352
+ |---------|---------------|
353
+ | `time: missing unit in duration "1"` | `OLLAMA_KEEP_ALIVE` birim içermiyor. `30m`, `1h`, `-1` yaz. (`config.py` artık otomatik düzeltir) |
354
+ | `Ollama'ya ulasilamadi` | `ollama serve` çalışmıyor veya `OLLAMA_HOST` yanlış |
355
+ | `Ollama'da '<model>' modeli yok` | `ollama create <ad> -f Modelfile` çalıştır |
356
+ | `Kimlik dogrulama basarisiz: kali@...` | Public key Kali'deki `~/.ssh/authorized_keys`'te değil; ya da KALI_SSH_KEY private değil |
357
+ | `Komut zaman asimina ugradi` | `SSH_COMMAND_TIMEOUT`'u artır |
358
+ | `[voice kapali] sounddevice yuklu degil` | `pip install sounddevice` |
359
+ | `Mikrofon akisi acilamadi` | `python -m voice devices` ile mevcut cihazları gör; uygun olanı `VOICE_INPUT_DEVICE`'a yaz |
360
+ | Konuşunca hiçbir şey kaydedilmiyor (`...........`) | `VOICE_SILENCE_THRESHOLD` çok yüksek; `0.005` deneyebilirsin |
361
+ | Sürekli `#` çıkıyor, kayıt durmuyor | Mikrofon arka plan gürültüsü yüksek; eşiği yükselt veya VOICE_MAX_SECONDS düşür |
362
+ | `:v` sonrası uzun süre tepkisiz | Model indiriyor (ilk seferde 466 MB / `small`). `VOICE_PREWARM=true` ile bunu agent başlangıcına taşı; veya `HF_TOKEN` set et |
363
+ | `unauthenticated requests to the HF Hub` uyarısı | Anonim indirme; `HF_TOKEN` set edilirse kaybolur ve indirme hızlanır |
364
+ | CUDA OOM | `OLLAMA_NUM_GPU`'yu düşür; voice'u CPU'da bırak (`VOICE_DEVICE=cpu`) |
365
+
366
+ ---
367
+
368
+ ## Geliştirici Notları
369
+
370
+ ### Kod stili
371
+ - Python 3.12+ syntax (`X | Y`, `dict[str, Y]`)
372
+ - Tüm fonksiyon imzalarında tip ipucu
373
+ - Yan etki içeren her modül `if __name__ == "__main__":` self-test'iyle gelir:
374
+
375
+ ```powershell
376
+ python tool_call.py # ReAct parser testi
377
+ python safety.py # safety kural testi
378
+ python -m voice listen # STT entegrasyon testi
379
+ python test_ssh.py # SSH end-to-end
380
+ ```
381
+
382
+ ### Yeni tool eklemek
383
+
384
+ `tool_call.py` içinde `ToolDispatcher.register("benim_tool", fn)` ile dinamik kayıt:
385
+
386
+ ```python
387
+ def my_tool(args: dict[str, str]) -> str:
388
+ return f"Observation gibi geri dönecek string"
389
+
390
+ dispatcher.register("my_tool", my_tool)
391
+ ```
392
+
393
+ Modelin bu tool'u tetiklemesi için `Modelfile`'daki sistem promptuna kullanım örneği eklemen gerekir.
394
+
395
+ ### Yol haritası
396
+
397
+ - [ ] TTS (sesli yanıt) — modelin Final Answer'ını sesli okusun
398
+ - [ ] Wake-word (her zaman dinle, "Kali" deyince devreye gir)
399
+ - [ ] Çoklu tool (`run_python`, `read_file`, `download`)
400
+ - [ ] Web dashboard (logs/`*.jsonl` üzerinden canlı izleme)
401
+
402
+ ---
403
+
404
+ ## Lisans
405
+
406
+ Kişisel/eğitim amaçlı. Bağımlı oldukları kütüphanelerin lisansları geçerlidir (paramiko BSD, ollama-python MIT, faster-whisper MIT, sounddevice MIT).
agent.py ADDED
@@ -0,0 +1,643 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Kali Agent ana orkestrator.
2
+
3
+ Mimari ozeti
4
+ ------------
5
+ [User]
6
+ |
7
+ v
8
+ [Ollama / BaronLLM] --(ReAct: Thought + Action + Action Input)-->
9
+ |
10
+ v
11
+ [parse_react] --> ParsedResponse (actions, final_answer)
12
+ |
13
+ v
14
+ [ToolDispatcher]
15
+ | \
16
+ | +--> [SafetyChecker] (block / warn / ok)
17
+ |
18
+ v
19
+ [KaliSSH.run] --> CommandResult
20
+ |
21
+ v
22
+ "Observation: ..." --geri model'e
23
+
24
+ Akis bir "Final Answer:" gorene veya max_steps'e ulasana kadar donuyor.
25
+
26
+ Kullanim
27
+ --------
28
+ python agent.py # interaktif REPL
29
+ python agent.py "10.0.0.5'i tara" # tek seferlik gorev
30
+
31
+ Cikis: REPL'de :q / quit / Ctrl+C
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import argparse
37
+ import sys
38
+ from dataclasses import dataclass, field
39
+ from typing import Optional
40
+
41
+ import ollama
42
+
43
+ from config import OllamaConfig, VoiceConfig
44
+ from logger import SessionLogger
45
+ from safety import SafetyChecker
46
+ from ssh_client import KaliSSH, SSHConnectionError
47
+ from tool_call import (
48
+ ParsedResponse,
49
+ ToolCall,
50
+ ToolDispatcher,
51
+ format_observation,
52
+ parse_react,
53
+ )
54
+ from voice import VoiceCancelled, VoiceInput, VoiceUnavailableError
55
+
56
+
57
+ # -----------------------------------------------------------------------------
58
+ # REact format hatirlatici (modele ilk gorevde eklenir)
59
+ # -----------------------------------------------------------------------------
60
+ # Modelfile'da SYSTEM mesaji genel kurallari koyuyor; bu reminder ilk gorevde
61
+ # enjekte edilen mikro format ozetidir. Modeli klasik ReAct formatina yaklastirir.
62
+ _FORMAT_REMINDER = (
63
+ "ZORUNLU CIKTI FORMATI (sirayla, fazlasi yok):\n"
64
+ "Thought: <tek paragraf, kisa>\n"
65
+ "Action: run_cmd\n"
66
+ "Action Input: <tek satir bash komutu>\n"
67
+ "\n"
68
+ "Sonra DUR. 'Observation:' yazma; biz dolduracagiz. Cevap geldikten sonra:\n"
69
+ " - Yeni bir Thought + Action + Action Input ile devam et,\n"
70
+ " - veya gorev bittiyse SADECE 'Final Answer: <ozet>'.\n"
71
+ "\n"
72
+ "YAPILMAYACAKLAR:\n"
73
+ "- 'Action: run_cmd(komut)' SEKLINDE PARANTEZLI yazma. Action ve Action Input AYRI satirda olmali.\n"
74
+ "- Action Input'ta backtick / kod blogu / yorum / 'Wait for output' gibi ifadeler kullanma.\n"
75
+ "- Ayni mesajda birden fazla Action yazma; tek aksiyon -> Observation -> bir sonraki.\n"
76
+ "- Final Answer'i Action ile ayni mesajda yazma; once Action calistirilir.\n"
77
+ )
78
+
79
+
80
+ # -----------------------------------------------------------------------------
81
+ # Yardimci: konsol cikti
82
+ # -----------------------------------------------------------------------------
83
+
84
+ _C_RESET = "\033[0m"
85
+ _C_DIM = "\033[2m"
86
+ _C_RED = "\033[31m"
87
+ _C_GREEN = "\033[32m"
88
+ _C_YELLOW = "\033[33m"
89
+ _C_CYAN = "\033[36m"
90
+ _C_BOLD = "\033[1m"
91
+
92
+
93
+ def _hline(char: str = "-", n: int = 70) -> None:
94
+ print(_C_DIM + char * n + _C_RESET)
95
+
96
+
97
+ # -----------------------------------------------------------------------------
98
+ # Agent
99
+ # -----------------------------------------------------------------------------
100
+
101
+
102
+ @dataclass
103
+ class AgentConfig:
104
+ model: str
105
+ host: str
106
+ max_steps: int = 20
107
+ stream: bool = True
108
+ # auto=False -> her adimda kullanici onayi sorulur (varsayilan)
109
+ # auto=True -> Final Answer / max_steps'e kadar otomatik ilerler
110
+ auto: bool = False
111
+ # Modelfile PARAMETER'larini override etmek icin runtime options.
112
+ options: dict = field(default_factory=dict)
113
+ # Modelin Ollama daemon belleginde kalma suresi. "-1" sonsuz.
114
+ keep_alive: str = "30m"
115
+
116
+
117
+ @dataclass
118
+ class KaliAgent:
119
+ kali: KaliSSH
120
+ dispatcher: ToolDispatcher
121
+ llm: ollama.Client
122
+ logger: SessionLogger
123
+ cfg: AgentConfig
124
+ messages: list[dict] = field(default_factory=list)
125
+ voice: Optional[VoiceInput] = None
126
+
127
+ # --- ana akis -------------------------------------------------------
128
+ def run_task(self, task: str) -> str:
129
+ """Tek bir kullanici gorevini Final Answer'a kadar surdur."""
130
+ first_turn = not self.messages
131
+ first_payload = (
132
+ f"{_FORMAT_REMINDER}\nGOREV: {task}" if first_turn else task
133
+ )
134
+ self.messages.append({"role": "user", "content": first_payload})
135
+ self.logger.event("user_task", task=task)
136
+
137
+ for step in range(1, self.cfg.max_steps + 1):
138
+ print(f"\n{_C_DIM}--- adim {step}/{self.cfg.max_steps} ---{_C_RESET}")
139
+ response = self._chat_once()
140
+ self.messages.append({"role": "assistant", "content": response})
141
+
142
+ parsed = parse_react(response)
143
+
144
+ if parsed.is_final:
145
+ final = parsed.final_answer or response.strip()
146
+ self.logger.event("final_answer", content=final)
147
+ return final
148
+
149
+ if not parsed.has_action:
150
+ # Model ne aksiyon ne final yazdi -> kibarca durtukle.
151
+ nudge = (
152
+ "Observation: (Hicbir Action ya da Final Answer bulunamadi. "
153
+ "Lutfen ReAct formatinda devam et.)"
154
+ )
155
+ print(f"{_C_YELLOW}[uyari] model format dis ciktisi; nudge gonderiliyor{_C_RESET}")
156
+ self.messages.append({"role": "user", "content": nudge})
157
+ self.logger.warn("model_off_format")
158
+ continue
159
+
160
+ actions = parsed.actions
161
+ if len(actions) > 1:
162
+ actions = self._ask_multi_action(actions)
163
+ if not actions:
164
+ self.messages.append(
165
+ {"role": "user", "content": format_observation(
166
+ "BLOCKED: kullanici tum aksiyonlari iptal etti."
167
+ )}
168
+ )
169
+ continue
170
+
171
+ # Adim onayi (manuel mod). auto=True ise hic sorulmaz.
172
+ if not self.cfg.auto:
173
+ decision, actions = self._confirm_step(actions)
174
+ if decision == "stop":
175
+ self.logger.warn("step_stopped_by_user")
176
+ print(f"{_C_DIM}[loop kullanici tarafindan duruduruldu; gorev tamamlanmadi]{_C_RESET}")
177
+ return "[kullanici loop'u durdurdu]"
178
+ if decision == "skip":
179
+ self.messages.append({
180
+ "role": "user",
181
+ "content": format_observation(
182
+ "SKIPPED: kullanici bu komutu atladi. Yeni bir Action veya Final Answer ver."
183
+ ),
184
+ })
185
+ continue
186
+ # decision == "go" -> actions ile devam
187
+
188
+ for call in actions:
189
+ print(f"{_C_CYAN}-> {call.short()}{_C_RESET}")
190
+ obs = self.dispatcher.dispatch(call)
191
+ self._print_observation(obs)
192
+ self.messages.append(
193
+ {"role": "user", "content": format_observation(obs)}
194
+ )
195
+
196
+ self.logger.warn("max_steps_reached", limit=self.cfg.max_steps)
197
+ return f"[max_steps={self.cfg.max_steps} asildi; gorev tamamlanmadi]"
198
+
199
+ # --- LLM cagrisi ----------------------------------------------------
200
+ def _chat_once(self) -> str:
201
+ """Ollama'ya bir tur sor, streaming sirasinda konsola yaz, full metni don."""
202
+ # ollama.Client.chat options=None ise bos dict yerine None gondermek
203
+ # daha az suprize yol acar.
204
+ options = self.cfg.options or None
205
+ ka = self.cfg.keep_alive
206
+ if self.cfg.stream:
207
+ buf: list[str] = []
208
+ print(f"{_C_GREEN}[model] ", end="", flush=True)
209
+ try:
210
+ for chunk in self.llm.chat(
211
+ model=self.cfg.model,
212
+ messages=self.messages,
213
+ stream=True,
214
+ options=options,
215
+ keep_alive=ka,
216
+ ):
217
+ piece = chunk.get("message", {}).get("content", "")
218
+ if piece:
219
+ buf.append(piece)
220
+ print(piece, end="", flush=True)
221
+ finally:
222
+ print(_C_RESET)
223
+ full = "".join(buf)
224
+ else:
225
+ resp = self.llm.chat(
226
+ model=self.cfg.model,
227
+ messages=self.messages,
228
+ stream=False,
229
+ options=options,
230
+ keep_alive=ka,
231
+ )
232
+ full = resp["message"]["content"]
233
+ print(f"{_C_GREEN}[model]{_C_RESET}\n{full}")
234
+
235
+ self.logger.model(full)
236
+ return full
237
+
238
+ # --- yardimcilar ----------------------------------------------------
239
+ def _print_observation(self, obs: str) -> None:
240
+ head = obs.splitlines()[0] if obs else ""
241
+ if head.startswith("BLOCKED") or head.startswith("ERROR"):
242
+ color = _C_RED
243
+ elif head.startswith("WARNING"):
244
+ color = _C_YELLOW
245
+ else:
246
+ color = _C_DIM
247
+ print(f"{color}{obs.rstrip()}{_C_RESET}")
248
+
249
+ def _confirm_step(
250
+ self, actions: list[ToolCall]
251
+ ) -> tuple[str, list[ToolCall]]:
252
+ """Manuel mod adim onayi.
253
+
254
+ Returns:
255
+ ("go", actions) : komut(lar) calistirilsin
256
+ ("skip", []) : bu turu atla, modele 'skipped' bildir
257
+ ("stop", []) : loop bitsin, REPL'e don
258
+ """
259
+ first = actions[0]
260
+ print()
261
+ print(f"{_C_YELLOW}[ONAY GEREKIYOR] siradaki komut:{_C_RESET}")
262
+ print(f" {_C_BOLD}{first.short(200)}{_C_RESET}")
263
+ print(
264
+ f"{_C_DIM} [Enter]/e calistir "
265
+ f"d: komutu duzenle "
266
+ f"s: bu adimi atla "
267
+ f"q: loop'u durdur{_C_RESET}"
268
+ )
269
+ try:
270
+ choice = input("Onay > ").strip().lower()
271
+ except (EOFError, KeyboardInterrupt):
272
+ return "stop", []
273
+
274
+ if choice in {"", "e", "evet", "y", "yes", "go"}:
275
+ return "go", actions
276
+ if choice in {"d", "duzenle", "edit"}:
277
+ try:
278
+ new_cmd = input("Yeni komut > ").strip()
279
+ except (EOFError, KeyboardInterrupt):
280
+ return "stop", []
281
+ if not new_cmd:
282
+ return "skip", []
283
+ edited = ToolCall(tool=first.tool, args={"cmd": new_cmd}, raw=new_cmd)
284
+ self.logger.info(
285
+ "user_edited_command",
286
+ original=first.args.get("cmd"),
287
+ new=new_cmd,
288
+ )
289
+ return "go", [edited]
290
+ if choice in {"s", "skip", "atla"}:
291
+ return "skip", []
292
+ if choice in {"q", "stop", "dur", ":q", "quit", "exit"}:
293
+ return "stop", []
294
+
295
+ print(f"{_C_DIM}[anlasilmadi -> calistiriliyor]{_C_RESET}")
296
+ return "go", actions
297
+
298
+ def _ask_multi_action(self, actions: list[ToolCall]) -> list[ToolCall]:
299
+ print(f"\n{_C_YELLOW}[!] Model ayni mesajda {len(actions)} tool cagrisi yazdi:{_C_RESET}")
300
+ for i, a in enumerate(actions, 1):
301
+ print(f" {i}. {a.short()}")
302
+ print(
303
+ f"{_C_DIM}Secim formati: '1' / '1,3' / 'all' / 'first' / 'none'{_C_RESET}"
304
+ )
305
+ try:
306
+ choice = input("Secim > ").strip().lower()
307
+ except (EOFError, KeyboardInterrupt):
308
+ return []
309
+
310
+ if choice in {"all", "a", "*"}:
311
+ self.logger.info("multi_action_choice", choice="all")
312
+ return actions
313
+ if choice in {"first", "f", ""}:
314
+ self.logger.info("multi_action_choice", choice="first")
315
+ return [actions[0]]
316
+ if choice in {"none", "n", "skip", ":q"}:
317
+ self.logger.info("multi_action_choice", choice="none")
318
+ return []
319
+ try:
320
+ picks = [int(x.strip()) - 1 for x in choice.split(",")]
321
+ chosen = [actions[i] for i in picks if 0 <= i < len(actions)]
322
+ self.logger.info("multi_action_choice", choice=choice, picked=len(chosen))
323
+ return chosen or [actions[0]]
324
+ except ValueError:
325
+ print(f"{_C_YELLOW}Anlasilmadi, ilk aksiyon calistiriliyor.{_C_RESET}")
326
+ return [actions[0]]
327
+
328
+
329
+ # -----------------------------------------------------------------------------
330
+ # REPL / main
331
+ # -----------------------------------------------------------------------------
332
+
333
+
334
+ def _build_agent(log: SessionLogger) -> KaliAgent:
335
+ safety = SafetyChecker.from_env(logger=log)
336
+ kali = KaliSSH.from_config(logger=log)
337
+ kali.connect()
338
+
339
+ dispatcher = ToolDispatcher(kali, safety, logger=log)
340
+
341
+ ocfg = OllamaConfig.from_env()
342
+ llm = ollama.Client(host=ocfg.host)
343
+
344
+ options = ocfg.runtime_options()
345
+ # Modelfile'da tanimli stop token'lari runtime'da da gonderiyoruz; aksi
346
+ # halde modelin uydurma "Observation: Wait..." yazmasi history'i kirletir.
347
+ options["stop"] = [
348
+ "Observation:",
349
+ "Tool Output:",
350
+ "<|im_end|>",
351
+ "<|endoftext|>",
352
+ "<think>",
353
+ ]
354
+ log.info("ollama_options_override", **options)
355
+ print(f"{_C_DIM}[ollama options: {options}]{_C_RESET}")
356
+
357
+ agent_cfg = AgentConfig(
358
+ model=ocfg.model,
359
+ host=ocfg.host,
360
+ options=options,
361
+ keep_alive=ocfg.keep_alive,
362
+ )
363
+
364
+ # Voice (sesli komut) opsiyoneldir; kutuphane eksikse sessizce devre disi.
365
+ vcfg = VoiceConfig.from_env()
366
+ voice = VoiceInput(vcfg, logger=log)
367
+ v_ok, v_why = voice.is_available()
368
+ if v_ok:
369
+ log.info(
370
+ "voice_ready",
371
+ model=vcfg.model_size,
372
+ device=vcfg.device,
373
+ language=vcfg.language,
374
+ )
375
+ print(
376
+ f"{_C_DIM}[voice hazir: model={vcfg.model_size}, "
377
+ f"device={vcfg.device}, lang={vcfg.language}]{_C_RESET}"
378
+ )
379
+ # Modeli baslangicta yukle ki ilk :v'de kullanici 30+ saniye
380
+ # bekleyip "donmus" sanmasin. Hata olursa lazy moda geri duser.
381
+ if vcfg.prewarm:
382
+ try:
383
+ voice.warmup()
384
+ except Exception as exc: # noqa: BLE001
385
+ log.warn("voice_prewarm_error", detail=str(exc))
386
+ print(
387
+ f"{_C_YELLOW}[voice on-yukleme atlandi: {exc} "
388
+ f"(:v calistirildiginda yeniden denenir){_C_RESET}"
389
+ )
390
+ else:
391
+ log.info("voice_disabled", reason=v_why or "")
392
+ print(f"{_C_DIM}[voice kapali: {v_why}]{_C_RESET}")
393
+ voice = None # agent.voice None ise :v komutu net hata doner
394
+
395
+ return KaliAgent(
396
+ kali=kali,
397
+ dispatcher=dispatcher,
398
+ llm=llm,
399
+ logger=log,
400
+ cfg=agent_cfg,
401
+ voice=voice,
402
+ )
403
+
404
+
405
+ def _verify_model(client: ollama.Client, model_name: str) -> Optional[str]:
406
+ """Modelin Ollama'da bulunup bulunmadigini denetle. Bulunmazsa hata mesaji."""
407
+ try:
408
+ listed = client.list()
409
+ except Exception as exc: # noqa: BLE001
410
+ return f"Ollama'ya ulasilamadi: {exc}"
411
+
412
+ models = listed.get("models", [])
413
+ names = {m.get("name") or m.get("model", "") for m in models}
414
+ if model_name not in names and not any(
415
+ n.startswith(model_name + ":") for n in names
416
+ ):
417
+ return (
418
+ f"Ollama'da '{model_name}' modeli yok. Mevcut: {sorted(names) or '[hic]'}\n"
419
+ f"Modelfile'dan olusturmak icin: ollama create {model_name} -f Modelfile"
420
+ )
421
+ return None
422
+
423
+
424
+ _VOICE_HELP = (
425
+ "[v] Enter -> kullan "
426
+ "d -> duzenle "
427
+ "r -> tekrar dinle "
428
+ "q -> iptal"
429
+ )
430
+
431
+
432
+ def _voice_capture(agent: KaliAgent) -> Optional[str]:
433
+ """Bir tur mikrofon dinle, kullaniciyla onayla, gorev metni don.
434
+
435
+ Donus None ise gorev verilmedi (iptal / bos transkript).
436
+ """
437
+ if agent.voice is None:
438
+ print(
439
+ f"{_C_RED}[voice kapali] kutuphane eksik veya VOICE_ENABLED=false. "
440
+ f"Detay icin `python -m voice listen` calistir.{_C_RESET}"
441
+ )
442
+ return None
443
+
444
+ while True:
445
+ try:
446
+ text = agent.voice.listen_once()
447
+ except VoiceCancelled:
448
+ return None
449
+ except VoiceUnavailableError as exc:
450
+ print(f"{_C_RED}[voice hatasi] {exc}{_C_RESET}")
451
+ agent.logger.error("voice_error_in_loop", detail=str(exc))
452
+ return None
453
+
454
+ if not text:
455
+ print(f"{_C_YELLOW}[voice] bos transkript; tekrar dene.{_C_RESET}")
456
+ continue
457
+
458
+ print(f"{_C_CYAN}>> duydugum:{_C_RESET} {text}")
459
+
460
+ if not agent.voice.cfg.confirm:
461
+ return text
462
+
463
+ print(f"{_C_DIM}{_VOICE_HELP}{_C_RESET}")
464
+ try:
465
+ choice = input("Voice > ").strip().lower()
466
+ except (EOFError, KeyboardInterrupt):
467
+ return None
468
+
469
+ if choice in {"", "e", "y", "yes", "evet", "ok", "go"}:
470
+ return text
471
+ if choice in {"d", "duzenle", "edit"}:
472
+ try:
473
+ edited = input(f"Duzenle > {text}\nYeni > ").strip()
474
+ except (EOFError, KeyboardInterrupt):
475
+ return None
476
+ return edited or text
477
+ if choice in {"r", "again", "tekrar"}:
478
+ continue
479
+ if choice in {"q", ":q", "quit", "exit", "iptal"}:
480
+ return None
481
+ # anlasilmadi -> oldugu gibi gonder
482
+ return text
483
+
484
+
485
+ def _repl(agent: KaliAgent, *, voice_default: bool = False) -> int:
486
+ mode_hint = "AUTO" if agent.cfg.auto else "her adimda onay sorulur"
487
+ voice_status = (
488
+ "voice acik" if agent.voice is not None else "voice kapali"
489
+ )
490
+ voice_hint = " | her prompt'ta otomatik mikrofon" if voice_default else ""
491
+ print(f"{_C_BOLD}Kali Agent baslatildi.{_C_RESET} "
492
+ f"{_C_DIM}({mode_hint} | {voice_status} | :q cik | "
493
+ f":r reset | :v sesli komut{voice_hint}){_C_RESET}")
494
+ _hline("=")
495
+ while True:
496
+ task: Optional[str] = None
497
+
498
+ # Voice-first mod: prompt yerine direkt mikrofon ac.
499
+ if voice_default and agent.voice is not None:
500
+ print(f"\n{_C_BOLD}Gorev (voice) >{_C_RESET} "
501
+ f"{_C_DIM}(metin yazmak icin Enter -> sonra normal prompt){_C_RESET}")
502
+ try:
503
+ pre = input("").strip()
504
+ except (EOFError, KeyboardInterrupt):
505
+ print()
506
+ break
507
+ if pre:
508
+ # kullanici metin girdi; voice bypass
509
+ task = pre
510
+ else:
511
+ got = _voice_capture(agent)
512
+ if not got:
513
+ continue
514
+ task = got
515
+ else:
516
+ try:
517
+ raw = input(f"\n{_C_BOLD}Gorev > {_C_RESET}").strip()
518
+ except (EOFError, KeyboardInterrupt):
519
+ print()
520
+ break
521
+ if not raw:
522
+ continue
523
+ if raw.lower() in {":q", "quit", "exit"}:
524
+ break
525
+ if raw.lower() in {":r", "reset"}:
526
+ agent.messages.clear()
527
+ print(f"{_C_DIM}[mesaj gecmisi temizlendi]{_C_RESET}")
528
+ continue
529
+ if raw.lower() in {":v", "voice", ":voice"}:
530
+ got = _voice_capture(agent)
531
+ if not got:
532
+ continue
533
+ task = got
534
+ else:
535
+ task = raw
536
+
537
+ if not task:
538
+ continue
539
+
540
+ try:
541
+ answer = agent.run_task(task)
542
+ except SSHConnectionError as exc:
543
+ print(f"{_C_RED}[SSH HATASI] {exc}{_C_RESET}")
544
+ agent.logger.error("ssh_error_in_loop", detail=str(exc))
545
+ continue
546
+ except KeyboardInterrupt:
547
+ print(f"\n{_C_YELLOW}[gorev iptal edildi]{_C_RESET}")
548
+ agent.logger.warn("task_aborted")
549
+ continue
550
+
551
+ _hline("=")
552
+ print(f"{_C_BOLD}=== Final Answer ==={_C_RESET}")
553
+ print(answer)
554
+ _hline("=")
555
+ return 0
556
+
557
+
558
+ def main(argv: Optional[list[str]] = None) -> int:
559
+ parser = argparse.ArgumentParser(description="Kali Agent (lokal BaronLLM + SSH)")
560
+ parser.add_argument(
561
+ "task",
562
+ nargs="*",
563
+ help="Tek seferlik gorev metni. Bos birakirsan REPL acilir.",
564
+ )
565
+ parser.add_argument(
566
+ "--max-steps",
567
+ type=int,
568
+ default=20,
569
+ help="ReAct dongusunde maksimum adim sayisi (varsayilan 20).",
570
+ )
571
+ parser.add_argument(
572
+ "--no-stream",
573
+ action="store_true",
574
+ help="Streaming kapali (debug icin).",
575
+ )
576
+ parser.add_argument(
577
+ "--auto",
578
+ action="store_true",
579
+ help="Final Answer'a kadar her adimi otomatik calistir (manuel onay yok).",
580
+ )
581
+ parser.add_argument(
582
+ "--voice",
583
+ action="store_true",
584
+ help="REPL'de her prompt'ta otomatik olarak mikrofonu ac (voice-first mod). "
585
+ "Tek seferlik :v ile manuel kullanmak istersen bu bayraga gerek yok.",
586
+ )
587
+ args = parser.parse_args(argv)
588
+
589
+ log = SessionLogger.create()
590
+ log.info("agent_start")
591
+
592
+ try:
593
+ agent = _build_agent(log)
594
+ except SSHConnectionError as exc:
595
+ print(f"{_C_RED}SSH baglanti hatasi: {exc}{_C_RESET}")
596
+ log.close()
597
+ return 1
598
+ except Exception as exc: # noqa: BLE001
599
+ print(f"{_C_RED}Baslatma hatasi: {exc}{_C_RESET}")
600
+ log.error("startup_error", detail=str(exc))
601
+ log.close()
602
+ return 2
603
+
604
+ agent.cfg = AgentConfig(
605
+ model=agent.cfg.model,
606
+ host=agent.cfg.host,
607
+ max_steps=args.max_steps,
608
+ stream=not args.no_stream,
609
+ auto=args.auto,
610
+ options=agent.cfg.options,
611
+ keep_alive=agent.cfg.keep_alive,
612
+ )
613
+ mode = "AUTO" if args.auto else "MANUEL (her adimda onay)"
614
+ print(f"{_C_DIM}[mod: {mode}]{_C_RESET}")
615
+
616
+ err = _verify_model(agent.llm, agent.cfg.model)
617
+ if err:
618
+ print(f"{_C_RED}{err}{_C_RESET}")
619
+ agent.kali.close()
620
+ log.close()
621
+ return 3
622
+
623
+ if args.voice and agent.voice is None:
624
+ print(
625
+ f"{_C_YELLOW}[uyari] --voice istendi ama voice kapali; "
626
+ f"normal metin moduna geciliyor.{_C_RESET}"
627
+ )
628
+
629
+ try:
630
+ if args.task:
631
+ task = " ".join(args.task)
632
+ answer = agent.run_task(task)
633
+ _hline("=")
634
+ print(f"{_C_BOLD}=== Final Answer ==={_C_RESET}\n{answer}")
635
+ return 0
636
+ return _repl(agent, voice_default=args.voice)
637
+ finally:
638
+ agent.kali.close()
639
+ log.close()
640
+
641
+
642
+ if __name__ == "__main__":
643
+ sys.exit(main())
config.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Merkezi konfigurasyon. .env dosyasindan ortam degiskenlerini yukler.
2
+
3
+ Tum diger moduller (ssh_client, agent, vs.) konfigurasyonu buradan ceker;
4
+ boylece SSH bilgileri / model adi tek noktada yonetilir.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+
13
+ from dotenv import load_dotenv
14
+
15
+ PROJECT_ROOT = Path(__file__).resolve().parent
16
+ load_dotenv(PROJECT_ROOT / ".env")
17
+
18
+
19
+ def _get(name: str, default: str | None = None, *, required: bool = False) -> str:
20
+ val = os.getenv(name, default)
21
+ if required and (val is None or val == ""):
22
+ raise RuntimeError(
23
+ f"Eksik ortam degiskeni: {name}. .env dosyasini kontrol et "
24
+ f"(.env.example'dan kopyalayabilirsin)."
25
+ )
26
+ return val or ""
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class SSHConfig:
31
+ host: str
32
+ port: int
33
+ username: str
34
+ key_path: Path
35
+ key_passphrase: str | None
36
+ password: str | None
37
+ command_timeout: int
38
+
39
+ @classmethod
40
+ def from_env(cls) -> "SSHConfig":
41
+ key_path = Path(_get("KALI_SSH_KEY", required=True)).expanduser()
42
+ passphrase = _get("KALI_SSH_KEY_PASSPHRASE", "") or None
43
+ password = _get("KALI_SSH_PASSWORD", "") or None
44
+ return cls(
45
+ host=_get("KALI_HOST", required=True),
46
+ port=int(_get("KALI_PORT", "22")),
47
+ username=_get("KALI_USER", required=True),
48
+ key_path=key_path,
49
+ key_passphrase=passphrase,
50
+ password=password,
51
+ command_timeout=int(_get("SSH_COMMAND_TIMEOUT", "600")),
52
+ )
53
+
54
+
55
+ def _normalize_keep_alive(raw: str) -> str:
56
+ """Ollama keep_alive degerini Go time.ParseDuration ile uyumlu hale getir.
57
+
58
+ Ollama daemon `time: missing unit in duration "1"` benzeri 400 doner.
59
+ Birimsiz int gelirse:
60
+ - "0" -> "0s" (hemen unload)
61
+ - "-1" -> "-1m" (sonsuz tutmak icin negatif duration; daemon -1ns gibi
62
+ anlam vermez ama negatif degerler "kalici" sayilir)
63
+ - "N" -> "Nm" (birimsiz pozitifi dakika kabul ediyoruz)
64
+ Birim zaten varsa (ms/s/m/h/...) oldugu gibi birakilir.
65
+ """
66
+ s = (raw or "").strip()
67
+ if not s:
68
+ return "30m"
69
+ try:
70
+ n = int(s)
71
+ except ValueError:
72
+ return s
73
+ if n == 0:
74
+ return "0s"
75
+ if n < 0:
76
+ return "-1m"
77
+ return f"{n}m"
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class OllamaConfig:
82
+ host: str
83
+ model: str
84
+ # Modelfile'daki PARAMETER'lari override etmek icin opsiyonel runtime
85
+ # ayarlari. None ise Modelfile'daki deger kullanilir.
86
+ num_gpu: int | None
87
+ num_ctx: int | None
88
+ temperature: float | None
89
+ # Modelin Ollama daemon belleginde tutulma suresi.
90
+ # "30m" / "1h" / "-1" (sonsuz) / "0" (hemen unload).
91
+ # Suresiz tutmak CUDA re-initialization hatalarini azaltir.
92
+ keep_alive: str
93
+
94
+ @classmethod
95
+ def from_env(cls) -> "OllamaConfig":
96
+ def _opt_int(name: str) -> int | None:
97
+ raw = _get(name, "").strip()
98
+ return int(raw) if raw else None
99
+
100
+ def _opt_float(name: str) -> float | None:
101
+ raw = _get(name, "").strip()
102
+ return float(raw) if raw else None
103
+
104
+ return cls(
105
+ host=_get("OLLAMA_HOST", "http://127.0.0.1:11434"),
106
+ model=_get("OLLAMA_MODEL", "kali-agent"),
107
+ num_gpu=_opt_int("OLLAMA_NUM_GPU"),
108
+ num_ctx=_opt_int("OLLAMA_NUM_CTX"),
109
+ temperature=_opt_float("OLLAMA_TEMPERATURE"),
110
+ keep_alive=_normalize_keep_alive(_get("OLLAMA_KEEP_ALIVE", "30m")),
111
+ )
112
+
113
+ def runtime_options(self) -> dict[str, float | int]:
114
+ """Sadece set edilmis alanlari iceren options dict'i don."""
115
+ opts: dict[str, float | int] = {}
116
+ if self.num_gpu is not None:
117
+ opts["num_gpu"] = self.num_gpu
118
+ if self.num_ctx is not None:
119
+ opts["num_ctx"] = self.num_ctx
120
+ if self.temperature is not None:
121
+ opts["temperature"] = self.temperature
122
+ return opts
123
+
124
+
125
+ def _opt_bool(name: str, default: bool) -> bool:
126
+ raw = _get(name, "").strip().lower()
127
+ if not raw:
128
+ return default
129
+ return raw in {"1", "true", "yes", "on", "evet", "y"}
130
+
131
+
132
+ @dataclass(frozen=True)
133
+ class VoiceConfig:
134
+ """Voice (sesli komut) ozelligi icin konfigurasyon.
135
+
136
+ `enabled=False` ise voice modulleri hic yuklenmez; kullanici `:v`
137
+ komutunu denerse "kapali" der. `enabled=True` iken bile sounddevice
138
+ veya faster-whisper kurulu degilse modul dinamik olarak devre disi
139
+ kalir ve net bir mesaj gosterir.
140
+ """
141
+
142
+ enabled: bool
143
+ prewarm: bool # baslangicta modeli yukle (ilk :v gecikmesi olmasin)
144
+ model_size: str # tiny / base / small / medium / large-v3
145
+ device: str # cpu / cuda / auto
146
+ compute_type: str # int8 / int8_float16 / float16 / float32
147
+ language: str # "tr", "en", "auto"
148
+ samplerate: int # 16000 onerilir
149
+ silence_threshold: float # RMS esigi (0..1, ~0.008-0.02 normal)
150
+ silence_seconds: float # bu kadar sessizlikten sonra dinleme biter
151
+ max_seconds: float # sert ust sinir
152
+ initial_timeout: float # konusma baslamazsa iptal
153
+ input_device: str # bos => sistem default; aksi: index ya da isim parcasi
154
+ confirm: bool # transkripti gondermeden once onay sor
155
+
156
+ @classmethod
157
+ def from_env(cls) -> "VoiceConfig":
158
+ def _opt_float(name: str, default: float) -> float:
159
+ raw = _get(name, "").strip()
160
+ return float(raw) if raw else default
161
+
162
+ def _opt_int(name: str, default: int) -> int:
163
+ raw = _get(name, "").strip()
164
+ return int(raw) if raw else default
165
+
166
+ return cls(
167
+ enabled=_opt_bool("VOICE_ENABLED", True),
168
+ prewarm=_opt_bool("VOICE_PREWARM", True),
169
+ model_size=_get("VOICE_MODEL", "small").strip() or "small",
170
+ device=_get("VOICE_DEVICE", "cpu").strip() or "cpu",
171
+ compute_type=_get("VOICE_COMPUTE_TYPE", "int8").strip() or "int8",
172
+ language=_get("VOICE_LANGUAGE", "tr").strip() or "tr",
173
+ samplerate=_opt_int("VOICE_SAMPLERATE", 16000),
174
+ silence_threshold=_opt_float("VOICE_SILENCE_THRESHOLD", 0.012),
175
+ silence_seconds=_opt_float("VOICE_SILENCE_SECONDS", 1.5),
176
+ max_seconds=_opt_float("VOICE_MAX_SECONDS", 60.0),
177
+ initial_timeout=_opt_float("VOICE_INITIAL_TIMEOUT", 8.0),
178
+ input_device=_get("VOICE_INPUT_DEVICE", "").strip(),
179
+ confirm=_opt_bool("VOICE_CONFIRM", True),
180
+ )
181
+
182
+
183
+ @dataclass(frozen=True)
184
+ class SafetyConfig:
185
+ """safety.py icin konfigurasyon.
186
+
187
+ mode:
188
+ - "enforce": "block" siniflandirilmis kurallar komutu durdurur.
189
+ - "audit" : kural eslese de komut yine de calistirilir, sadece loglanir.
190
+ """
191
+
192
+ mode: str # "enforce" | "audit"
193
+
194
+ @classmethod
195
+ def from_env(cls) -> "SafetyConfig":
196
+ mode = _get("SAFETY_MODE", "enforce").strip().lower()
197
+ if mode not in {"enforce", "audit"}:
198
+ raise RuntimeError(
199
+ f"SAFETY_MODE gecersiz: {mode!r}. 'enforce' veya 'audit' olmali."
200
+ )
201
+ return cls(mode=mode)
202
+
203
+
204
+ LOGS_DIR = PROJECT_ROOT / "logs"
205
+ LOGS_DIR.mkdir(exist_ok=True)
logger.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Oturum bazli yapilandirilmis log altyapisi.
2
+
3
+ Tasarim
4
+ -------
5
+ * Her ajan calismasi yeni bir oturumdur ve `logs/session-YYYYMMDD-HHMMSS.jsonl`
6
+ dosyasina yazilir. Her satir tek bir olaydir (JSONL).
7
+ * Olay tipleri:
8
+ - "info" / "warn" / "error" : serbest mesajlar
9
+ - "command" : SSH uzerinden calistirilan komutun tam sonucu
10
+ - "model" : modelden donen icerik (thought / response)
11
+ - "tool_call" : ajanin cagirdigi tool ve argumanlari
12
+ - "session_start" / "session_end"
13
+ * Konsola insan-okur formatta (kisaltilmis), dosyaya tam icerik gider.
14
+ * Thread-safe (basit Lock); ileride paralel komut calistirma istersek hazir.
15
+
16
+ Kullanim
17
+ --------
18
+ log = SessionLogger.create()
19
+ log.info("ajan basladi")
20
+ log.command(result) # CommandResult dogrudan loglanir
21
+ log.tool_call("run_cmd", {"cmd": "nmap -sV ..."})
22
+ log.model("nmap baslatiyorum...")
23
+ log.close()
24
+
25
+ veya context manager:
26
+
27
+ with SessionLogger.create() as log:
28
+ ...
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import json
34
+ import sys
35
+ import threading
36
+ from dataclasses import asdict, is_dataclass
37
+ from datetime import datetime, timezone
38
+ from pathlib import Path
39
+ from typing import Any, Optional
40
+
41
+ from config import LOGS_DIR
42
+
43
+ # ANSI renk kodlari (PowerShell + Windows Terminal modern surumlerde calisir)
44
+ _C_RESET = "\033[0m"
45
+ _C_DIM = "\033[2m"
46
+ _C_RED = "\033[31m"
47
+ _C_GREEN = "\033[32m"
48
+ _C_YELLOW = "\033[33m"
49
+ _C_BLUE = "\033[34m"
50
+ _C_MAGENTA = "\033[35m"
51
+ _C_CYAN = "\033[36m"
52
+
53
+ _LEVEL_COLORS: dict[str, str] = {
54
+ "info": _C_CYAN,
55
+ "warn": _C_YELLOW,
56
+ "error": _C_RED,
57
+ "command": _C_GREEN,
58
+ "model": _C_MAGENTA,
59
+ "tool_call": _C_BLUE,
60
+ "session_start": _C_DIM,
61
+ "session_end": _C_DIM,
62
+ }
63
+
64
+
65
+ def _utc_now_iso() -> str:
66
+ return datetime.now(timezone.utc).isoformat(timespec="milliseconds")
67
+
68
+
69
+ def _short(text: str, n: int = 240) -> str:
70
+ """Konsol icin tek satira indir + kirp."""
71
+ if not text:
72
+ return ""
73
+ flat = text.replace("\n", " | ").strip()
74
+ return flat if len(flat) <= n else flat[: n - 3] + "..."
75
+
76
+
77
+ def _safe_json(value: Any) -> Any:
78
+ """JSON'a cevrilebilir hale getir (dataclass / Path / set destekler)."""
79
+ if value is None or isinstance(value, (str, int, float, bool)):
80
+ return value
81
+ if is_dataclass(value):
82
+ return _safe_json(asdict(value))
83
+ if isinstance(value, dict):
84
+ return {str(k): _safe_json(v) for k, v in value.items()}
85
+ if isinstance(value, (list, tuple, set)):
86
+ return [_safe_json(v) for v in value]
87
+ if isinstance(value, Path):
88
+ return str(value)
89
+ return repr(value)
90
+
91
+
92
+ class SessionLogger:
93
+ """Tek oturumluk JSONL + konsol logger'i."""
94
+
95
+ def __init__(
96
+ self,
97
+ path: Path,
98
+ session_id: str,
99
+ *,
100
+ echo_to_console: bool = True,
101
+ ) -> None:
102
+ self.path = path
103
+ self.session_id = session_id
104
+ self.echo = echo_to_console
105
+ self._lock = threading.Lock()
106
+ # line buffering ki kill edilse bile son olaylar diske yazilmis olsun
107
+ self._fp = path.open("a", encoding="utf-8", buffering=1)
108
+ self.event(
109
+ "session_start",
110
+ session_id=session_id,
111
+ log_path=str(path),
112
+ )
113
+
114
+ # --- yapilandirma --------------------------------------------------
115
+ @classmethod
116
+ def create(
117
+ cls,
118
+ *,
119
+ log_dir: Optional[Path] = None,
120
+ echo_to_console: bool = True,
121
+ ) -> "SessionLogger":
122
+ log_dir = log_dir or LOGS_DIR
123
+ log_dir.mkdir(parents=True, exist_ok=True)
124
+ sid = datetime.now().strftime("%Y%m%d-%H%M%S")
125
+ path = log_dir / f"session-{sid}.jsonl"
126
+ return cls(path=path, session_id=sid, echo_to_console=echo_to_console)
127
+
128
+ # --- yasam dongusu --------------------------------------------------
129
+ def __enter__(self) -> "SessionLogger":
130
+ return self
131
+
132
+ def __exit__(self, exc_type, exc, tb) -> None:
133
+ if exc_type is not None:
134
+ self.error(f"oturum istisna ile kapaniyor: {exc_type.__name__}: {exc}")
135
+ self.close()
136
+
137
+ def close(self) -> None:
138
+ if self._fp.closed:
139
+ return
140
+ try:
141
+ self.event("session_end", session_id=self.session_id)
142
+ finally:
143
+ self._fp.close()
144
+
145
+ # --- ana API --------------------------------------------------------
146
+ def event(self, event_type: str, **fields: Any) -> None:
147
+ record = {
148
+ "ts": _utc_now_iso(),
149
+ "session": self.session_id,
150
+ "type": event_type,
151
+ **{k: _safe_json(v) for k, v in fields.items()},
152
+ }
153
+ line = json.dumps(record, ensure_ascii=False)
154
+
155
+ with self._lock:
156
+ if not self._fp.closed:
157
+ self._fp.write(line + "\n")
158
+ if self.echo:
159
+ self._echo(event_type, fields)
160
+
161
+ def info(self, msg: str, **extra: Any) -> None:
162
+ self.event("info", message=msg, **extra)
163
+
164
+ def warn(self, msg: str, **extra: Any) -> None:
165
+ self.event("warn", message=msg, **extra)
166
+
167
+ def error(self, msg: str, **extra: Any) -> None:
168
+ self.event("error", message=msg, **extra)
169
+
170
+ def model(self, content: str, *, role: str = "assistant", **extra: Any) -> None:
171
+ """Modelden donen icerigi logla (thought + response)."""
172
+ self.event("model", role=role, content=content, **extra)
173
+
174
+ def tool_call(self, name: str, args: dict[str, Any], **extra: Any) -> None:
175
+ self.event("tool_call", name=name, args=args, **extra)
176
+
177
+ def command(self, result: Any) -> None:
178
+ """CommandResult'i (ssh_client) dogrudan logla."""
179
+ # Geri dongusel import olmasin diye duck-typing yapiyoruz.
180
+ self.event(
181
+ "command",
182
+ command=getattr(result, "command", None),
183
+ exit_code=getattr(result, "exit_code", None),
184
+ duration_s=round(float(getattr(result, "duration_s", 0.0)), 3),
185
+ stdout=getattr(result, "stdout", ""),
186
+ stderr=getattr(result, "stderr", ""),
187
+ )
188
+
189
+ # --- konsol formatlama ---------------------------------------------
190
+ def _echo(self, event_type: str, fields: dict[str, Any]) -> None:
191
+ color = _LEVEL_COLORS.get(event_type, "")
192
+ ts = datetime.now().strftime("%H:%M:%S")
193
+ prefix = f"{_C_DIM}{ts}{_C_RESET} {color}{event_type:>13}{_C_RESET}"
194
+
195
+ if event_type == "command":
196
+ cmd = _short(str(fields.get("command", "")), 120)
197
+ ec = fields.get("exit_code")
198
+ dur = fields.get("duration_s")
199
+ tag = _C_GREEN if ec == 0 else _C_RED
200
+ print(f"{prefix} {tag}exit={ec}{_C_RESET} {dur}s $ {cmd}")
201
+ stdout = _short(str(fields.get("stdout", "")), 200)
202
+ stderr = _short(str(fields.get("stderr", "")), 200)
203
+ if stdout:
204
+ print(f" {_C_DIM}stdout:{_C_RESET} {stdout}")
205
+ if stderr:
206
+ print(f" {_C_RED}stderr:{_C_RESET} {stderr}")
207
+ return
208
+
209
+ if event_type == "tool_call":
210
+ name = fields.get("name")
211
+ args = _short(json.dumps(_safe_json(fields.get("args", {})), ensure_ascii=False), 200)
212
+ print(f"{prefix} {name}({args})")
213
+ return
214
+
215
+ if event_type == "model":
216
+ role = fields.get("role", "assistant")
217
+ content = _short(str(fields.get("content", "")), 280)
218
+ print(f"{prefix} [{role}] {content}")
219
+ return
220
+
221
+ # info / warn / error / session_*
222
+ msg = fields.get("message") or fields.get("session_id") or ""
223
+ extras = {k: v for k, v in fields.items() if k not in {"message", "session_id"}}
224
+ extras_str = f" {_C_DIM}{extras}{_C_RESET}" if extras else ""
225
+ print(f"{prefix} {_short(str(msg), 280)}{extras_str}", file=sys.stderr if event_type == "error" else sys.stdout)
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --- core ---
2
+ paramiko>=3.4.0
3
+ python-dotenv>=1.0.1
4
+ ollama>=0.4.4
5
+
6
+ # --- voice (opsiyonel; eksikse :v komutu devre disi kalir) ---
7
+ # faster-whisper kurulumda ctranslate2 wheel gerektirir; Windows + Python
8
+ # 3.12-3.14 icin pip otomatik secer. CUDA istersen `pip install ...` yerine
9
+ # https://github.com/SYSTRAN/faster-whisper README'sine bak.
10
+ faster-whisper>=1.0.3
11
+ sounddevice>=0.5.0
12
+ numpy>=1.26
safety.py ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Komut guvenlik filtresi (Kali VM tarafini korur).
2
+
3
+ Modelin "ahlak bekceligi yapma" sistem promptu var; bu yuzden Python tarafinda
4
+ ince bir filtre tutuyoruz. Hedef ag/IP filtrelemesi YOK (kullanici tercihi);
5
+ sadece Kali VM'ini ve SSH erisimini bozacak destruktif komutlari yakalariz.
6
+
7
+ Kullanim
8
+ --------
9
+ checker = SafetyChecker.from_env(logger=log)
10
+ verdict = checker.check("rm -rf /")
11
+ if not verdict.allowed:
12
+ ... # modele BLOCKED ciktisi don, Kali'ye gonderme
13
+
14
+ Severity
15
+ --------
16
+ "block" : enforce modunda durdurulur, audit modunda loglanir + gecirilir.
17
+ "warn" : her iki modda da gecer, sadece uyari + log.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import re
23
+ from dataclasses import dataclass
24
+ from typing import TYPE_CHECKING, Optional, Pattern
25
+
26
+ from config import SafetyConfig
27
+
28
+ if TYPE_CHECKING:
29
+ from logger import SessionLogger
30
+
31
+
32
+ # -----------------------------------------------------------------------------
33
+ # Kural tanimlari
34
+ # -----------------------------------------------------------------------------
35
+ # Her kural: (rule_id, regex, severity, human_description)
36
+ # Regexler `re.IGNORECASE | re.VERBOSE` ile derleniyor; bosluklara dikkat:
37
+ # ' ' literal bosluk degil, \s+ veya \s* kullaniyoruz.
38
+ # -----------------------------------------------------------------------------
39
+
40
+ _RAW_RULES: tuple[tuple[str, str, str, str], ...] = (
41
+ # === Dosya sistemi yikimi ===
42
+ (
43
+ "fs.rm_root",
44
+ # Sondaki sinirlandirici: bosluk, EOL, virgul, noktalivirgul veya '/' (alt yol).
45
+ # \b kullanmiyoruz cunku '/' ve '~' word-karakter degil; EOL ile boundary olusmaz.
46
+ r"\brm\s+(?:-[rRfF]+\s+)+(?:--no-preserve-root\s+)?(?:/(?:\*|etc|root|home|boot|usr|var|bin|sbin|lib)?)(?:\s|/|;|$)",
47
+ "block",
48
+ "Kok dizin / kritik sistem dizinine 'rm -rf' deniyor.",
49
+ ),
50
+ (
51
+ "fs.rm_home",
52
+ r"\brm\s+(?:-[rRfF]+\s+)+(?:~|\$HOME)(?:/|\s|;|$)",
53
+ "block",
54
+ "Kullanici ev dizinine 'rm -rf' deniyor.",
55
+ ),
56
+ (
57
+ "fs.find_delete_root",
58
+ r"\bfind\s+(?:/|/\*)\s+.*-delete\b",
59
+ "block",
60
+ "find / -delete tum dosya sistemini siler.",
61
+ ),
62
+ (
63
+ "fs.etc_overwrite",
64
+ r">\s*/etc/(passwd|shadow|sudoers(?:\.d/[^\s]*)?|gshadow|fstab)\b",
65
+ "block",
66
+ "Kritik /etc dosyasinin uzerine yaziliyor.",
67
+ ),
68
+
69
+ # === Disk / blok aygit ===
70
+ (
71
+ "disk.mkfs",
72
+ r"\bmkfs(?:\.[a-z0-9]+)?\b",
73
+ "block",
74
+ "Bir blok aygit uzerinde dosya sistemi olusturuluyor (mkfs).",
75
+ ),
76
+ (
77
+ "disk.dd",
78
+ r"\bdd\b[^|;&]*\bof=/dev/(?:sd[a-z]\d*|nvme\d+n\d+(?:p\d+)?|vd[a-z]\d*|xvd[a-z]\d*|hd[a-z]\d*)\b",
79
+ "block",
80
+ "dd dogrudan blok aygita yaziyor.",
81
+ ),
82
+ (
83
+ "disk.wipefs",
84
+ r"\bwipefs\b",
85
+ "block",
86
+ "wipefs blok aygit imzalarini siler.",
87
+ ),
88
+ (
89
+ "disk.shred_dev",
90
+ r"\bshred\b[^|;&]*\s/dev/(?:sd|nvme|vd|xvd|hd)",
91
+ "block",
92
+ "shred dogrudan bir blok aygita uygulaniyor.",
93
+ ),
94
+ (
95
+ "disk.redirect_to_dev",
96
+ r">\s*/dev/(?:sd[a-z]\d*|nvme\d+n\d+(?:p\d+)?|vd[a-z]\d*|xvd[a-z]\d*|hd[a-z]\d*)\b",
97
+ "block",
98
+ "Yonlendirme dogrudan blok aygita yapiliyor.",
99
+ ),
100
+
101
+ # === Hizmet reddi / fork bomb ===
102
+ (
103
+ "dos.forkbomb",
104
+ r":\s*\(\s*\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:",
105
+ "block",
106
+ "Fork bomb tespit edildi.",
107
+ ),
108
+ (
109
+ "dos.bg_loop",
110
+ r"\bwhile\s+(?:true|:)\s*;\s*do\b[^|]*&\s*done",
111
+ "warn",
112
+ "Sonsuz arkaplan dongusu (kaynak tuketebilir).",
113
+ ),
114
+
115
+ # === Sistemi kapatma ===
116
+ (
117
+ "power.shutdown",
118
+ r"\b(?:sudo\s+)?(?:shutdown|reboot|halt|poweroff)\b",
119
+ "block",
120
+ "Sistem kapatma / yeniden baslatma komutu.",
121
+ ),
122
+ (
123
+ "power.init0",
124
+ r"\binit\s+[06]\b",
125
+ "block",
126
+ "init 0/6 sistem kapatma / yeniden baslatma.",
127
+ ),
128
+ (
129
+ "power.systemctl",
130
+ r"\bsystemctl\s+(?:poweroff|reboot|halt|isolate\s+(?:rescue|emergency))\b",
131
+ "block",
132
+ "systemctl ile sistem kapatma / kurtarma modu.",
133
+ ),
134
+
135
+ # === Kendini SSH'tan dislama ===
136
+ (
137
+ "ssh.lockout_dir",
138
+ r"\brm\s+(?:-[rRfF]+\s+)+(?:~|\$HOME)?/?\.ssh\b",
139
+ "block",
140
+ "~/.ssh dizini siliniyor; SSH erisimini kaybedersin.",
141
+ ),
142
+ (
143
+ "ssh.lockout_authorized_keys",
144
+ r"\brm\s+(?:-[rRfF]+\s+)*(?:~|\$HOME)?/?\.ssh/authorized_keys\b",
145
+ "block",
146
+ "authorized_keys siliniyor; SSH erisimini kaybedersin.",
147
+ ),
148
+ (
149
+ "ssh.overwrite_authorized_keys",
150
+ r">\s*(?:~|\$HOME)?/?\.ssh/authorized_keys\b",
151
+ "warn",
152
+ "authorized_keys uzerine yaziliyor (>>); kasitliysa sorun yok.",
153
+ ),
154
+ (
155
+ "ssh.sshd_disable",
156
+ r"\bsystemctl\s+(?:stop|disable|mask)\s+ssh(?:d)?\b",
157
+ "block",
158
+ "sshd durduruluyor / devre disi birakiliyor.",
159
+ ),
160
+
161
+ # === Kullanici / yetki yikimi ===
162
+ (
163
+ "user.del_critical",
164
+ r"\b(?:userdel|deluser)\s+(?:-r\s+)?(?:root|kali)\b",
165
+ "block",
166
+ "Kritik kullanici (root/kali) siliniyor.",
167
+ ),
168
+ (
169
+ "user.passwd_critical",
170
+ r"\bpasswd\s+(?:root|kali)\b",
171
+ "warn",
172
+ "root/kali parolasi degistiriliyor (lockout riski).",
173
+ ),
174
+ (
175
+ "user.sudoers_pipe",
176
+ r"\becho\b[^|]*\|\s*(?:sudo\s+)?tee\s+(?:-a\s+)?/etc/sudoers",
177
+ "block",
178
+ "/etc/sudoers'a dogrudan yaziliyor.",
179
+ ),
180
+
181
+ # === Suphe/uyari (block degil, sadece warn) ===
182
+ (
183
+ "exec.curl_pipe_sh",
184
+ r"\b(?:curl|wget)\b[^|]*\|\s*(?:sudo\s+)?(?:bash|sh|zsh|dash|ksh)\b",
185
+ "warn",
186
+ "curl/wget ciktisi dogrulanmadan kabuga aktariliyor.",
187
+ ),
188
+ (
189
+ "net.iptables_flush",
190
+ r"\biptables\s+-F\b",
191
+ "warn",
192
+ "Tum iptables kurallari temizleniyor.",
193
+ ),
194
+ (
195
+ "net.ufw_disable",
196
+ r"\bufw\s+disable\b",
197
+ "warn",
198
+ "ufw guvenlik duvari devre disi birakiliyor.",
199
+ ),
200
+ )
201
+
202
+
203
+ def _compile_rules() -> list[tuple[str, Pattern[str], str, str]]:
204
+ flags = re.IGNORECASE | re.VERBOSE
205
+ compiled: list[tuple[str, Pattern[str], str, str]] = []
206
+ for rid, pattern, severity, desc in _RAW_RULES:
207
+ compiled.append((rid, re.compile(pattern, flags), severity, desc))
208
+ return compiled
209
+
210
+
211
+ _COMPILED_RULES = _compile_rules()
212
+
213
+
214
+ # -----------------------------------------------------------------------------
215
+ # Sonuc tipi
216
+ # -----------------------------------------------------------------------------
217
+
218
+
219
+ @dataclass
220
+ class Verdict:
221
+ """Tek bir komut hakkindaki guvenlik karari."""
222
+
223
+ allowed: bool
224
+ rule_id: str
225
+ severity: str # "block" | "warn" | "ok"
226
+ reason: str
227
+ mode: str # "enforce" | "audit"
228
+
229
+ @property
230
+ def blocked(self) -> bool:
231
+ return not self.allowed
232
+
233
+ def to_user_message(self) -> str:
234
+ """Modele geri donulebilecek kisa aciklama (BLOCKED veya WARNING)."""
235
+ if self.blocked:
236
+ return f"BLOCKED [{self.rule_id}]: {self.reason}"
237
+ if self.severity == "warn":
238
+ return f"WARNING [{self.rule_id}]: {self.reason}"
239
+ return "OK"
240
+
241
+
242
+ # -----------------------------------------------------------------------------
243
+ # Ana sinif
244
+ # -----------------------------------------------------------------------------
245
+
246
+
247
+ class SafetyChecker:
248
+ """Komutlari kural tabanli filtreden geciren sinif."""
249
+
250
+ def __init__(
251
+ self,
252
+ cfg: SafetyConfig,
253
+ *,
254
+ logger: Optional["SessionLogger"] = None,
255
+ ):
256
+ self.cfg = cfg
257
+ self.logger = logger
258
+ self.rules = _COMPILED_RULES
259
+
260
+ @classmethod
261
+ def from_env(cls, *, logger: Optional["SessionLogger"] = None) -> "SafetyChecker":
262
+ return cls(SafetyConfig.from_env(), logger=logger)
263
+
264
+ def check(self, command: str) -> Verdict:
265
+ """Komutu kurallara karsi degerlendir.
266
+
267
+ Donus:
268
+ Verdict. Birden fazla kural eslesirse en yuksek oncelikli ('block'
269
+ > 'warn') donulur.
270
+ """
271
+ norm = command.strip()
272
+ if not norm:
273
+ return self._verdict_ok()
274
+
275
+ block_match: tuple[str, str, str] | None = None
276
+ warn_match: tuple[str, str, str] | None = None
277
+
278
+ for rid, pattern, severity, desc in self.rules:
279
+ if pattern.search(norm):
280
+ if severity == "block" and block_match is None:
281
+ block_match = (rid, severity, desc)
282
+ break # block bulunursa kalanini taramaya gerek yok
283
+ if severity == "warn" and warn_match is None:
284
+ warn_match = (rid, severity, desc)
285
+
286
+ match = block_match or warn_match
287
+ if match is None:
288
+ return self._verdict_ok()
289
+
290
+ rid, severity, desc = match
291
+ # enforce -> block durdurur; audit -> her sey gecer.
292
+ allowed = self.cfg.mode == "audit" or severity != "block"
293
+ verdict = Verdict(
294
+ allowed=allowed,
295
+ rule_id=rid,
296
+ severity=severity,
297
+ reason=desc,
298
+ mode=self.cfg.mode,
299
+ )
300
+ self._log_verdict(command, verdict)
301
+ return verdict
302
+
303
+ # --- yardimcilar ----------------------------------------------------
304
+ def _verdict_ok(self) -> Verdict:
305
+ return Verdict(
306
+ allowed=True,
307
+ rule_id="default",
308
+ severity="ok",
309
+ reason="kural eslesmedi",
310
+ mode=self.cfg.mode,
311
+ )
312
+
313
+ def _log_verdict(self, command: str, verdict: Verdict) -> None:
314
+ if not self.logger:
315
+ return
316
+ event = "info" if verdict.severity == "warn" else (
317
+ "warn" if verdict.allowed else "error"
318
+ )
319
+ method = getattr(self.logger, event)
320
+ method(
321
+ "safety_match",
322
+ command=command,
323
+ rule=verdict.rule_id,
324
+ severity=verdict.severity,
325
+ allowed=verdict.allowed,
326
+ reason=verdict.reason,
327
+ mode=verdict.mode,
328
+ )
329
+
330
+
331
+ # -----------------------------------------------------------------------------
332
+ # CLI: kurallari elle test etmek icin
333
+ # python safety.py "rm -rf /"
334
+ # python safety.py "nmap -sV 10.0.0.1"
335
+ # -----------------------------------------------------------------------------
336
+
337
+
338
+ def _self_test() -> int:
339
+ samples = [
340
+ ("nmap -sV 192.168.1.10", True),
341
+ ("rm -rf /", False),
342
+ ("rm -rf ~", False),
343
+ ("rm -rf /etc", False),
344
+ ("dd if=/dev/zero of=/dev/sda bs=1M", False),
345
+ ("mkfs.ext4 /dev/sdb1", False),
346
+ (":(){ :|:& };:", False),
347
+ ("shutdown -h now", False),
348
+ ("systemctl stop ssh", False),
349
+ ("rm -rf ~/.ssh", False),
350
+ ("curl http://x.y/install.sh | bash", True), # warn ama gecer
351
+ ("iptables -F", True), # warn ama gecer
352
+ ("echo hello && ls -la /tmp", True),
353
+ ("gobuster dir -u http://10.0.0.1 -w /usr/share/wordlists/dirb/common.txt", True),
354
+ ]
355
+ checker = SafetyChecker(SafetyConfig(mode="enforce"))
356
+ failed = 0
357
+ for cmd, expected_allowed in samples:
358
+ v = checker.check(cmd)
359
+ ok = (v.allowed == expected_allowed)
360
+ marker = "OK " if ok else "FAIL"
361
+ print(f"[{marker}] allowed={v.allowed!s:<5} severity={v.severity:<5} "
362
+ f"rule={v.rule_id:<28} :: {cmd}")
363
+ if not ok:
364
+ failed += 1
365
+ print()
366
+ print(f"{len(samples) - failed}/{len(samples)} kural-davranis testi gecti.")
367
+ return 0 if failed == 0 else 1
368
+
369
+
370
+ if __name__ == "__main__":
371
+ import sys
372
+
373
+ if len(sys.argv) >= 2:
374
+ cmd = " ".join(sys.argv[1:])
375
+ v = SafetyChecker.from_env().check(cmd)
376
+ print(f"command : {cmd}")
377
+ print(f"verdict : {v}")
378
+ print(f"message : {v.to_user_message()}")
379
+ sys.exit(0 if v.allowed else 1)
380
+ sys.exit(_self_test())
ssh_client.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Kali Linux VM icin SSH istemcisi.
2
+
3
+ Tasarim notlari
4
+ ---------------
5
+ * Anahtar tabanli kimlik dogrulama (parola fallback yok, .env'de KALI_SSH_KEY
6
+ zorunlu). Anahtar parolaliysa KALI_SSH_KEY_PASSPHRASE ile cozulur.
7
+ * `run()` -> stdout, stderr, exit_code ve sureyi tek bir CommandResult'ta doner.
8
+ * Context manager olarak kullanilabilir:
9
+ with KaliSSH.from_config() as kali:
10
+ res = kali.run("nmap -sV 10.0.0.1")
11
+ * Bridged adapter senaryosunda IP degisirse sadece .env guncellenir.
12
+
13
+ Bu dosya kendi basina test edilebilir; agent.py / tool_call.py bunu sarici
14
+ olarak kullanacak.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import socket
20
+ import time
21
+ from dataclasses import dataclass
22
+ from pathlib import Path
23
+ from typing import Optional
24
+
25
+ import paramiko
26
+ from paramiko.ssh_exception import (
27
+ AuthenticationException,
28
+ NoValidConnectionsError,
29
+ SSHException,
30
+ )
31
+
32
+ from config import SSHConfig
33
+
34
+ # Logger sadece tip ipucu icin; runtime'da opsiyonel kalir (geri donus
35
+ # importunu engellemek icin TYPE_CHECKING bloguna alindi).
36
+ from typing import TYPE_CHECKING
37
+
38
+ if TYPE_CHECKING:
39
+ from logger import SessionLogger
40
+
41
+
42
+ # Paramiko'nun denedigi anahtar tipleri (parola cozumu icin sirayla denenir).
43
+
44
+ _KEY_LOADERS = (
45
+ paramiko.Ed25519Key,
46
+ paramiko.ECDSAKey,
47
+ paramiko.RSAKey,
48
+ )
49
+
50
+
51
+ @dataclass
52
+ class CommandResult:
53
+ """Bir SSH komutunun calisma sonucu."""
54
+
55
+ command: str
56
+ stdout: str
57
+ stderr: str
58
+ exit_code: int
59
+ duration_s: float
60
+
61
+ @property
62
+ def ok(self) -> bool:
63
+ return self.exit_code == 0
64
+
65
+ def combined_output(self, max_chars: int = 8000) -> str:
66
+ """Modele geri verilecek tek string. Cok uzun ciktilar kirpilir."""
67
+ parts: list[str] = []
68
+ if self.stdout:
69
+ parts.append(self.stdout.rstrip())
70
+ if self.stderr:
71
+ parts.append(f"[stderr]\n{self.stderr.rstrip()}")
72
+ text = "\n".join(parts) if parts else "(cikti yok)"
73
+ if len(text) > max_chars:
74
+ text = text[:max_chars] + f"\n...[CIKTI {len(text) - max_chars} KARAKTER KIRPILDI]"
75
+ return text
76
+
77
+
78
+ class SSHConnectionError(RuntimeError):
79
+ """Bag­lan­ti / kimlik dogrulama hatalarini sarmalayan tek tip hata."""
80
+
81
+
82
+ def _load_private_key(key_path: Path, passphrase: Optional[str]) -> paramiko.PKey:
83
+ """Anahtari tip otomatik tespit ederek yukle."""
84
+ if not key_path.exists():
85
+ raise SSHConnectionError(f"SSH anahtari bulunamadi: {key_path}")
86
+
87
+ last_error: Exception | None = None
88
+ for loader in _KEY_LOADERS:
89
+ try:
90
+ return loader.from_private_key_file(str(key_path), password=passphrase)
91
+ except paramiko.PasswordRequiredException as exc:
92
+ raise SSHConnectionError(
93
+ "SSH anahtari parolali; .env icinde KALI_SSH_KEY_PASSPHRASE bos."
94
+ ) from exc
95
+ except SSHException as exc:
96
+ last_error = exc
97
+ continue
98
+ raise SSHConnectionError(
99
+ f"SSH anahtari yuklenemedi ({key_path}). Son hata: {last_error}"
100
+ )
101
+
102
+
103
+ class KaliSSH:
104
+ """Kali VM'e ince SSH sarmali."""
105
+
106
+ def __init__(self, cfg: SSHConfig, logger: Optional["SessionLogger"] = None):
107
+ self.cfg = cfg
108
+ self._client: Optional[paramiko.SSHClient] = None
109
+ self.logger = logger
110
+
111
+ # --- yasam dongusu --------------------------------------------------
112
+ @classmethod
113
+ def from_config(cls, logger: Optional["SessionLogger"] = None) -> "KaliSSH":
114
+ return cls(SSHConfig.from_env(), logger=logger)
115
+
116
+ def attach_logger(self, logger: "SessionLogger") -> None:
117
+ """Olusturulduktan sonra logger baglamak icin."""
118
+ self.logger = logger
119
+
120
+ def __enter__(self) -> "KaliSSH":
121
+ self.connect()
122
+ return self
123
+
124
+ def __exit__(self, exc_type, exc, tb) -> None:
125
+ self.close()
126
+
127
+ @property
128
+ def is_connected(self) -> bool:
129
+ if self._client is None:
130
+ return False
131
+ transport = self._client.get_transport()
132
+ return transport is not None and transport.is_active()
133
+
134
+ def connect(self) -> None:
135
+ if self.is_connected:
136
+ return
137
+ pkey = _load_private_key(self.cfg.key_path, self.cfg.key_passphrase)
138
+
139
+ client = paramiko.SSHClient()
140
+ # Bilinmeyen host icin otomatik kabul (lokal VM senaryosu icin uygun;
141
+ # production'da known_hosts kullanilmali).
142
+ client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
143
+
144
+ try:
145
+ client.connect(
146
+ hostname=self.cfg.host,
147
+ port=self.cfg.port,
148
+ username=self.cfg.username,
149
+ pkey=pkey,
150
+ password=self.cfg.password,
151
+ timeout=15,
152
+ allow_agent=False,
153
+ look_for_keys=False,
154
+ )
155
+ except AuthenticationException as exc:
156
+ if self.logger:
157
+ self.logger.error(
158
+ "ssh_auth_failed", host=self.cfg.host, user=self.cfg.username
159
+ )
160
+ raise SSHConnectionError(
161
+ f"Kimlik dogrulama basarisiz: {self.cfg.username}@{self.cfg.host}. "
162
+ "Anahtarin Kali tarafindaki ~/.ssh/authorized_keys icinde oldugundan emin ol "
163
+ "(veya gecici olarak .env icinde KALI_SSH_PASSWORD doldur)."
164
+ ) from exc
165
+ except NoValidConnectionsError as exc:
166
+ if self.logger:
167
+ self.logger.error(
168
+ "ssh_connect_failed", host=self.cfg.host, port=self.cfg.port
169
+ )
170
+ raise SSHConnectionError(
171
+ f"Baglanti kurulamadi: {self.cfg.host}:{self.cfg.port}. "
172
+ "Kali VM ayakta mi, sshd calisiyor mu, IP/port dogru mu?"
173
+ ) from exc
174
+ except (socket.timeout, TimeoutError) as exc:
175
+ if self.logger:
176
+ self.logger.error(
177
+ "ssh_connect_timeout", host=self.cfg.host, port=self.cfg.port
178
+ )
179
+ raise SSHConnectionError(
180
+ f"Zaman asimi: {self.cfg.host}:{self.cfg.port}"
181
+ ) from exc
182
+ except SSHException as exc:
183
+ if self.logger:
184
+ self.logger.error("ssh_error", detail=str(exc))
185
+ raise SSHConnectionError(f"SSH hatasi: {exc}") from exc
186
+
187
+ self._client = client
188
+ if self.logger:
189
+ self.logger.info(
190
+ "ssh_connected",
191
+ host=self.cfg.host,
192
+ port=self.cfg.port,
193
+ user=self.cfg.username,
194
+ )
195
+
196
+ def close(self) -> None:
197
+ if self._client is not None:
198
+ try:
199
+ self._client.close()
200
+ finally:
201
+ self._client = None
202
+
203
+ # --- komut calistirma ----------------------------------------------
204
+ def run(
205
+ self,
206
+ command: str,
207
+ *,
208
+ timeout: Optional[int] = None,
209
+ get_pty: bool = False,
210
+ ) -> CommandResult:
211
+ """Komutu Kali'de calistir, sonucu CommandResult olarak don.
212
+
213
+ timeout None ise SSHConfig.command_timeout kullanilir.
214
+ get_pty=True bazi tool'lar (ornek: msfconsole) icin gerekebilir;
215
+ ancak ciktinin renk kodlari ile karismasina yol acar, varsayilan False.
216
+ """
217
+ if not self.is_connected:
218
+ self.connect()
219
+ assert self._client is not None # type checker icin
220
+
221
+ effective_timeout = timeout if timeout is not None else self.cfg.command_timeout
222
+ start = time.monotonic()
223
+
224
+ try:
225
+ stdin, stdout, stderr = self._client.exec_command(
226
+ command,
227
+ timeout=effective_timeout,
228
+ get_pty=get_pty,
229
+ )
230
+ stdin.close()
231
+ # exit_status_ready'i beklemeden read yaparsak deadlock olabilir;
232
+ # paramiko'nun standart akisi: once read, exit_status sona.
233
+ out = stdout.read().decode("utf-8", errors="replace")
234
+ err = stderr.read().decode("utf-8", errors="replace")
235
+ exit_code = stdout.channel.recv_exit_status()
236
+ except socket.timeout as exc:
237
+ if self.logger:
238
+ self.logger.error(
239
+ "command_timeout", command=command, timeout_s=effective_timeout
240
+ )
241
+ raise SSHConnectionError(
242
+ f"Komut zaman asimina ugradi ({effective_timeout}s): {command!r}"
243
+ ) from exc
244
+ except SSHException as exc:
245
+ if self.logger:
246
+ self.logger.error(
247
+ "command_ssh_error", command=command, detail=str(exc)
248
+ )
249
+ raise SSHConnectionError(f"Komut calistirma hatasi: {exc}") from exc
250
+
251
+ result = CommandResult(
252
+ command=command,
253
+ stdout=out,
254
+ stderr=err,
255
+ exit_code=exit_code,
256
+ duration_s=time.monotonic() - start,
257
+ )
258
+ if self.logger:
259
+ self.logger.command(result)
260
+ return result
261
+
262
+ def ping(self) -> bool:
263
+ """Hizli saglik kontrolu. True donerse SSH kanali calisiyor demektir."""
264
+ try:
265
+ res = self.run("echo pong", timeout=10)
266
+ return res.ok and "pong" in res.stdout
267
+ except SSHConnectionError:
268
+ return False
test_ssh.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SSH baglanti testi.
2
+
3
+ Calistirma:
4
+ python test_ssh.py
5
+
6
+ Yaptiklari:
7
+ 1. .env'i okur, SSHConfig olusturur (eksik alan varsa erken hata).
8
+ 2. Kali'ye baglanir, ping atar.
9
+ 3. Kimlik / sistem dogrulayan bir dizi guvenli komut calistirir.
10
+ 4. Pentest araclarinin (nmap, gobuster, sqlmap, vs.) varligini kontrol eder.
11
+ 5. Adim adim yesil/kirmizi rapor basar.
12
+
13
+ Hata cikarsa son satira bakman yeterli; basarisiz olan adim aciklanir.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import sys
19
+ from typing import Iterable
20
+
21
+ from logger import SessionLogger
22
+ from ssh_client import CommandResult, KaliSSH, SSHConnectionError
23
+
24
+ # (etiket, komut, basari icin stdout icinde aranacak alt-string ya da None)
25
+ SANITY_COMMANDS: tuple[tuple[str, str, str | None], ...] = (
26
+ ("kullanici", "whoami", None),
27
+ ("hostname", "hostname", None),
28
+ ("kernel", "uname -a", "Linux"),
29
+ ("dagitim", "cat /etc/os-release | head -n 5", "kali"),
30
+ ("ip adresleri", "hostname -I", None),
31
+ ("calisma dizini", "pwd", None),
32
+ )
33
+
34
+ PENTEST_TOOLS: tuple[str, ...] = (
35
+ "nmap",
36
+ "gobuster",
37
+ "dirb",
38
+ "sqlmap",
39
+ "msfconsole",
40
+ "hydra",
41
+ "nikto",
42
+ )
43
+
44
+
45
+ def _color(code: str, text: str) -> str:
46
+ return f"\033[{code}m{text}\033[0m"
47
+
48
+
49
+ def _ok(msg: str) -> None:
50
+ print(_color("32", "[OK] ") + msg)
51
+
52
+
53
+ def _fail(msg: str) -> None:
54
+ print(_color("31", "[FAIL] ") + msg)
55
+
56
+
57
+ def _info(msg: str) -> None:
58
+ print(_color("36", "[..] ") + msg)
59
+
60
+
61
+ def _short(text: str, n: int = 200) -> str:
62
+ text = text.strip().replace("\n", " | ")
63
+ return text if len(text) <= n else text[:n] + "..."
64
+
65
+
66
+ def run_sanity(kali: KaliSSH, items: Iterable[tuple[str, str, str | None]]) -> bool:
67
+ all_ok = True
68
+ for label, cmd, expect in items:
69
+ try:
70
+ res: CommandResult = kali.run(cmd, timeout=15)
71
+ except SSHConnectionError as exc:
72
+ _fail(f"{label}: {exc}")
73
+ all_ok = False
74
+ continue
75
+
76
+ if not res.ok:
77
+ _fail(f"{label}: exit={res.exit_code} | {_short(res.stderr or res.stdout)}")
78
+ all_ok = False
79
+ continue
80
+
81
+ if expect and expect.lower() not in res.stdout.lower():
82
+ _fail(f"{label}: '{expect}' beklenirdi ama stdout: {_short(res.stdout)}")
83
+ all_ok = False
84
+ continue
85
+
86
+ _ok(f"{label}: {_short(res.stdout)}")
87
+ return all_ok
88
+
89
+
90
+ def check_tools(kali: KaliSSH, tools: Iterable[str]) -> None:
91
+ print()
92
+ _info("Pentest araclari kontrolu (eksik olan varsa: sudo apt install ...)")
93
+ for tool in tools:
94
+ try:
95
+ res = kali.run(f"command -v {tool}", timeout=10)
96
+ except SSHConnectionError as exc:
97
+ _fail(f"{tool}: {exc}")
98
+ continue
99
+
100
+ if res.ok and res.stdout.strip():
101
+ _ok(f"{tool}: {res.stdout.strip()}")
102
+ else:
103
+ _fail(f"{tool}: bulunamadi")
104
+
105
+
106
+ def main() -> int:
107
+ print(_color("1", "=== Kali SSH baglanti testi ==="))
108
+
109
+ # Test scriptinin kendi [OK]/[FAIL] ciktisi var; logger'i sadece dosyaya yaz.
110
+ log = SessionLogger.create(echo_to_console=False)
111
+ log.info("ssh_test_start")
112
+
113
+ try:
114
+ kali = KaliSSH.from_config(logger=log)
115
+ except Exception as exc: # noqa: BLE001
116
+ _fail(f"Konfigurasyon hatasi: {exc}")
117
+ log.close()
118
+ return 2
119
+
120
+ _info(
121
+ f"Hedef: {kali.cfg.username}@{kali.cfg.host}:{kali.cfg.port} "
122
+ f"(anahtar: {kali.cfg.key_path})"
123
+ )
124
+
125
+ try:
126
+ kali.connect()
127
+ except SSHConnectionError as exc:
128
+ _fail(str(exc))
129
+ log.close()
130
+ return 1
131
+ _ok("TCP + kimlik dogrulama basarili")
132
+
133
+ if not kali.ping():
134
+ _fail("Ping (echo pong) basarisiz; kanal saglikli degil")
135
+ kali.close()
136
+ log.close()
137
+ return 1
138
+ _ok("Kanal saglikli (echo pong)")
139
+
140
+ print()
141
+ _info("Sanity komutlari calistiriliyor...")
142
+ sanity_ok = run_sanity(kali, SANITY_COMMANDS)
143
+
144
+ check_tools(kali, PENTEST_TOOLS)
145
+
146
+ kali.close()
147
+ log.info("ssh_test_done", sanity_ok=sanity_ok)
148
+ log.close()
149
+
150
+ print()
151
+ if sanity_ok:
152
+ print(_color("32;1", "TUM SANITY KONTROLLERI GECTI."))
153
+ return 0
154
+
155
+ print(_color("31;1", "BAZI KONTROLLER BASARISIZ. Yukaridaki [FAIL] satirlarini incele."))
156
+ return 1
157
+
158
+
159
+ if __name__ == "__main__":
160
+ sys.exit(main())
tool_call.py ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ReAct stili tool cagri ayriciligi + dispatcher.
2
+
3
+ Akis (genel)
4
+ ------------
5
+ 1. Model ureten bir metin doner. Genellikle su sablon:
6
+
7
+ Thought: hedefin portlarini taramaliyim.
8
+ Action: run_cmd
9
+ Action Input: nmap -sV -p- 10.0.0.5
10
+
11
+ ya da bitirirken:
12
+
13
+ Thought: yeterli bilgi var.
14
+ Final Answer: Acik portlar: 22/ssh, 80/http ...
15
+
16
+ 2. `parse_react()` bu metni `ParsedResponse`'a cevirir.
17
+ 3. agent.py birden fazla aksiyon varsa kullaniciya sorar (proje karari).
18
+ 4. `ToolDispatcher.dispatch(call)` -> safety -> KaliSSH -> Observation string.
19
+ 5. Observation modele "Observation: ..." prefix'i ile geri verilir.
20
+
21
+ Bu modul sadece parsing ve dispatch'i yapar; LLM cagrisi agent.py'da.
22
+
23
+ Modelfile uyumu
24
+ ---------------
25
+ Modelfile'da `Observation:` ve `Tool Output:` stop token'lari var. Bu sayede
26
+ model `Action Input: ...` yazdiktan sonra durur ve biz observation'i
27
+ ekleyene kadar uretmez. parse_react bu sayede tek seferde bir aksiyona
28
+ odaklanir.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import json
34
+ import re
35
+ from dataclasses import dataclass, field
36
+ from typing import TYPE_CHECKING, Callable, Optional
37
+
38
+ from safety import SafetyChecker, Verdict
39
+ from ssh_client import KaliSSH, SSHConnectionError
40
+
41
+ if TYPE_CHECKING:
42
+ from logger import SessionLogger
43
+
44
+
45
+ # -----------------------------------------------------------------------------
46
+ # Veri tipleri
47
+ # -----------------------------------------------------------------------------
48
+
49
+
50
+ @dataclass
51
+ class ToolCall:
52
+ """Model tarafindan istenen tek bir tool cagrisi."""
53
+
54
+ tool: str
55
+ args: dict[str, str]
56
+ raw: str = "" # ham metin (debug)
57
+
58
+ def short(self, n: int = 120) -> str:
59
+ body = self.args.get("cmd") or json.dumps(self.args, ensure_ascii=False)
60
+ body = body.replace("\n", " ")
61
+ return f"{self.tool}({body if len(body) <= n else body[: n - 3] + '...'})"
62
+
63
+
64
+ @dataclass
65
+ class ParsedResponse:
66
+ """Modelin tek bir uretiminden cikarilmis yapisal bilgi."""
67
+
68
+ thought: Optional[str]
69
+ actions: list[ToolCall] = field(default_factory=list)
70
+ final_answer: Optional[str] = None
71
+ raw: str = ""
72
+
73
+ @property
74
+ def has_action(self) -> bool:
75
+ return bool(self.actions)
76
+
77
+ @property
78
+ def is_final(self) -> bool:
79
+ return self.final_answer is not None and not self.actions
80
+
81
+
82
+ # -----------------------------------------------------------------------------
83
+ # Parser
84
+ # -----------------------------------------------------------------------------
85
+
86
+ # Bir bolumun bittigini gosteren etiketler. Lookahead'de kullanilir.
87
+ _SECTION_LOOKAHEAD = (
88
+ r"(?=\n\s*(?:Thought\s*:|Action\s*:|Action\s*Input\s*:|"
89
+ r"Observation\s*:|Tool\s*Output\s*:|Final\s*Answer\s*:)|\Z)"
90
+ )
91
+
92
+ _THOUGHT_RE = re.compile(
93
+ r"Thought\s*:\s*(?P<body>.*?)" + _SECTION_LOOKAHEAD,
94
+ re.DOTALL | re.IGNORECASE,
95
+ )
96
+
97
+ # Klasik ReAct format:
98
+ # Action: run_cmd
99
+ # Action Input: nmap -sV 1.2.3.4
100
+ _ACTION_BLOCK_RE = re.compile(
101
+ r"Action\s*:\s*(?P<tool>[A-Za-z_][\w\-]*)\s*\n"
102
+ r"\s*Action\s*Input\s*:\s*(?P<input>.*?)" + _SECTION_LOOKAHEAD,
103
+ re.DOTALL | re.IGNORECASE,
104
+ )
105
+
106
+ # Fonksiyon-cagri stili (model bu sekilde de yazabilir):
107
+ # Action: run_cmd(nmap -sV 1.2.3.4)
108
+ # Parantez ici icerigi tolere etmek icin nested 1 seviye paren'e izin veriyoruz.
109
+ # Onemli: bu regex \n veya '(' ile baslayan satirlari yakalamali, klasik
110
+ # formati da yanlis match etmesin diye lookahead ile parantez sart.
111
+ _ACTION_FUNCTION_RE = re.compile(
112
+ r"Action\s*:\s*(?P<tool>[A-Za-z_][\w\-]*)\s*"
113
+ r"\(\s*(?P<input>(?:[^()]|\([^()]*\))*?)\s*\)",
114
+ re.DOTALL | re.IGNORECASE,
115
+ )
116
+
117
+ _FINAL_RE = re.compile(
118
+ r"Final\s*Answer\s*:\s*(?P<body>.*?)\Z",
119
+ re.DOTALL | re.IGNORECASE,
120
+ )
121
+
122
+
123
+ def _strip_input(raw: str) -> str:
124
+ """Action Input'u temizle: kod blogu / tirnak isaretlerini sok."""
125
+ text = raw.strip()
126
+ if not text:
127
+ return ""
128
+
129
+ # ```bash\n...\n``` veya ```\n...\n```
130
+ fenced = re.match(r"^```(?:[a-zA-Z0-9_+-]*)\s*\n(?P<body>.*?)\n```\s*$", text, re.DOTALL)
131
+ if fenced:
132
+ text = fenced.group("body").strip()
133
+ return text
134
+
135
+ # `tek-satir`
136
+ if text.startswith("`") and text.endswith("`") and text.count("`") == 2:
137
+ text = text[1:-1].strip()
138
+ return text
139
+
140
+ # "cift tirnak" veya 'tek tirnak' (sarmalayici)
141
+ if (text.startswith('"') and text.endswith('"')) or (
142
+ text.startswith("'") and text.endswith("'")
143
+ ):
144
+ text = text[1:-1].strip()
145
+
146
+ return text
147
+
148
+
149
+ def parse_react(text: str) -> ParsedResponse:
150
+ """ReAct stilinde uretilmis metni yapisal hale getir.
151
+
152
+ Notlar:
153
+ * Birden fazla Action blogu varsa hepsi listeye girer.
154
+ * Final Answer varsa actions yine de toplanir; agent.py karari verir.
155
+ * Buyuk/kucuk harf duyarsiz; etiketlerin once gelen bosluklari onemsiz.
156
+ """
157
+ raw = text or ""
158
+ thought_match = _THOUGHT_RE.search(raw)
159
+ thought = thought_match.group("body").strip() if thought_match else None
160
+
161
+ # Iki farkli format'i da yakaliyoruz; pozisyona gore sirala ki model'in
162
+ # uretim sirasi korunsun. Ayni pozisyonda klasik bulunduysa fonksiyon
163
+ # cagrisi versiyonunu yoksay (cunku zaten klasik match ediyor demektir).
164
+ raw_matches: list[tuple[int, str, str, str]] = [] # (pos, tool, input, raw_text)
165
+
166
+ classic_spans: list[tuple[int, int]] = []
167
+ for m in _ACTION_BLOCK_RE.finditer(raw):
168
+ classic_spans.append((m.start(), m.end()))
169
+ raw_matches.append(
170
+ (m.start(), m.group("tool").strip(), _strip_input(m.group("input")), m.group(0))
171
+ )
172
+
173
+ def _overlaps_classic(start: int, end: int) -> bool:
174
+ return any(not (end <= s or start >= e) for s, e in classic_spans)
175
+
176
+ for m in _ACTION_FUNCTION_RE.finditer(raw):
177
+ if _overlaps_classic(m.start(), m.end()):
178
+ continue
179
+ raw_matches.append(
180
+ (m.start(), m.group("tool").strip(), _strip_input(m.group("input")), m.group(0))
181
+ )
182
+
183
+ raw_matches.sort(key=lambda t: t[0])
184
+
185
+ actions: list[ToolCall] = [
186
+ ToolCall(tool=tool, args={"cmd": cmd_input}, raw=raw_text)
187
+ for _, tool, cmd_input, raw_text in raw_matches
188
+ ]
189
+
190
+ final_match = _FINAL_RE.search(raw)
191
+ final_answer = final_match.group("body").strip() if final_match else None
192
+ # Final Answer eger ayni cikti icinde Action'dan SONRA geliyorsa, ReAct
193
+ # mantiginda Action'i once isleriz. Bu yuzden eger actions varsa
194
+ # final_answer'i bu turda yoksayariz; agent.py loop'u bir sonraki turda
195
+ # alir. Aksi durumda final_answer dogru kalir.
196
+ if actions and final_answer is not None:
197
+ # Eger final_answer son Action'dan sonra geliyorsa, bos olmadigi
198
+ # surece bilgi olarak tutalim ama is_final dondermeyiz.
199
+ all_action_ends = [
200
+ m.end() for m in _ACTION_BLOCK_RE.finditer(raw)
201
+ ] + [
202
+ m.end() for m in _ACTION_FUNCTION_RE.finditer(raw)
203
+ ]
204
+ last_action_end = max(all_action_ends) if all_action_ends else 0
205
+ final_pos = raw.rfind("Final Answer")
206
+ if final_pos < last_action_end:
207
+ final_answer = None
208
+
209
+ return ParsedResponse(
210
+ thought=thought,
211
+ actions=actions,
212
+ final_answer=final_answer,
213
+ raw=raw,
214
+ )
215
+
216
+
217
+ # -----------------------------------------------------------------------------
218
+ # Dispatcher
219
+ # -----------------------------------------------------------------------------
220
+
221
+
222
+ ToolFn = Callable[[dict[str, str]], str]
223
+
224
+
225
+ class UnknownToolError(RuntimeError):
226
+ pass
227
+
228
+
229
+ class ToolDispatcher:
230
+ """ToolCall -> Observation string. SafetyChecker araligi burada."""
231
+
232
+ def __init__(
233
+ self,
234
+ kali: KaliSSH,
235
+ safety: SafetyChecker,
236
+ *,
237
+ logger: Optional["SessionLogger"] = None,
238
+ ):
239
+ self.kali = kali
240
+ self.safety = safety
241
+ self.logger = logger
242
+ self._tools: dict[str, ToolFn] = {
243
+ "run_cmd": self._tool_run_cmd,
244
+ }
245
+
246
+ @property
247
+ def available_tools(self) -> tuple[str, ...]:
248
+ return tuple(sorted(self._tools.keys()))
249
+
250
+ def register(self, name: str, fn: ToolFn) -> None:
251
+ self._tools[name] = fn
252
+
253
+ def dispatch(self, call: ToolCall) -> str:
254
+ if self.logger:
255
+ self.logger.tool_call(call.tool, call.args)
256
+ fn = self._tools.get(call.tool)
257
+ if fn is None:
258
+ msg = (
259
+ f"BLOCKED: bilinmeyen tool '{call.tool}'. "
260
+ f"Kullanilabilir: {', '.join(self.available_tools)}"
261
+ )
262
+ if self.logger:
263
+ self.logger.error("unknown_tool", tool=call.tool)
264
+ return msg
265
+ try:
266
+ return fn(call.args)
267
+ except Exception as exc: # noqa: BLE001
268
+ if self.logger:
269
+ self.logger.error("tool_exception", tool=call.tool, detail=str(exc))
270
+ return f"ERROR: tool '{call.tool}' istisna firlatti: {exc}"
271
+
272
+ # --- tools ----------------------------------------------------------
273
+ def _tool_run_cmd(self, args: dict[str, str]) -> str:
274
+ cmd = (args.get("cmd") or "").strip()
275
+ if not cmd:
276
+ return "BLOCKED: bos komut."
277
+
278
+ verdict: Verdict = self.safety.check(cmd)
279
+ if verdict.blocked:
280
+ # Modele net mesaj donelim ki yeniden dene-mesin / siklasmasin.
281
+ return verdict.to_user_message()
282
+
283
+ try:
284
+ result = self.kali.run(cmd)
285
+ except SSHConnectionError as exc:
286
+ return f"ERROR: SSH/komut hatasi: {exc}"
287
+
288
+ body = result.combined_output()
289
+ prefix = ""
290
+ if verdict.severity == "warn":
291
+ prefix = verdict.to_user_message() + "\n"
292
+ return f"{prefix}exit={result.exit_code} ({result.duration_s:.1f}s)\n{body}"
293
+
294
+
295
+ # -----------------------------------------------------------------------------
296
+ # Yardimci: observation'i model girdisine donustur
297
+ # -----------------------------------------------------------------------------
298
+
299
+
300
+ def format_observation(obs: str) -> str:
301
+ """Modele Observation: olarak verilecek bicimi olustur.
302
+
303
+ `Observation:` Modelfile'da stop token oldugu icin model bunu yazmaya
304
+ calismaz; bizim eklememiz gerekir. Sonuna bos satir koymak modelin
305
+ devam etme niyetini desteklemek icin.
306
+ """
307
+ return f"Observation: {obs.rstrip()}\n"
308
+
309
+
310
+ # -----------------------------------------------------------------------------
311
+ # Self-test
312
+ # -----------------------------------------------------------------------------
313
+
314
+
315
+ def _self_test() -> int:
316
+ samples = [
317
+ # 0: tek action
318
+ (
319
+ "tek_action",
320
+ "Thought: portlari taramaliyim.\n"
321
+ "Action: run_cmd\n"
322
+ "Action Input: nmap -sV 10.0.0.1\n",
323
+ {"actions": 1, "final": False, "tool": "run_cmd",
324
+ "cmd": "nmap -sV 10.0.0.1"},
325
+ ),
326
+ # 1: kod bloklu input
327
+ (
328
+ "kod_bloklu",
329
+ "Action: run_cmd\n"
330
+ "Action Input: ```bash\nnmap -sV 10.0.0.1\n```\n",
331
+ {"actions": 1, "cmd": "nmap -sV 10.0.0.1"},
332
+ ),
333
+ # 2: tirnakli input
334
+ (
335
+ "tirnakli",
336
+ 'Action: run_cmd\nAction Input: "whoami"\n',
337
+ {"actions": 1, "cmd": "whoami"},
338
+ ),
339
+ # 3: final answer
340
+ (
341
+ "final",
342
+ "Thought: bitti.\nFinal Answer: 22/ssh, 80/http acik.\n",
343
+ {"actions": 0, "final": True},
344
+ ),
345
+ # 4: coklu action
346
+ (
347
+ "coklu_action",
348
+ "Action: run_cmd\nAction Input: whoami\n"
349
+ "Action: run_cmd\nAction Input: hostname\n",
350
+ {"actions": 2},
351
+ ),
352
+ # 5: action sonrasi final (agent loop bir sonraki tura biraktirir)
353
+ (
354
+ "action_sonra_final",
355
+ "Action: run_cmd\nAction Input: ls\nFinal Answer: tamam\n",
356
+ {"actions": 1, "final": False}, # is_final False olmali
357
+ ),
358
+ # 6: fonksiyon-cagri stili (model bu sekilde de yazabilir)
359
+ (
360
+ "fonksiyon_cagri",
361
+ "Thought: scan.\nAction: run_cmd(nmap -p- 1.2.3.4 | grep open)\n",
362
+ {"actions": 1, "tool": "run_cmd",
363
+ "cmd": "nmap -p- 1.2.3.4 | grep open"},
364
+ ),
365
+ # 7: fonksiyon-cagri + final (action calismali, final_answer yoksayilir)
366
+ (
367
+ "fonksiyon_sonra_final",
368
+ "Action: run_cmd(whoami)\nFinal Answer: ben kullaniciyim\n",
369
+ {"actions": 1, "final": False, "cmd": "whoami"},
370
+ ),
371
+ # 8: ic parantezli komut (process substitution)
372
+ (
373
+ "ic_paren",
374
+ "Action: run_cmd(echo $(date) > /tmp/x)\n",
375
+ {"actions": 1, "cmd": "echo $(date) > /tmp/x"},
376
+ ),
377
+ ]
378
+
379
+ failed = 0
380
+ for name, text, expected in samples:
381
+ p = parse_react(text)
382
+ ok = True
383
+ if "actions" in expected and len(p.actions) != expected["actions"]:
384
+ ok = False
385
+ if "tool" in expected and (not p.actions or p.actions[0].tool != expected["tool"]):
386
+ ok = False
387
+ if "cmd" in expected and (not p.actions or p.actions[0].args.get("cmd") != expected["cmd"]):
388
+ ok = False
389
+ if "final" in expected and bool(p.is_final) != bool(expected["final"]):
390
+ ok = False
391
+ marker = "OK " if ok else "FAIL"
392
+ print(f"[{marker}] {name:<20} actions={len(p.actions)} "
393
+ f"final={p.is_final} thought={'Y' if p.thought else 'N'}")
394
+ if not ok:
395
+ failed += 1
396
+ print(f" beklenen: {expected}")
397
+ print(f" bulunan : actions={[a.short() for a in p.actions]} "
398
+ f"final={p.final_answer!r}")
399
+ print()
400
+ print(f"{len(samples) - failed}/{len(samples)} parse testi gecti.")
401
+ return 0 if failed == 0 else 1
402
+
403
+
404
+ if __name__ == "__main__":
405
+ import sys
406
+
407
+ sys.exit(_self_test())
voice.py ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sesli komut girisi (STT).
2
+
3
+ Tasarim
4
+ -------
5
+ * Mikrofon yakalama : `sounddevice` (PortAudio sarmalayicisi, pip ile gelir)
6
+ * Konusma -> metin : `faster-whisper` (yerel; CPU int8 / GPU float16)
7
+ * Konusma sonu tespiti: basit RMS esigi + sessizlik suresi (silence detection)
8
+ * Modulin yuklenmesi : tembel; faster-whisper modeli ilk `listen()` cagrisinda
9
+ indirilip belleme alinir.
10
+
11
+ Bu modul agent.py'da REPL'in `:v` komutuyla cagrilir. `is_available()` False
12
+ donerse kullaniciya net "voice kapali" mesaji gosterilir; agent yine de
13
+ calisir.
14
+
15
+ Cevre degiskenleri (config.py / VoiceConfig):
16
+ VOICE_ENABLED, VOICE_MODEL, VOICE_DEVICE, VOICE_COMPUTE_TYPE,
17
+ VOICE_LANGUAGE, VOICE_SAMPLERATE, VOICE_SILENCE_THRESHOLD,
18
+ VOICE_SILENCE_SECONDS, VOICE_MAX_SECONDS, VOICE_INITIAL_TIMEOUT,
19
+ VOICE_INPUT_DEVICE, VOICE_CONFIRM
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import os
25
+ import queue
26
+ import sys
27
+ import time
28
+ from typing import TYPE_CHECKING, Optional
29
+
30
+ import numpy as np
31
+
32
+ from config import VoiceConfig
33
+
34
+ if TYPE_CHECKING:
35
+ from logger import SessionLogger
36
+
37
+
38
+ # -----------------------------------------------------------------------------
39
+ # huggingface_hub'in symlink uyarisi Windows'ta cok gurultulu; bizim icin
40
+ # sembolik link sart degil (cache yine calisir). Faster-whisper import edilmeden
41
+ # once env var'i set ediyoruz.
42
+ # -----------------------------------------------------------------------------
43
+ os.environ.setdefault("HF_HUB_DISABLE_SYMLINKS_WARNING", "1")
44
+
45
+
46
+ # -----------------------------------------------------------------------------
47
+ # Opsiyonel bagimliliklarin tembel ithali
48
+ # -----------------------------------------------------------------------------
49
+ # sounddevice / faster-whisper olmadan da agent.py calismali. Bu yuzden
50
+ # import hatalarini sessizce tutup `is_available()` ile dosabilecegiz.
51
+
52
+ try:
53
+ import sounddevice as sd # type: ignore[import-not-found]
54
+ _SD_OK = True
55
+ _SD_ERR: Optional[Exception] = None
56
+ except Exception as exc: # noqa: BLE001
57
+ sd = None # type: ignore[assignment]
58
+ _SD_OK = False
59
+ _SD_ERR = exc
60
+
61
+ try:
62
+ from faster_whisper import WhisperModel # type: ignore[import-not-found]
63
+ _FW_OK = True
64
+ _FW_ERR: Optional[Exception] = None
65
+ except Exception as exc: # noqa: BLE001
66
+ WhisperModel = None # type: ignore[assignment]
67
+ _FW_OK = False
68
+ _FW_ERR = exc
69
+
70
+
71
+ # -----------------------------------------------------------------------------
72
+ # Konsol renkleri (agent.py ile ayni palet)
73
+ # -----------------------------------------------------------------------------
74
+ _C_RESET = "\033[0m"
75
+ _C_DIM = "\033[2m"
76
+ _C_RED = "\033[31m"
77
+ _C_GREEN = "\033[32m"
78
+ _C_YELLOW = "\033[33m"
79
+ _C_CYAN = "\033[36m"
80
+
81
+
82
+ # -----------------------------------------------------------------------------
83
+ # Hatalar
84
+ # -----------------------------------------------------------------------------
85
+
86
+
87
+ class VoiceUnavailableError(RuntimeError):
88
+ """Kutuphaneler eksik veya cihaz acilamadigi durum."""
89
+
90
+
91
+ class VoiceCancelled(RuntimeError):
92
+ """Kullanici Ctrl+C ile dinlemeyi iptal etti."""
93
+
94
+
95
+ # -----------------------------------------------------------------------------
96
+ # Yardimci: cihaz secimi
97
+ # -----------------------------------------------------------------------------
98
+
99
+
100
+ def _resolve_device(spec: str) -> Optional[int | str]:
101
+ """`VOICE_INPUT_DEVICE` degerini sounddevice'in bekledigi forma cevir.
102
+
103
+ Bos -> None (sistem default)
104
+ Tam sayi -> int (device index)
105
+ String -> sounddevice'in kendi name-substring resolution'i kullanilir.
106
+ """
107
+ if not spec:
108
+ return None
109
+ s = spec.strip()
110
+ try:
111
+ return int(s)
112
+ except ValueError:
113
+ return s
114
+
115
+
116
+ def list_input_devices() -> list[tuple[int, str, int]]:
117
+ """Mevcut input cihazlarini listele. (index, ad, max_input_channels)."""
118
+ if not _SD_OK:
119
+ raise VoiceUnavailableError(
120
+ "sounddevice yuklu degil. `pip install sounddevice` ile kur."
121
+ )
122
+ devices = sd.query_devices() # type: ignore[union-attr]
123
+ out: list[tuple[int, str, int]] = []
124
+ for i, d in enumerate(devices):
125
+ ch = int(d.get("max_input_channels", 0))
126
+ if ch <= 0:
127
+ continue
128
+ out.append((i, str(d.get("name", "?")), ch))
129
+ return out
130
+
131
+
132
+ # -----------------------------------------------------------------------------
133
+ # Ana sinif
134
+ # -----------------------------------------------------------------------------
135
+
136
+
137
+ class VoiceInput:
138
+ """Push-to-record stili sesli komut girisi.
139
+
140
+ Kullanim:
141
+ voice = VoiceInput(VoiceConfig.from_env(), logger=log)
142
+ if voice.is_available():
143
+ text = voice.listen_once() # mikrofona konus, transkript don
144
+ """
145
+
146
+ def __init__(
147
+ self,
148
+ cfg: VoiceConfig,
149
+ *,
150
+ logger: Optional["SessionLogger"] = None,
151
+ ) -> None:
152
+ self.cfg = cfg
153
+ self.logger = logger
154
+ self._model: Optional["WhisperModel"] = None # tembel yukle
155
+
156
+ # --- saglik kontrolu -------------------------------------------------
157
+ def is_available(self) -> tuple[bool, Optional[str]]:
158
+ """(ok, sebep) doner. ok=False ise `sebep` insan-okur aciklamadir."""
159
+ if not self.cfg.enabled:
160
+ return False, "VOICE_ENABLED=false (.env icinde acabilirsin)."
161
+ if not _SD_OK:
162
+ return False, (
163
+ "sounddevice yuklu degil veya yuklenemedi. "
164
+ "Kurulum: `pip install sounddevice` "
165
+ f"(orijinal hata: {_SD_ERR})"
166
+ )
167
+ if not _FW_OK:
168
+ return False, (
169
+ "faster-whisper yuklu degil. "
170
+ "Kurulum: `pip install faster-whisper` "
171
+ f"(orijinal hata: {_FW_ERR})"
172
+ )
173
+ return True, None
174
+
175
+ # --- model yuklemesi (tembel) ---------------------------------------
176
+ def warmup(self) -> bool:
177
+ """Modeli onceden yukle (agent baslarken cagirilirsa ilk :v'de
178
+ beklemeyi azaltir). Hata olursa False doner; ana akis durmaz.
179
+ """
180
+ ok, why = self.is_available()
181
+ if not ok:
182
+ return False
183
+ try:
184
+ self._ensure_model()
185
+ except VoiceUnavailableError as exc:
186
+ print(f"{_C_YELLOW}[voice] model on-yukleme basarisiz: {exc}{_C_RESET}")
187
+ return False
188
+ return True
189
+
190
+ def _ensure_model(self) -> "WhisperModel":
191
+ if self._model is not None:
192
+ return self._model
193
+ ok, why = self.is_available()
194
+ if not ok:
195
+ raise VoiceUnavailableError(why or "voice kullanilamiyor")
196
+
197
+ print(
198
+ f"{_C_DIM}[voice] faster-whisper yukleniyor "
199
+ f"(model={self.cfg.model_size}, device={self.cfg.device}, "
200
+ f"compute_type={self.cfg.compute_type}; "
201
+ f"ilk seferde HF'den indirilebilir, bekle){_C_RESET}",
202
+ flush=True,
203
+ )
204
+ if self.logger:
205
+ self.logger.info(
206
+ "voice_model_load",
207
+ model=self.cfg.model_size,
208
+ device=self.cfg.device,
209
+ compute_type=self.cfg.compute_type,
210
+ )
211
+ t0 = time.monotonic()
212
+ # Onemli: download veya init sirasinda Ctrl+C gelirse self._model
213
+ # None kalsin ki sonraki cagri yeniden denesin (tutarli durum).
214
+ local_model: Optional["WhisperModel"] = None
215
+ try:
216
+ local_model = WhisperModel( # type: ignore[misc]
217
+ self.cfg.model_size,
218
+ device=self.cfg.device,
219
+ compute_type=self.cfg.compute_type,
220
+ )
221
+ except KeyboardInterrupt:
222
+ print(f"\n{_C_YELLOW}[voice] model yuklemesi iptal edildi.{_C_RESET}")
223
+ if self.logger:
224
+ self.logger.warn("voice_model_load_cancelled")
225
+ raise VoiceCancelled("model yuklemesi iptal") from None
226
+ except Exception as exc: # noqa: BLE001
227
+ if self.logger:
228
+ self.logger.error("voice_model_load_failed", detail=str(exc))
229
+ raise VoiceUnavailableError(
230
+ f"faster-whisper modeli yuklenemedi: {exc}"
231
+ ) from exc
232
+
233
+ self._model = local_model
234
+ dt = time.monotonic() - t0
235
+ print(
236
+ f"{_C_DIM}[voice] model hazir ({dt:.1f}s).{_C_RESET}",
237
+ flush=True,
238
+ )
239
+ if self.logger:
240
+ self.logger.info("voice_model_ready", load_seconds=round(dt, 2))
241
+ return self._model
242
+
243
+ # --- ana akis: kayit + transkript -----------------------------------
244
+ def listen_once(self) -> str:
245
+ """Bir tur dinle, transkripti string olarak don.
246
+
247
+ - Konusma baslamazsa `initial_timeout` icinde abort
248
+ - Konusma bittikten sonra `silence_seconds` sessizlikten sonra dur
249
+ - `max_seconds` sert ust sinir (kotu calar / surekli gurultu)
250
+ - Ctrl+C -> VoiceCancelled
251
+ """
252
+ ok, why = self.is_available()
253
+ if not ok:
254
+ raise VoiceUnavailableError(why or "voice kullanilamiyor")
255
+
256
+ audio = self._record_until_silence()
257
+ if audio.size == 0:
258
+ return ""
259
+
260
+ # faster-whisper float32 mono, 16 kHz beklemiyor; resample gerekmez
261
+ # cunku biz zaten 16 kHz mono float32 kayit alacagiz.
262
+ text = self._transcribe(audio)
263
+ if self.logger:
264
+ self.logger.info("voice_transcript", text=text, samples=int(audio.size))
265
+ return text
266
+
267
+ # --- kayit: silence detection ile ----------------------------------
268
+ def _record_until_silence(self) -> np.ndarray:
269
+ if not _SD_OK:
270
+ raise VoiceUnavailableError("sounddevice yok")
271
+
272
+ cfg = self.cfg
273
+ device = _resolve_device(cfg.input_device)
274
+ block_seconds = 0.05 # 50 ms blok -> akiskan VAD
275
+ blocksize = int(cfg.samplerate * block_seconds)
276
+
277
+ buf: queue.Queue[np.ndarray] = queue.Queue()
278
+
279
+ def _cb(indata, frames, time_info, status): # noqa: ARG001
280
+ if status:
281
+ # Underrun/overflow gibi durumlarda sessizce gec; hatayi
282
+ # logger'a yazip akisi bozmamak istiyoruz.
283
+ if self.logger:
284
+ self.logger.warn("voice_stream_status", detail=str(status))
285
+ buf.put(indata.copy())
286
+
287
+ collected: list[np.ndarray] = []
288
+ spoke = False
289
+ silence_started_at: Optional[float] = None
290
+ start = time.monotonic()
291
+
292
+ print(
293
+ f"{_C_GREEN}[voice] dinleniyor... "
294
+ f"{_C_DIM}(konusmaya basla; {cfg.silence_seconds:.1f}s sessiz "
295
+ f"kalinca otomatik kapanir, Ctrl+C iptal){_C_RESET}",
296
+ flush=True,
297
+ )
298
+ if self.logger:
299
+ self.logger.info(
300
+ "voice_record_start",
301
+ samplerate=cfg.samplerate,
302
+ device=str(device) if device is not None else "default",
303
+ )
304
+
305
+ try:
306
+ with sd.InputStream( # type: ignore[union-attr]
307
+ samplerate=cfg.samplerate,
308
+ channels=1,
309
+ dtype="float32",
310
+ blocksize=blocksize,
311
+ device=device,
312
+ callback=_cb,
313
+ ):
314
+ while True:
315
+ elapsed = time.monotonic() - start
316
+ if elapsed >= cfg.max_seconds:
317
+ print(
318
+ f"\n{_C_YELLOW}[voice] max_seconds ({cfg.max_seconds:.0f}s) "
319
+ f"asildi, kapaniyor.{_C_RESET}"
320
+ )
321
+ break
322
+ if not spoke and elapsed >= cfg.initial_timeout:
323
+ print(
324
+ f"\n{_C_YELLOW}[voice] {cfg.initial_timeout:.0f}s icinde "
325
+ f"konusma duyulmadi, iptal.{_C_RESET}"
326
+ )
327
+ return np.zeros(0, dtype=np.float32)
328
+
329
+ try:
330
+ chunk = buf.get(timeout=0.1)
331
+ except queue.Empty:
332
+ continue
333
+
334
+ rms = float(np.sqrt(np.mean(np.square(chunk, dtype=np.float64))))
335
+ loud = rms >= cfg.silence_threshold
336
+
337
+ # Mikro VU-meter: konsola tek karakter yaz
338
+ bar = "#" if loud else "."
339
+ sys.stdout.write(bar)
340
+ sys.stdout.flush()
341
+
342
+ if loud:
343
+ if not spoke:
344
+ spoke = True
345
+ silence_started_at = None
346
+ collected.append(chunk)
347
+ else:
348
+ if spoke:
349
+ collected.append(chunk)
350
+ if silence_started_at is None:
351
+ silence_started_at = time.monotonic()
352
+ elif (time.monotonic() - silence_started_at) >= cfg.silence_seconds:
353
+ break
354
+ # konusma henuz baslamadiysa bos chunk'lari atlat
355
+ except KeyboardInterrupt as exc:
356
+ print(f"\n{_C_YELLOW}[voice] iptal edildi.{_C_RESET}")
357
+ if self.logger:
358
+ self.logger.warn("voice_cancelled")
359
+ raise VoiceCancelled("kullanici dinlemeyi iptal etti") from exc
360
+ except Exception as exc: # noqa: BLE001
361
+ if self.logger:
362
+ self.logger.error("voice_stream_error", detail=str(exc))
363
+ raise VoiceUnavailableError(
364
+ f"Mikrofon akisi acilamadi: {exc}. "
365
+ "VOICE_INPUT_DEVICE'i kontrol et veya `python -m voice devices` ile listele."
366
+ ) from exc
367
+
368
+ print() # vu-meter satirini kapat
369
+ if not collected:
370
+ return np.zeros(0, dtype=np.float32)
371
+ audio = np.concatenate(collected, axis=0).flatten().astype(np.float32, copy=False)
372
+ duration = audio.size / cfg.samplerate
373
+ rms_avg = float(np.sqrt(np.mean(np.square(audio, dtype=np.float64))))
374
+ print(
375
+ f"{_C_DIM}[voice] kayit bitti: {duration:.1f}s, "
376
+ f"rms={rms_avg:.3f} (esik={cfg.silence_threshold:.3f}){_C_RESET}",
377
+ flush=True,
378
+ )
379
+ if self.logger:
380
+ self.logger.info(
381
+ "voice_record_done",
382
+ duration_s=round(duration, 2),
383
+ rms_avg=rms_avg,
384
+ )
385
+ return audio
386
+
387
+ # --- transkripsiyon -------------------------------------------------
388
+ def _transcribe(self, audio: np.ndarray) -> str:
389
+ model = self._ensure_model()
390
+ lang = None if self.cfg.language.lower() in {"auto", ""} else self.cfg.language
391
+ # Kullanici sessizlikte bekledigini sansin diye kucuk bir not.
392
+ print(f"{_C_DIM}[voice] transkript ediliyor...{_C_RESET}", flush=True)
393
+ t0 = time.monotonic()
394
+ try:
395
+ segments, info = model.transcribe(
396
+ audio,
397
+ language=lang,
398
+ beam_size=5,
399
+ vad_filter=True,
400
+ vad_parameters={"min_silence_duration_ms": 300},
401
+ )
402
+ text_parts: list[str] = []
403
+ for seg in segments:
404
+ if seg.text:
405
+ text_parts.append(seg.text.strip())
406
+ text = " ".join(p for p in text_parts if p).strip()
407
+ except KeyboardInterrupt:
408
+ print(f"\n{_C_YELLOW}[voice] transkript iptal edildi.{_C_RESET}")
409
+ if self.logger:
410
+ self.logger.warn("voice_transcribe_cancelled")
411
+ raise VoiceCancelled("transkript iptal") from None
412
+ except Exception as exc: # noqa: BLE001
413
+ if self.logger:
414
+ self.logger.error("voice_transcribe_error", detail=str(exc))
415
+ raise VoiceUnavailableError(f"Transkripsiyon hatasi: {exc}") from exc
416
+
417
+ dt = time.monotonic() - t0
418
+ detected = getattr(info, "language", None)
419
+ prob = getattr(info, "language_probability", None)
420
+ prob_str = f", lang={detected} ({prob:.2f})" if detected and prob is not None else ""
421
+ print(
422
+ f"{_C_DIM}[voice] transkript {dt:.1f}s{prob_str}{_C_RESET}"
423
+ )
424
+ return text
425
+
426
+
427
+ # -----------------------------------------------------------------------------
428
+ # CLI yardimcisi:
429
+ # python -m voice devices -> mikrofonlari listele
430
+ # python -m voice listen -> tek seferlik dinle, transkripti yaz
431
+ # -----------------------------------------------------------------------------
432
+
433
+
434
+ def _cli(argv: list[str]) -> int:
435
+ cmd = argv[1] if len(argv) > 1 else "devices"
436
+ if cmd in {"devices", "list"}:
437
+ try:
438
+ for idx, name, ch in list_input_devices():
439
+ print(f" [{idx:>2}] {name} (in_ch={ch})")
440
+ except VoiceUnavailableError as exc:
441
+ print(f"{_C_RED}{exc}{_C_RESET}", file=sys.stderr)
442
+ return 2
443
+ return 0
444
+
445
+ if cmd in {"listen", "test"}:
446
+ cfg = VoiceConfig.from_env()
447
+ v = VoiceInput(cfg)
448
+ ok, why = v.is_available()
449
+ if not ok:
450
+ print(f"{_C_RED}voice kullanilamiyor: {why}{_C_RESET}", file=sys.stderr)
451
+ return 3
452
+ try:
453
+ text = v.listen_once()
454
+ except VoiceCancelled:
455
+ return 130
456
+ except VoiceUnavailableError as exc:
457
+ print(f"{_C_RED}{exc}{_C_RESET}", file=sys.stderr)
458
+ return 4
459
+ print(f"\n{_C_CYAN}>> transkript:{_C_RESET} {text!r}")
460
+ return 0
461
+
462
+ print(__doc__)
463
+ print("\nKomutlar: devices | listen", file=sys.stderr)
464
+ return 1
465
+
466
+
467
+ if __name__ == "__main__":
468
+ sys.exit(_cli(sys.argv))