-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
2860 lines (2573 loc) · 141 KB
/
Copy pathserver.py
File metadata and controls
2860 lines (2573 loc) · 141 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
🧠 INFATON Control Center v4.0
Универсальный инструмент разработки
Git + Files + Models + Chat | PWA | Порт 9090
"""
import subprocess
import json
import os
import time
import re
import mimetypes
from datetime import datetime
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs, unquote
import urllib.request
PORT = 9090
LMS_BIN = os.path.expanduser("~/.lmstudio/bin/lms")
AGENT_TARS_BIN = "/opt/homebrew/bin/agent-tars"
LM_STUDIO_URL = "http://localhost:1234/v1"
LM_STUDIO_KEY = "lm-studio"
PROJECT_ROOT = os.environ.get("PROJECT_ROOT", os.path.expanduser("~/Projects/my-project"))
LOG_FILE = os.path.expanduser("~/Projects/automation/agent-manager/logs/agents.log")
MAX_FILE_SIZE = 2 * 1024 * 1024 # 2MB limit for editor
WORKTREES = {
# Add your projects here or use the UI to add them dynamically
# Example:
# "my-project": {"path": os.path.expanduser("~/Projects/my-project"), "branch": "main", "label": "My Project", "icon": "📁"},
}
# Allow adding custom projects via env or config
PROJECTS_FILE = os.path.expanduser("~/Projects/automation/control-panel/projects.json")
def load_projects():
"""Load additional projects from config file"""
global WORKTREES
if os.path.exists(PROJECTS_FILE):
try:
with open(PROJECTS_FILE) as f:
extra = json.load(f)
WORKTREES.update(extra)
except: pass
def save_projects():
"""Save custom projects (non-default) to config"""
defaults = {"main", "sso", "devtask", "tests"}
custom = {k: v for k, v in WORKTREES.items() if k not in defaults}
os.makedirs(os.path.dirname(PROJECTS_FILE), exist_ok=True)
with open(PROJECTS_FILE, "w") as f:
json.dump(custom, f, ensure_ascii=False, indent=2)
load_projects()
def ensure_dirs():
os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True)
def log_event(msg):
ensure_dirs()
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(LOG_FILE, "a") as f:
f.write(f"[{ts}] {msg}\n")
# ═══════════════════════════════════════
# System functions
# ═══════════════════════════════════════
def run_cmd(cmd, timeout=10, cwd=None):
try:
env = os.environ.copy()
env["PATH"] = os.path.expanduser("~/.lmstudio/bin") + ":/opt/homebrew/bin:" + os.path.expanduser("~/.local/bin:") + env.get("PATH", "")
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout, env=env, cwd=cwd)
return r.stdout.strip(), r.returncode
except subprocess.TimeoutExpired:
return "timeout", -1
except Exception as e:
return str(e), -1
def check_port(port):
try:
urllib.request.urlopen(f"http://localhost:{port}/", timeout=3)
return True
except:
return False
# ═══════════════════════════════════════
# Model functions
# ═══════════════════════════════════════
def get_lm_models():
try:
req = urllib.request.urlopen(f"{LM_STUDIO_URL}/models", timeout=5)
data = json.loads(req.read())
return [{"id": m["id"], "owned_by": m.get("owned_by", "")} for m in data.get("data", [])]
except:
return []
def get_all_models():
out, rc = run_cmd(f"{LMS_BIN} ls --json", timeout=15)
models = []
loaded_ids = [m["id"] for m in get_lm_models()]
try:
data = json.loads(out)
for m in data:
if m.get("type") == "embedding": continue
mid = m.get("modelKey", "")
models.append({
"id": mid, "display": m.get("displayName", mid),
"size_gb": round(m.get("sizeBytes", 0) / (1024**3), 1),
"vision": m.get("vision", False), "params": m.get("paramsString", ""),
"arch": m.get("architecture", ""), "ctx": m.get("maxContextLength", 0),
"loaded": mid in loaded_ids,
})
except: pass
return models
def unload_model(model_id):
try:
payload = json.dumps({"model": model_id}).encode()
req = urllib.request.Request(f"{LM_STUDIO_URL}/models/unload",
data=payload, headers={"Content-Type": "application/json"})
urllib.request.urlopen(req, timeout=10)
return True
except:
out, rc = run_cmd(f"{LMS_BIN} unload {model_id}", timeout=15)
return rc == 0
def load_model(model_id):
try:
payload = json.dumps({"model": model_id}).encode()
req = urllib.request.Request(f"{LM_STUDIO_URL}/models/load",
data=payload, headers={"Content-Type": "application/json"})
urllib.request.urlopen(req, timeout=30)
return True
except:
out, rc = run_cmd(f"{LMS_BIN} load {model_id}", timeout=30)
return rc == 0
# ═══════════════════════════════════════
# System info
# ═══════════════════════════════════════
def get_system_info():
mem_out, _ = run_cmd("sysctl -n hw.memsize")
total_gb = int(mem_out) / (1024**3) if mem_out.isdigit() else 64
pressure_out, _ = run_cmd("sysctl -n kern.memorystatus_vm_pressure_level")
pressure_map = {"0": "нет", "1": "низкое", "2": "среднее", "4": "высокое"}
pressure = pressure_map.get(pressure_out.strip(), "—")
vm_out, _ = run_cmd("vm_stat | head -5")
used_gb = total_gb * 0.5
try:
pages = {}
for line in vm_out.split("\n"):
m = re.match(r'Pages (\w+):\s+(\d+)', line)
if m: pages[m.group(1)] = int(m.group(2))
page_size = 16384
active = pages.get("active", 0) + pages.get("wired", 0) + pages.get("speculative", 0)
used_gb = (active * page_size) / (1024**3)
except: pass
swap_out, _ = run_cmd("sysctl -n vm.swapusage")
swap_used = "0"
try:
m = re.search(r'used\s*=\s*([\d.]+)M', swap_out)
if m: swap_used = str(round(float(m.group(1)) / 1024, 1))
except: pass
return {"total": round(total_gb), "used": round(used_gb, 1), "pressure": pressure, "swap_used": swap_used}
# ═══════════════════════════════════════
# Services
# ═══════════════════════════════════════
SERVICES = [
{"name": "LM Studio", "port": 1234, "url": "http://localhost:1234"},
{"name": "Open WebUI", "port": 8080, "url": "http://localhost:8080"},
{"name": "Agent TARS", "port": 8888, "url": "http://localhost:8888"},
{"name": "Control Center", "port": 9090, "url": "http://localhost:9090"},
]
def get_services_status():
result = []
for s in SERVICES:
running = True if s["port"] == PORT else check_port(s["port"])
result.append({"name": s["name"], "port": s["port"], "url": s["url"], "running": running})
return result
def get_lm_status():
try:
req = urllib.request.urlopen(f"{LM_STUDIO_URL}/models", timeout=5)
data = json.loads(req.read())
return {"running": True, "models": len(data.get("data", []))}
except:
return {"running": False, "models": 0}
# ═══════════════════════════════════════
# Agent/tmux functions
# ═══════════════════════════════════════
def get_worktree_status(name):
wt = WORKTREES.get(name)
if not wt or not os.path.exists(wt["path"]): return {"exists": False}
try:
r1 = subprocess.run(["git", "log", "--oneline", "-1"], cwd=wt["path"], capture_output=True, text=True, timeout=5)
last_commit = r1.stdout.strip() if r1.returncode == 0 else "N/A"
r2 = subprocess.run(["git", "status", "--porcelain"], cwd=wt["path"], capture_output=True, text=True, timeout=5)
changes = len([l for l in r2.stdout.strip().split("\n") if l.strip()]) if r2.stdout.strip() else 0
r3 = subprocess.run(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=wt["path"], capture_output=True, text=True, timeout=5)
actual_branch = r3.stdout.strip() if r3.returncode == 0 else wt["branch"]
return {"exists": True, "branch": actual_branch, "path": wt["path"],
"last_commit": last_commit, "uncommitted_changes": changes,
"label": wt["label"], "icon": wt["icon"]}
except Exception as e:
return {"exists": True, "error": str(e)}
def get_worktrees():
result = []
for name, wt in WORKTREES.items():
st = get_worktree_status(name)
result.append({
"id": name,
"name": wt.get("label", name),
"branch": st.get("branch", wt["branch"]),
"path": wt["path"],
"icon": wt.get("icon", "📁"),
"status": f"⚡ {st.get('uncommitted_changes', 0)} changes" if st.get("uncommitted_changes", 0) > 0 else "✓ clean",
"last_commit": st.get("last_commit", ""),
"changes": st.get("uncommitted_changes", 0),
})
return result
def get_tmux_sessions():
try:
r = subprocess.run(["tmux", "list-sessions", "-F", "#{session_name}"],
capture_output=True, text=True, timeout=5)
if r.returncode == 0:
return [s.strip() for s in r.stdout.strip().split("\n") if s.strip()]
return []
except:
return []
def get_tmux_logs(session):
if not session: return "Выберите сессию"
try:
r = subprocess.run(["tmux", "capture-pane", "-t", session, "-p", "-S", "-50"],
capture_output=True, text=True, timeout=5)
if r.returncode == 0: return r.stdout
return f"Ошибка: {r.stderr}"
except Exception as e:
return f"Ошибка: {e}"
def start_agent(agent_type, worktree, model=None):
wt = WORKTREES.get(worktree)
if not wt: return {"ok": False, "error": f"Worktree {worktree} не найден"}
model = model or "qwen2.5-coder-32b-instruct-4bit"
if agent_type == "aider":
cmd = f"aider --model openai/{model} --no-auto-commits --dark-mode"
elif agent_type == "opencode":
cmd = "opencode"
elif agent_type == "smolagent":
cmd = f"smolagent --model openai/{model}"
else:
return {"ok": False, "error": f"Неизвестный тип: {agent_type}"}
try:
env_str = f"export PATH=$HOME/.local/bin:/opt/homebrew/bin:$PATH && export OPENAI_API_BASE={LM_STUDIO_URL} && export OPENAI_API_KEY={LM_STUDIO_KEY} && cd {wt['path']} && {cmd}"
r = subprocess.run(["tmux", "new-window", "-t", "agents", "-n", f"{agent_type}-{worktree}", "/bin/zsh", "-c", env_str],
capture_output=True, text=True, timeout=5)
if r.returncode == 0:
log_event(f"START: {agent_type} в {worktree} ({model})")
return {"ok": True}
return {"ok": False, "error": "tmux сессия 'agents' не найдена. Запустите start-agent-team.sh"}
except Exception as e:
return {"ok": False, "error": str(e)}
# ═══════════════════════════════════════
# Smart Chat with tool use (v4.1)
# ═══════════════════════════════════════
import platform
import socket
def _detect_intent(message):
"""Detect user intent from message"""
msg = message.lower()
# File search intent
search_words = ['найди', 'найти', 'поиск', 'поищи', 'search', 'find', 'где ', 'покажи файл',
'есть ли файл', 'документ', 'ищи', 'отыщи', 'locate', 'grep']
file_words = ['файл', 'документ', 'file', 'doc', 'pdf', 'txt', 'папк', 'директори',
'folder', 'каталог', 'проект', 'исходник', 'скрипт', '.py', '.ts', '.js', '.md']
has_search = any(w in msg for w in search_words)
has_file = any(w in msg for w in file_words)
if has_search and has_file:
return 'file_search'
if has_search and not any(w in msg for w in ['инфо', 'что такое', 'как ', 'зачем', 'почему']):
return 'file_search'
# System info intent
sys_words = ['диск', 'память', 'cpu', 'процессор', 'место', 'ram', 'систем', 'uptime',
'температур', 'батаре', 'заряд', 'ip адрес', 'hostname', 'версия os']
if any(w in msg for w in sys_words):
return 'system_info'
# Process intent
proc_words = ['процесс', 'запущен', 'работает ли', 'порт', 'pid', 'kill', 'убить процесс',
'сервис', 'демон', 'слушает порт']
if any(w in msg for w in proc_words):
return 'process_info'
return 'chat'
def _extract_search_query(message):
"""Extract what to search for from message"""
msg = message.lower()
# Remove command words
for w in ['найди', 'найти', 'поиск', 'поищи', 'search', 'find', 'покажи', 'ищи', 'отыщи', 'locate',
'на моем', 'на моём', 'моем', 'моём', 'ноутбуке', 'макбуке', 'macbook', 'компьютере',
'все ', 'все\n', 'мне ', 'пожалуйста', 'документы', 'файлы', 'про ', 'о ', 'об ',
'в папке', 'в каталоге', 'в директории']:
msg = msg.replace(w, ' ')
# Clean up
query = ' '.join(msg.split()).strip()
# If nothing left, use original
if len(query) < 2:
# Try to extract quoted text or capitalized words
import re
caps = re.findall(r'[A-ZА-Я][a-zA-Zа-яА-Я0-9_-]+', message)
if caps:
query = ' '.join(caps)
else:
query = message
return query
def _run_file_search(query, message):
"""Actually search files on the machine"""
results = {}
# 1. Spotlight search (macOS mdfind - fastest, searches content + filenames)
mdfind_cmd = f"mdfind '{query}' 2>/dev/null | head -30"
out, rc = run_cmd(mdfind_cmd, timeout=15)
if rc == 0 and out:
results['spotlight'] = [f for f in out.split('\n') if f.strip()]
# 2. Filename search in common locations
find_cmd = f"find ~/Projects ~/Documents ~/Desktop ~/Downloads -iname '*{query}*' -type f 2>/dev/null | head -20"
out2, rc2 = run_cmd(find_cmd, timeout=10)
if rc2 == 0 and out2:
results['filenames'] = [f for f in out2.split('\n') if f.strip()]
# 3. Content search in project files
grep_cmd = f"grep -rl --include='*.md' --include='*.txt' --include='*.py' --include='*.ts' --include='*.tsx' --include='*.json' --include='*.yaml' --include='*.yml' --include='*.html' --include='*.css' '{query}' ~/Projects/ 2>/dev/null | head -20"
out3, rc3 = run_cmd(grep_cmd, timeout=15)
if rc3 == 0 and out3:
results['content'] = [f for f in out3.split('\n') if f.strip()]
return results
def _format_search_results(query, results):
"""Format search results as readable text"""
total = sum(len(v) for v in results.values())
if total == 0:
return f"🔍 По запросу **\"{query}\"** ничего не найдено на этом компьютере.\n\nПопробуйте:\n- Другие ключевые слова\n- Проверить правописание\n- Поискать в конкретной папке через файловый менеджер (вкладка 📁)"
lines = [f"🔍 Найдено **{total}** результатов по запросу **\"{query}\"**:\n"]
# Spotlight results
if results.get('spotlight'):
lines.append("### 📂 Spotlight (macOS)")
for f in results['spotlight'][:15]:
# Shorten home path
f_short = f.replace(os.path.expanduser('~'), '~')
lines.append(f"- `{f_short}`")
# Filename matches
if results.get('filenames'):
seen = set(results.get('spotlight', []))
new_files = [f for f in results['filenames'] if f not in seen]
if new_files:
lines.append("\n### 📄 Совпадения по имени файла")
for f in new_files[:10]:
f_short = f.replace(os.path.expanduser('~'), '~')
lines.append(f"- `{f_short}`")
# Content matches
if results.get('content'):
seen = set(results.get('spotlight', []) + results.get('filenames', []))
new_files = [f for f in results['content'] if f not in seen]
if new_files:
lines.append("\n### 🔎 Содержат текст в файле")
for f in new_files[:10]:
f_short = f.replace(os.path.expanduser('~'), '~')
lines.append(f"- `{f_short}`")
return '\n'.join(lines)
def _get_system_context(project_id=None):
"""Get current system context for LLM. Only include project info if project_id is given."""
uname = platform.uname()
home = os.path.expanduser('~')
user = os.environ.get('USER', 'unknown')
hostname = socket.gethostname()
project_block = ""
if project_id and project_id in WORKTREES:
wt = WORKTREES[project_id]
project_block = f"""
Активный проект: {wt.get('label', project_id)}
Путь: {wt['path']}
Ветка: {wt.get('branch', '?')}
Используй этот контекст при ответах о коде и структуре этого проекта."""
return f"""Ты — ИИ-помощник в INFATON Control Center v4.1, работающий ЛОКАЛЬНО на компьютере пользователя.
Среда:
- ОС: {uname.system} {uname.release} ({uname.machine})
- Хост: {hostname}
- Пользователь: {user}
- Домашняя папка: {home}
{project_block}
Правила:
- Отвечай на русском, кратко и по делу
- Если вопрос про код — показывай примеры
- Ты работаешь ЛОКАЛЬНО, у тебя есть доступ к файлам через Control Center
- НЕ давай инструкции для Windows если система macOS и наоборот
- НЕ упоминай и не ссылайся на проекты пользователя, если он сам не спросил
- Если проект не выбран — ты универсальный помощник, не привязанный к конкретному проекту"""
def _get_system_info():
"""Gather system info for sys info requests"""
parts = []
# Memory
out, _ = run_cmd("vm_stat | head -5; echo '---'; sysctl -n hw.memsize", timeout=5)
parts.append(f"**Память:**\n```\n{out}\n```")
# Disk
out2, _ = run_cmd("df -h / | tail -1", timeout=5)
parts.append(f"**Диск:**\n```\n{out2}\n```")
# CPU
out3, _ = run_cmd("sysctl -n machdep.cpu.brand_string 2>/dev/null || echo 'N/A'; echo 'Load:'; uptime", timeout=5)
parts.append(f"**CPU:**\n```\n{out3}\n```")
# Battery
out4, _ = run_cmd("pmset -g batt 2>/dev/null | head -3", timeout=5)
if out4:
parts.append(f"**Батарея:**\n```\n{out4}\n```")
# Network
out5, _ = run_cmd("ifconfig en0 | grep 'inet ' | awk '{print $2}'; echo 'Tailscale:'; tailscale ip -4 2>/dev/null || echo 'N/A'", timeout=5)
parts.append(f"**Сеть:**\n```\n{out5}\n```")
return '\n\n'.join(parts)
def _get_process_info(message):
"""Get process/port info"""
msg = message.lower()
parts = []
# Check for specific port
import re
port_match = re.search(r'порт[уе]?\s*(\d+)|port\s*(\d+)|:(\d+)', msg)
if port_match:
port = port_match.group(1) or port_match.group(2) or port_match.group(3)
out, _ = run_cmd(f"lsof -i :{port} -P -n 2>/dev/null | head -10", timeout=5)
parts.append(f"**Порт {port}:**\n```\n{out or 'Свободен'}\n```")
# Top processes
out2, _ = run_cmd("ps aux --sort=-%mem 2>/dev/null | head -10 || ps aux | head -10", timeout=5)
parts.append(f"**Топ процессы:**\n```\n{out2}\n```")
# Listening ports
out3, _ = run_cmd("lsof -i -P -n 2>/dev/null | grep LISTEN | head -15", timeout=5)
parts.append(f"**Открытые порты:**\n```\n{out3}\n```")
return '\n\n'.join(parts)
def _extract_file_content(attachment):
"""Extract text content from attached file"""
import base64, tempfile
name = attachment.get('name', '')
data_url = attachment.get('data', '')
is_image = attachment.get('isImage', False)
if is_image:
return None, data_url # Return as image for vision model
# Decode base64 data
try:
# data:application/pdf;base64,XXXX
if ',' in data_url:
b64_data = data_url.split(',', 1)[1]
else:
b64_data = data_url
raw = base64.b64decode(b64_data)
except:
return f"[Ошибка чтения файла {name}]", None
ext = name.rsplit('.', 1)[-1].lower() if '.' in name else ''
# Plain text files
if ext in ('txt', 'md', 'json', 'py', 'ts', 'js', 'css', 'html', 'csv', 'log', 'yaml', 'yml', 'sh', 'bat'):
try:
return raw.decode('utf-8', errors='replace'), None
except:
return raw.decode('latin-1', errors='replace'), None
# PDF — use macOS textutil or pdftotext
if ext == 'pdf':
with tempfile.NamedTemporaryFile(suffix='.pdf', delete=False) as tmp:
tmp.write(raw)
tmp_path = tmp.name
# Try pdftotext first, then textutil
out, rc = run_cmd(f"pdftotext '{tmp_path}' - 2>/dev/null || textutil -convert txt -stdout '{tmp_path}' 2>/dev/null", timeout=15)
os.unlink(tmp_path)
if out.strip():
return out[:10000], None # Limit to 10K chars
return f"[PDF: не удалось извлечь текст из {name}]", None
# DOCX — use textutil (macOS built-in)
if ext in ('doc', 'docx'):
with tempfile.NamedTemporaryFile(suffix=f'.{ext}', delete=False) as tmp:
tmp.write(raw)
tmp_path = tmp.name
out, rc = run_cmd(f"textutil -convert txt -stdout '{tmp_path}' 2>/dev/null", timeout=15)
os.unlink(tmp_path)
if out.strip():
return out[:10000], None
return f"[DOCX: не удалось извлечь текст из {name}]", None
# XLSX — use python3 inline
if ext in ('xls', 'xlsx'):
with tempfile.NamedTemporaryFile(suffix=f'.{ext}', delete=False) as tmp:
tmp.write(raw)
tmp_path = tmp.name
# Try using python csv export
out, rc = run_cmd(f"""python3 -c "
import csv, io, sys
try:
import openpyxl
wb = openpyxl.load_workbook('{tmp_path}', read_only=True, data_only=True)
result = []
for ws in wb.worksheets:
result.append(f'=== Sheet: {{ws.title}} ===')
for row in ws.iter_rows(max_row=200, values_only=True):
result.append('\t'.join(str(c) if c is not None else '' for c in row))
print('\n'.join(result[:500]))
except ImportError:
print('[XLSX: openpyxl не установлен, установите: pip3 install openpyxl]')
except Exception as e:
print(f'[XLSX ошибка: {{e}}]')
" 2>/dev/null""", timeout=15)
os.unlink(tmp_path)
if out.strip():
return out[:10000], None
return f"[XLSX: не удалось прочитать {name}]", None
return f"[Формат .{ext} не поддерживается]", None
def quick_chat(message, model=None, project=None, attachments=None):
"""Enhanced chat with tool use and system context"""
models = get_lm_models()
if not model:
model = models[0]["id"] if models else "qwen2.5-coder-32b-instruct-4bit"
# Process file attachments
extra_context = ""
image_data = None
if attachments:
for att in attachments:
text, img = _extract_file_content(att)
if text:
extra_context += f"\n\n--- Содержимое файла {att.get('name', '?')} ---\n{text}\n---"
if img:
image_data = img # Use last image for vision
if extra_context:
message = message + extra_context
intent = _detect_intent(message)
# === File search: execute locally, then pass results to LLM ===
if intent == 'file_search':
query = _extract_search_query(message)
results = _run_file_search(query, message)
formatted = _format_search_results(query, results)
# If we have results, ask LLM to summarize/comment
if sum(len(v) for v in results.values()) > 0:
try:
context = f"Пользователь попросил: {message}\n\nРезультаты реального поиска на компьютере:\n{formatted}\n\nДай краткий комментарий к найденным файлам (1-2 предложения). Не повторяй список."
payload = json.dumps({"model": model, "messages": [
{"role": "system", "content": _get_system_context(project)},
{"role": "user", "content": context}
], "temperature": 0.3, "max_tokens": 512, "stream": False}).encode()
req = urllib.request.Request(f"{LM_STUDIO_URL}/chat/completions", data=payload,
headers={"Content-Type": "application/json", "Authorization": f"Bearer {LM_STUDIO_KEY}"})
with urllib.request.urlopen(req, timeout=60) as resp:
comment = json.loads(resp.read())["choices"][0]["message"]["content"]
return formatted + "\n\n---\n💬 " + comment
except:
return formatted
else:
return formatted
# === System info: gather and return ===
if intent == 'system_info':
info = _get_system_info()
return f"📊 **Информация о системе:**\n\n{info}"
# === Process info ===
if intent == 'process_info':
info = _get_process_info(message)
return f"⚙️ **Информация о процессах:**\n\n{info}"
# === Regular chat with system context ===
try:
# Build messages with optional image
user_msg = message
if image_data and 'vl' in model.lower():
# Vision model — send image inline
messages = [
{"role": "system", "content": _get_system_context(project)},
{"role": "user", "content": [
{"type": "text", "text": message},
{"type": "image_url", "image_url": {"url": image_data}}
]}
]
else:
messages = [
{"role": "system", "content": _get_system_context(project)},
{"role": "user", "content": message}
]
payload = json.dumps({"model": model, "messages": messages, "temperature": 0.3, "max_tokens": 2048, "stream": False}).encode()
req = urllib.request.Request(f"{LM_STUDIO_URL}/chat/completions", data=payload,
headers={"Content-Type": "application/json", "Authorization": f"Bearer {LM_STUDIO_KEY}"})
with urllib.request.urlopen(req, timeout=120) as resp:
return json.loads(resp.read())["choices"][0]["message"]["content"]
except urllib.error.URLError as e:
return f"⚠️ LM Studio недоступен: {e}\n\nПроверьте что LM Studio запущен на порту 1234."
except Exception as e:
return f"❌ Ошибка: {e}"
# ═══════════════════════════════════════
# GIT functions (NEW in v4)
# ═══════════════════════════════════════
def _resolve_wt_path(wt_id):
"""Resolve worktree path from ID or direct path"""
if wt_id in WORKTREES:
return WORKTREES[wt_id]["path"]
# Try direct path
if os.path.isdir(wt_id):
return wt_id
return None
def git_status_detailed(wt_id):
"""Full git status: branch, ahead/behind, files, last commits"""
path = _resolve_wt_path(wt_id)
if not path: return {"error": f"Project not found: {wt_id}"}
# Current branch
branch, _ = run_cmd("git rev-parse --abbrev-ref HEAD", cwd=path)
# Status porcelain
status_out, _ = run_cmd("git status --porcelain -u", cwd=path)
files = []
for line in status_out.split("\n"):
if not line.strip(): continue
st = line[:2]
fname = line[3:]
files.append({"status": st.strip(), "file": fname})
# Ahead/behind
ahead_behind, _ = run_cmd("git rev-list --left-right --count HEAD...@{upstream} 2>/dev/null || echo '0\t0'", cwd=path)
parts = ahead_behind.split("\t")
ahead = int(parts[0]) if len(parts) >= 2 else 0
behind = int(parts[1]) if len(parts) >= 2 else 0
# Last 5 commits
log_out, _ = run_cmd('git log --oneline -5 --format="%h|%s|%an|%ar"', cwd=path)
commits = []
for line in log_out.split("\n"):
if not line.strip(): continue
p = line.split("|", 3)
if len(p) >= 4:
commits.append({"hash": p[0], "message": p[1], "author": p[2], "time": p[3]})
elif len(p) >= 2:
commits.append({"hash": p[0], "message": p[1], "author": "", "time": ""})
# Remote URL
remote, _ = run_cmd("git remote get-url origin 2>/dev/null", cwd=path)
return {
"branch": branch, "files": files, "ahead": ahead, "behind": behind,
"commits": commits, "remote": remote, "path": path,
"clean": len(files) == 0
}
def git_pull(wt_id):
path = _resolve_wt_path(wt_id)
if not path: return {"ok": False, "error": "Project not found"}
out, rc = run_cmd("git pull --rebase 2>&1", timeout=30, cwd=path)
log_event(f"GIT PULL: {wt_id} → {'OK' if rc == 0 else 'FAIL'}")
return {"ok": rc == 0, "output": out}
def git_push(wt_id):
path = _resolve_wt_path(wt_id)
if not path: return {"ok": False, "error": "Project not found"}
out, rc = run_cmd("git push 2>&1", timeout=30, cwd=path)
log_event(f"GIT PUSH: {wt_id} → {'OK' if rc == 0 else 'FAIL'}")
return {"ok": rc == 0, "output": out}
def git_commit(wt_id, message, files=None):
path = _resolve_wt_path(wt_id)
if not path: return {"ok": False, "error": "Project not found"}
if not message: return {"ok": False, "error": "Empty commit message"}
if files:
for f in files:
run_cmd(f"git add {json.dumps(f)}", cwd=path)
else:
run_cmd("git add -A", cwd=path)
out, rc = run_cmd(f'git commit -m {json.dumps(message)} 2>&1', timeout=15, cwd=path)
log_event(f"GIT COMMIT: {wt_id} — {message[:50]}")
return {"ok": rc == 0, "output": out}
def git_diff(wt_id, file_path=None):
path = _resolve_wt_path(wt_id)
if not path: return {"error": "Project not found"}
if file_path:
safe_file = file_path.replace("'", "\\'")
out, _ = run_cmd(f"git diff -- '{safe_file}' 2>&1; git diff --cached -- '{safe_file}' 2>&1", cwd=path)
else:
out, _ = run_cmd("git diff 2>&1; git diff --cached 2>&1", cwd=path)
return {"diff": out}
def git_checkout(wt_id, branch):
path = _resolve_wt_path(wt_id)
if not path: return {"ok": False, "error": "Project not found"}
out, rc = run_cmd(f"git checkout {branch} 2>&1", timeout=15, cwd=path)
return {"ok": rc == 0, "output": out}
def git_branches(wt_id):
path = _resolve_wt_path(wt_id)
if not path: return {"error": "Project not found"}
out, _ = run_cmd("git branch -a --format='%(refname:short)|%(objectname:short)|%(committerdate:relative)'", cwd=path)
branches = []
current, _ = run_cmd("git rev-parse --abbrev-ref HEAD", cwd=path)
for line in out.split("\n"):
if not line.strip(): continue
p = line.split("|", 2)
branches.append({
"name": p[0], "hash": p[1] if len(p) > 1 else "",
"time": p[2] if len(p) > 2 else "",
"current": p[0] == current
})
return {"branches": branches, "current": current}
def git_stash(wt_id, action="push", message=""):
path = _resolve_wt_path(wt_id)
if not path: return {"ok": False, "error": "Project not found"}
if action == "push":
cmd = f'git stash push -m {json.dumps(message or "WIP")} 2>&1'
elif action == "pop":
cmd = "git stash pop 2>&1"
elif action == "list":
cmd = "git stash list 2>&1"
else:
return {"ok": False, "error": f"Unknown stash action: {action}"}
out, rc = run_cmd(cmd, cwd=path)
return {"ok": rc == 0, "output": out}
# ═══════════════════════════════════════
# FILE functions (NEW in v4)
# ═══════════════════════════════════════
BINARY_EXTS = {'.png', '.jpg', '.jpeg', '.gif', '.ico', '.webp', '.svg', '.woff', '.woff2', '.ttf', '.eot',
'.zip', '.gz', '.tar', '.pdf', '.mp4', '.mp3', '.wav', '.mov', '.avi',
'.pyc', '.pyo', '.so', '.dylib', '.o', '.a', '.exe', '.dll'}
SKIP_DIRS = {'node_modules', '.next', '.build', '.git', '__pycache__', '.cache', 'dist', '.yarn', 'venv', '.venv'}
def list_files(base_path, rel_path=""):
"""List directory contents with git status indicators"""
full = os.path.join(base_path, rel_path) if rel_path else base_path
if not os.path.isdir(full): return {"error": "Not a directory"}
# Get git status for this directory
git_status = {}
try:
out, rc = run_cmd("git status --porcelain -u", cwd=base_path)
if rc == 0:
for line in out.split("\n"):
if not line.strip(): continue
st = line[:2].strip()
fname = line[3:]
git_status[fname] = st
except: pass
items = []
try:
entries = sorted(os.listdir(full), key=lambda x: (not os.path.isdir(os.path.join(full, x)), x.lower()))
except PermissionError:
return {"error": "Permission denied"}
for entry in entries:
if entry.startswith('.') and entry not in ('.env', '.gitignore', '.eslintrc.json', '.prettierrc'):
continue
if entry in SKIP_DIRS: continue
fpath = os.path.join(full, entry)
rpath = os.path.join(rel_path, entry) if rel_path else entry
is_dir = os.path.isdir(fpath)
git_st = ""
if is_dir:
# Check if any file inside has git changes
for gf, gs in git_status.items():
if gf.startswith(rpath + "/"):
git_st = "M"
break
else:
git_st = git_status.get(rpath, "")
item = {"name": entry, "path": rpath, "is_dir": is_dir, "git_status": git_st}
if not is_dir:
try:
item["size"] = os.path.getsize(fpath)
except: item["size"] = 0
_, ext = os.path.splitext(entry)
item["ext"] = ext.lower()
item["binary"] = ext.lower() in BINARY_EXTS
items.append(item)
return {"items": items, "path": rel_path, "base": base_path}
def read_file(base_path, rel_path):
"""Read file contents for editor"""
full = os.path.join(base_path, rel_path)
if not os.path.isfile(full): return {"error": "File not found"}
try:
size = os.path.getsize(full)
if size > MAX_FILE_SIZE:
return {"error": f"File too large: {size} bytes (max {MAX_FILE_SIZE})"}
_, ext = os.path.splitext(full)
if ext.lower() in BINARY_EXTS:
return {"error": "Binary file, cannot edit"}
with open(full, 'r', errors='replace') as f:
content = f.read()
return {"content": content, "path": rel_path, "size": size, "ext": ext.lower()}
except Exception as e:
return {"error": str(e)}
def write_file(base_path, rel_path, content):
"""Save file from editor"""
full = os.path.join(base_path, rel_path)
if not full.startswith(base_path):
return {"ok": False, "error": "Path traversal blocked"}
try:
os.makedirs(os.path.dirname(full), exist_ok=True)
with open(full, 'w') as f:
f.write(content)
return {"ok": True, "size": len(content)}
except Exception as e:
return {"ok": False, "error": str(e)}
def create_item(base_path, rel_path, is_dir=False):
"""Create file or directory"""
full = os.path.join(base_path, rel_path)
try:
if is_dir:
os.makedirs(full, exist_ok=True)
else:
os.makedirs(os.path.dirname(full), exist_ok=True)
with open(full, 'w') as f: pass
return {"ok": True}
except Exception as e:
return {"ok": False, "error": str(e)}
def delete_item(base_path, rel_path):
"""Delete file or directory"""
full = os.path.join(base_path, rel_path)
if not full.startswith(base_path):
return {"ok": False, "error": "Path traversal blocked"}
try:
if os.path.isdir(full):
import shutil
shutil.rmtree(full)
else:
os.remove(full)
return {"ok": True}
except Exception as e:
return {"ok": False, "error": str(e)}
def search_files(base_path, query, max_results=50):
"""Search in files using grep"""
try:
safe_q = query.replace("'", "\\'")
out, rc = run_cmd(
f"grep -rn --include='*.py' --include='*.ts' --include='*.tsx' --include='*.js' --include='*.jsx' --include='*.json' --include='*.css' --include='*.html' --include='*.md' --include='*.yaml' --include='*.yml' --include='*.prisma' --include='*.env' -l '{safe_q}' . 2>/dev/null | head -{max_results}",
timeout=15, cwd=base_path
)
files = [f.lstrip('./') for f in out.split("\n") if f.strip()]
# Get matches with context
results = []
for fpath in files[:20]:
out2, _ = run_cmd(f"grep -n '{safe_q}' '{fpath}' 2>/dev/null | head -5", cwd=base_path)
matches = []
for line in out2.split("\n"):
if ":" in line:
ln, txt = line.split(":", 1)
matches.append({"line": int(ln) if ln.isdigit() else 0, "text": txt[:200]})
results.append({"file": fpath, "matches": matches})
return {"results": results, "total": len(files)}
except Exception as e:
return {"error": str(e)}
# ═══════════════════════════════════════
# Project management (NEW in v4)
# ═══════════════════════════════════════
def add_project(key, path, label, icon="📁"):
"""Add a new project to the panel"""
if not os.path.isdir(path):
return {"ok": False, "error": f"Directory not found: {path}"}
# Detect branch
branch_out, rc = run_cmd("git rev-parse --abbrev-ref HEAD 2>/dev/null", cwd=path)
branch = branch_out if rc == 0 else "—"
WORKTREES[key] = {"path": path, "branch": branch, "label": label, "icon": icon}
save_projects()
return {"ok": True}
def remove_project(key):
defaults = {"main", "sso", "devtask", "tests"}
if key in defaults:
return {"ok": False, "error": "Cannot remove default project"}
if key in WORKTREES:
del WORKTREES[key]
save_projects()
return {"ok": True}
return {"ok": False, "error": "Project not found"}
# ═══════════════════════════════════════
# PWA Assets
# ═══════════════════════════════════════
MANIFEST_JSON = json.dumps({
"name": "INFATON Control Center",
"short_name": "INFATON CC",
"description": "Универсальный инструмент разработки",
"start_url": "/",
"display": "standalone",
"background_color": "#0d1017",
"theme_color": "#7c3aed",
"orientation": "any",
"icons": [
{"src": "/icon-192.svg", "sizes": "192x192", "type": "image/svg+xml"},
{"src": "/icon-512.svg", "sizes": "512x512", "type": "image/svg+xml"}
]
})
ICON_SVG = """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<defs><linearGradient id="g" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" style="stop-color:#6366f1"/><stop offset="100%" style="stop-color:#a855f7"/></linearGradient></defs>
<rect width="512" height="512" rx="96" fill="url(#g)"/>
<text x="256" y="320" text-anchor="middle" font-size="280" fill="white" font-family="system-ui">🧠</text>
</svg>"""
SW_JS = """
const CACHE = 'infaton-cc-v4';
const PRECACHE = ['/', '/manifest.json'];
self.addEventListener('install', e => { e.waitUntil(caches.open(CACHE).then(c => c.addAll(PRECACHE))); self.skipWaiting(); });
self.addEventListener('activate', e => { e.waitUntil(caches.keys().then(ks => Promise.all(ks.filter(k => k !== CACHE).map(k => caches.delete(k))))); });
self.addEventListener('fetch', e => {
if (e.request.url.includes('/api')) return;
e.respondWith(fetch(e.request).then(r => { const c = r.clone(); caches.open(CACHE).then(cache => cache.put(e.request, c)); return r; }).catch(() => caches.match(e.request)));
});
"""
HTML_PAGE = r"""<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#0d1017">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<link rel="manifest" href="/manifest.json">
<link rel="icon" href="/icon-192.svg">
<title>INFATON Control Center</title>
<style>
/* ═══ CSS Variables ═══ */
:root{
--bg-0:#0d1017;--bg-1:#131721;--bg-2:#1a1f2e;--bg-3:#222738;
--tx-0:#e6e6e6;--tx-1:#a0a8c0;--tx-2:#6b7394;
--accent:#7c3aed;--accent2:#a855f7;--green:#22c55e;--red:#ef4444;--yellow:#eab308;--blue:#3b82f6;
--mono:'SF Mono','Fira Code','JetBrains Mono',monospace;
--sans:'Inter',-apple-system,system-ui,sans-serif;
--radius:10px;--glass:rgba(255,255,255,0.04);
}
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:var(--sans);background:var(--bg-0);color:var(--tx-0);overflow-x:hidden;min-height:100vh}
::-webkit-scrollbar{width:6px;height:6px}
::-webkit-scrollbar-track{background:var(--bg-1)}
::-webkit-scrollbar-thumb{background:var(--bg-3);border-radius:3px}
/* ═══ Layout ═══ */
.app{display:flex;height:100vh;overflow:hidden}
.sidebar{width:52px;background:var(--bg-1);border-right:1px solid var(--bg-3);display:flex;flex-direction:column;align-items:center;padding:8px 0;gap:2px;flex-shrink:0;z-index:50}
.sidebar .logo{width:36px;height:36px;border-radius:10px;background:linear-gradient(135deg,var(--accent),var(--accent2));display:flex;align-items:center;justify-content:center;font-size:20px;margin-bottom:12px;cursor:pointer}
.sidebar .nav-btn{width:40px;height:40px;border-radius:8px;border:none;background:transparent;color:var(--tx-2);font-size:18px;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all .15s}
.sidebar .nav-btn:hover{background:var(--glass);color:var(--tx-1)}
.sidebar .nav-btn.active{background:var(--accent);color:#fff}
.sidebar .spacer{flex:1}