-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.py
More file actions
1885 lines (1632 loc) · 71 KB
/
Copy pathmain.py
File metadata and controls
1885 lines (1632 loc) · 71 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
# main.py — Scryptian Core
# Skill scanner | Hotkey | UI bar
import os
import sys
import re
import importlib.util
import threading
import tkinter as tk
import pyperclip
import keyboard
import time
import datetime
import bridge
import telemetry
import tray
import store
import updater
from ui import StorePanel
import autostart
import queue
import selection_watcher
import pins as pins_module
import main_pins
import skill_editor
import skill_settings
import core
IS_WINDOWS = sys.platform == "win32"
if IS_WINDOWS:
import ctypes
# ── DPI (crisp rendering on Windows) ──
if IS_WINDOWS:
try:
ctypes.windll.shcore.SetProcessDpiAwareness(2)
except Exception:
try:
ctypes.windll.user32.SetProcessDPIAware()
except Exception:
pass
# ── Settings ──
from config import HOTKEY, BASE_DIR, APP_VERSION, MAX_SKILL_INPUT_CHARS
from core.registry import _version_ge
import bootstrap
SKILLS_DIR = os.path.join(BASE_DIR, "skills")
_BROWSERS = {
"chrome.exe", "msedge.exe", "firefox.exe", "brave.exe",
"opera.exe", "opera_gx.exe", "vivaldi.exe", "arc.exe",
}
# Known sites, detected LOCALLY from the browser window title. Only the matched
# label below is ever sent — the raw title (which may contain personal data)
# never leaves the machine. No match -> "other". First hit wins.
_SITE_KEYWORDS = (
("youtube", ("youtube",)),
("reddit", ("reddit",)),
("gmail", ("gmail",)),
("outlook", ("outlook",)),
("chatgpt", ("chatgpt", "openai")),
("github", ("github",)),
("stackoverflow", ("stack overflow", "stackoverflow")),
("wikipedia", ("wikipedia", "википедия")),
("twitter/x", ("twitter", "/ x", "x.com")),
("facebook", ("facebook",)),
("instagram", ("instagram",)),
("linkedin", ("linkedin",)),
("telegram", ("telegram",)),
("whatsapp", ("whatsapp",)),
("discord", ("discord",)),
("amazon", ("amazon",)),
("netflix", ("netflix",)),
("medium", ("medium",)),
("quora", ("quora",)),
("vk", ("vkontakte", "вконтакте")),
("yandex", ("yandex", "яндекс")),
("google-docs", ("google docs", "google документы")),
("google-search", ("google search", " - поиск в google")),
("notion", ("notion",)),
)
def _detect_site(title: str) -> str:
"""Map a browser window title to a whitelisted site label (local only).
Returns the matched label, or "other". The input title is used purely for
this local lookup and is never stored or transmitted.
"""
t = (title or "").lower()
if not t:
return "other"
for label, keys in _SITE_KEYWORDS:
for k in keys:
if k in t:
return label
return "other"
def _get_source_app(hwnd) -> dict:
"""Describe the window active before Scryptian opened.
Returns {"source_app": <exe>} and, only for browsers, {"source_site": <label>}
where the label comes from a local whitelist. The raw window title is never
included, so no personal data (document names, email subjects, private pages)
is ever transmitted. Scryptian's own process is ignored.
"""
result = {"source_app": "unknown"}
try:
if not hwnd:
return result
import ctypes
import ctypes.wintypes
pid = ctypes.wintypes.DWORD()
ctypes.windll.user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
# Ignore Scryptian's own windows — they must never count as a source.
if pid.value == ctypes.windll.kernel32.GetCurrentProcessId():
return result
h = ctypes.windll.kernel32.OpenProcess(0x0410, False, pid.value)
buf = ctypes.create_unicode_buffer(260)
ctypes.windll.psapi.GetModuleFileNameExW(h, None, buf, 260)
ctypes.windll.kernel32.CloseHandle(h)
exe = os.path.basename(buf.value).lower() or "unknown"
result["source_app"] = exe
# Only browsers get site-level context — and only as a whitelisted label
# derived locally. For other apps the exe (e.g. winword.exe) is enough.
if exe in _BROWSERS:
length = ctypes.windll.user32.GetWindowTextLengthW(hwnd)
title = ""
if length:
tbuf = ctypes.create_unicode_buffer(length + 1)
ctypes.windll.user32.GetWindowTextW(hwnd, tbuf, length + 1)
title = tbuf.value
result["source_site"] = _detect_site(title)
return result
except Exception:
return result
def _format_last_used(iso: str) -> str:
"""Convert ISO UTC timestamp to human-readable relative string."""
try:
dt = datetime.datetime.fromisoformat(iso)
delta = datetime.datetime.now(datetime.timezone.utc) - dt.replace(tzinfo=datetime.timezone.utc)
days = delta.days
if days == 0:
return "today"
elif days == 1:
return "yesterday"
elif days < 7:
return f"{days}d ago"
elif days < 30:
return f"{days // 7}w ago"
else:
return f"{days // 30}mo ago"
except Exception:
return ""
def _track_skill(skill_id: str) -> None:
"""Record count and last_used for a skill after successful run."""
state = bridge.get_state(skill_id)
bridge.set_state(skill_id, {
"count": state.get("count", 0) + 1,
"last_used": datetime.datetime.now(datetime.timezone.utc).isoformat(),
})
def _build_skill_event(skill, input_text, elapsed, **extra):
"""Build a detailed skill_run telemetry payload."""
inp = core.get_input()
input_type = inp["type"] if inp else "text"
ext = None
if input_type == "file" and input_text:
_, ext = os.path.splitext(input_text)
ext = ext.lower() if ext else None
sec = round(elapsed, 2)
if sec < 1:
bucket = "<1s"
elif sec < 5:
bucket = "1-5s"
elif sec < 30:
bucket = "5-30s"
else:
bucket = "30s+"
skill_id = skill.get("id") or skill.get("filename", "").replace(".py", "")
state = bridge.get_state(skill_id)
is_first = state.get("count", 0) == 0
return {
"skill_id": skill_id,
"skill_title": skill.get("title", ""),
"skill_version": skill.get("version", ""),
"skill_author": skill.get("author", ""),
"needs_llm": skill.get("needs_llm", True),
"input_type": input_type,
"input_ext": ext,
"text_len": len(input_text or ""),
"word_count": len((input_text or "").split()),
"elapsed_sec": sec,
"duration_bucket": bucket,
"is_first_run": is_first,
**extra,
}
# ── UI ──
class ScryptianBar:
def __init__(self, root, skills, toolbar=None):
self.root = root
self.skills = skills
self.toolbar = toolbar
self.filtered = list(skills)
self.selected_index = 0
self.window = None
self.visible = False
self.has_result = False
self.last_result = ""
self.processing = False
self.pending_result = None
self._has_add_item = False
self._has_folder_item = False
self._has_feedback_item = False
self._has_store_item = False
self.store_frame = None
self.in_store = False
self.store_panel = StorePanel(self)
self._source_hwnd = None
def toggle(self):
"""Show/hide the bar (called from any thread)."""
if IS_WINDOWS and not self.visible:
try:
self._source_hwnd = ctypes.windll.user32.GetForegroundWindow()
except Exception:
self._source_hwnd = None
telemetry.send("hotkey_pressed")
self.root.after(0, self._do_toggle)
def _do_toggle(self):
"""Toggle visibility (runs on tkinter main thread)."""
if self.visible:
self._hide()
else:
self._show()
def _show(self):
if self.window and self.visible:
return
if self.toolbar:
self.toolbar._dismiss()
# Hot-reload skills on every open
self.skills = core.scan_skills()
self.filtered = list(self.skills)
self.window = tk.Toplevel(self.root)
self.window.title("Scryptian")
self.window.overrideredirect(True)
self.window.attributes("-toolwindow", True)
self.window.configure(bg="#313244")
# ── Size and center position ──
screen_w = self.root.winfo_screenwidth()
screen_h = self.root.winfo_screenheight()
bar_width = max(560, int(screen_w * 0.4))
bar_height = 52
x = (screen_w - bar_width) // 2
y = int(screen_h * 0.3)
self._bar_width = bar_width
self.window.geometry(f"{bar_width}x{bar_height}+{x}+{y}")
self.window.attributes("-alpha", 0.0)
self.window.update_idletasks()
# ── Border ──
self.border = tk.Frame(self.window, bg="#45475a", padx=1, pady=1)
self.border.pack(fill="both", expand=True)
# ── Container ──
self.container = tk.Frame(self.border, bg="#1e1e2e")
self.container.pack(fill="both", expand=True)
# ── Input field ──
self.entry = tk.Entry(
self.container,
font=("Segoe UI", 16),
bg="#1e1e2e",
fg="#cdd6f4",
disabledbackground="#1e1e2e",
disabledforeground="#585b70",
insertbackground="#cdd6f4",
relief="flat",
borderwidth=0,
)
self.entry.pack(fill="x", padx=12, pady=8)
self.placeholder = tk.Label(
self.container,
text="Works with text from clipboard",
font=("Segoe UI", 16),
bg="#1e1e2e",
fg="#585b70",
)
self.placeholder.place(x=14, y=8)
self.placeholder.bind("<Button-1>", lambda e: self.entry.focus_set())
self.entry.bind("<KeyRelease>", self._on_key)
self.entry.bind("<Escape>", lambda e: self._hide())
self.entry.bind("<Down>", self._select_next)
self.entry.bind("<Up>", self._select_prev)
self.window.bind("<Return>", self._on_enter)
self.window.bind("<Escape>", lambda e: self._hide())
# ── Result list (hidden until input) ──
self.list_frame = tk.Frame(self.container, bg="#1e1e2e")
self._skill_rows = []
# ── Response area (hidden until result) ──
self.separator = tk.Frame(self.container, bg="#45475a", height=1)
self.result_box = tk.Text(
self.container,
font=("Consolas", 13),
bg="#1e1e2e",
fg="#a6adc8",
relief="flat",
borderwidth=0,
highlightthickness=0,
wrap="word",
state="disabled",
)
self.skill_hint = tk.Frame(self.container, bg="#1e1e2e")
tk.Label(
self.skill_hint,
text="Ctrl+Alt - hide",
font=("Segoe UI", 10),
bg="#1e1e2e",
fg="#585b70",
).pack(side="left")
tk.Label(
self.skill_hint,
text="Enter - run action",
font=("Segoe UI", 10),
bg="#1e1e2e",
fg="#585b70",
).pack(side="right")
self.hint_label = tk.Frame(self.container, bg="#1e1e2e")
tk.Label(
self.hint_label,
text="Enter - copy to clipboard and close",
font=("Segoe UI", 10),
bg="#1e1e2e",
fg="#585b70",
).pack(side="left")
report_btn = tk.Label(
self.hint_label,
text="[ Report ]",
font=("Segoe UI", 10),
bg="#1e1e2e",
fg="#6c7086",
cursor="hand2",
)
report_btn.pack(side="right")
report_btn.bind("<Button-1>", lambda e: self._open_report_dialog())
report_btn.bind("<Enter>", lambda e: report_btn.config(fg="#cdd6f4"))
report_btn.bind("<Leave>", lambda e: report_btn.config(fg="#6c7086"))
# Chain bar — quick actions on result
self.chain_frame = tk.Frame(self.container, bg="#1e1e2e")
self._chain_btns = []
# Processing animation
self._anim_job = None
self._anim_skill = ""
self._anim_frame = 0
self.window.attributes("-topmost", True)
self.window.update_idletasks()
self.window.lift()
# Drop topmost after focus so other windows can be clicked
self.window.after(300, lambda: self.window and self.window.attributes("-topmost", False))
# Hide when clicking outside
self.window.bind("<FocusOut>", self._on_focus_out)
# Chain hotkeys
self.window.bind("<Control-Key-1>", lambda e: self._run_chain("Summarize"))
self.window.bind("<Control-Key-2>", lambda e: self._run_chain("Change tone to professional"))
self.window.bind("<Control-Key-3>", lambda e: self._run_chain("Change tone to friendly"))
self.visible = True
self.selected_index = 0
self.in_store = False
self.store_frame = None
self.processing = False
self._bar_fade_in(0.0)
# If there's a pending result from a background task, show it
if self.pending_result is not None:
self.has_result = True
self.last_result = self.pending_result
self.pending_result = None
self.processing = False
self.list_frame.pack_forget()
self.entry.config(state="disabled")
self._show_result(self.last_result)
else:
self.has_result = False
self.last_result = ""
self._update_filter("")
self.window.after(50, self._force_focus)
def _force_focus(self, attempt=0):
"""Force focus via Windows API."""
if not self.window:
return
if IS_WINDOWS:
try:
hwnd = int(self.window.wm_frame(), 16)
fg = ctypes.windll.user32.GetForegroundWindow()
tid_fg = ctypes.windll.user32.GetWindowThreadProcessId(fg, None)
tid_self = ctypes.windll.kernel32.GetCurrentThreadId()
ctypes.windll.user32.AttachThreadInput(tid_fg, tid_self, True)
ctypes.windll.user32.SetForegroundWindow(hwnd)
ctypes.windll.user32.BringWindowToTop(hwnd)
ctypes.windll.user32.AttachThreadInput(tid_fg, tid_self, False)
except Exception:
pass
self.window.focus_force()
self.entry.focus_set()
# Retry up to 3 times — sometimes OS delays focus
if attempt < 3:
self.window.after(80, lambda: self._force_focus(attempt + 1))
def _on_focus_out(self, event):
"""Close only if focus truly left the window (delayed check)."""
if not self.window or self.processing:
return
self.window.after(150, self._check_focus)
def _check_focus(self):
"""Verify focus is still lost before hiding."""
if not self.window:
return
try:
focused = self.window.focus_get()
if focused is None:
self._hide()
except (KeyError, tk.TclError):
self._hide()
def _bar_fade_in(self, alpha):
if not self.window or not self.visible:
return
alpha = min(alpha + 0.1, 1.0)
try:
self.window.attributes("-alpha", alpha)
except Exception:
return
if alpha < 1.0:
self.root.after(16, lambda: self._bar_fade_in(alpha))
def _hide(self):
if self.window:
self.visible = False
win = self.window
self.window = None
self._bar_fade_out(win, 1.0)
def _bar_fade_out(self, win, alpha):
alpha = max(alpha - 0.12, 0.0)
try:
win.attributes("-alpha", alpha)
except Exception:
return
if alpha > 0.0:
self.root.after(16, lambda: self._bar_fade_out(win, alpha))
else:
try:
win.destroy()
except Exception:
pass
def _on_key(self, event):
if event.keysym in ("Return", "Escape", "Up", "Down"):
return
if str(self.entry.cget("state")) == "disabled":
return
query = self.entry.get()
if query:
self.placeholder.place_forget()
try:
self._hide_chain()
except Exception:
pass
else:
self.placeholder.place(x=14, y=8)
self._update_filter(query)
def _update_filter(self, query):
"""Filters skills by input. Pinned skills float to top when no filter."""
q = query.lower().strip()
if q:
self.filtered = [
s for s in self.skills
if q in s["title"].lower()
]
else:
pinned = main_pins.get_pinned_skills(self.skills)
rest = [s for s in self.skills if s["title"] not in main_pins.load()]
self.filtered = pinned + rest
self._render_list()
def _render_list(self):
"""Renders the dropdown list."""
if not self.window:
return
# Clear old rows
for row in self._skill_rows:
row.destroy()
self._skill_rows = []
if not self.filtered:
self.list_frame.pack_forget()
self.skill_hint.pack_forget()
self._resize(52)
return
for i, p in enumerate(self.filtered):
skill_id = p.get("filename", "").replace(".py", "")
row = self._make_row(p["title"], p["description"], i, pinnable=True, skill_id=skill_id)
self._skill_rows.append(row)
# "Add skill" shortcut — only when no filter is active
self._has_add_item = False
self._has_folder_item = False
self._has_feedback_item = False
self._has_store_item = False
if not self.entry.get().strip():
row = self._make_row("+ Add your own action", "", len(self.filtered))
self._skill_rows.append(row)
self._has_add_item = True
row2 = self._make_row("📁 Open actions folder", "", len(self.filtered) + 1)
self._skill_rows.append(row2)
self._has_folder_item = True
row3 = self._make_row("💬 Help & feedback (discord server)", "", len(self.filtered) + 2)
self._skill_rows.append(row3)
self._has_feedback_item = True
row4 = self._make_row("📦 Scryptian Store", "", len(self.filtered) + 3)
self._skill_rows.append(row4)
self._has_store_item = True
self.list_frame.pack(fill="x", padx=6, pady=(0, 2))
self.skill_hint.pack(fill="x", padx=12, pady=(0, 6))
self.window.update_idletasks()
needed = self.container.winfo_reqheight()
self._resize(needed + 4)
max_idx = len(self._skill_rows) - 1
self.selected_index = max(0, min(self.selected_index, max_idx))
self._highlight_row()
def _make_row(self, title, desc, idx, pinnable=False, skill_id=None):
"""Creates a single skill row with title (bright) and description (dim)."""
row = tk.Frame(self.list_frame, bg="#1e1e2e", cursor="hand2")
row.pack(fill="x", padx=4, pady=1)
title_lbl = tk.Label(
row, text=f" {title}", font=("Segoe UI", 13),
bg="#1e1e2e", fg="#cdd6f4", anchor="w",
)
title_lbl.pack(side="left", fill="x", expand=True)
if skill_id:
state = bridge.get_state(skill_id)
count = state.get("count", 0)
last_used = state.get("last_used", "")
if count > 0:
stats_parts = [f"{count}×"]
if last_used:
stats_parts.append(_format_last_used(last_used))
stats_text = " ".join(stats_parts)
stats_lbl = tk.Label(
row, text=stats_text, font=("Segoe UI", 9),
bg="#1e1e2e", fg="#45475a", anchor="e", padx=4,
)
stats_lbl.pack(side="left")
stats_lbl.bind("<Button-1>", lambda e, i=idx: self._click_row(i))
if pinnable:
skill_obj = self.filtered[idx] if idx < len(self.filtered) else None
# Main-bar pin (left of star)
mpinned = main_pins.is_pinned(title)
pin_lbl = tk.Label(
row,
text="\ue718" if mpinned else "\ue77a",
font=("Segoe MDL2 Assets", 12),
bg="#1e1e2e",
fg="#a6e3a1" if mpinned else "#6c7086",
cursor="hand2",
padx=4,
)
pin_lbl.pack(side="right")
pin_lbl.bind("<Button-1>", lambda e, t=title: self._toggle_main_pin(t))
# Star always rightmost
pinned = pins_module.is_pinned(title)
star_lbl = tk.Label(
row,
text="\ue735" if pinned else "\ue734",
font=("Segoe MDL2 Assets", 13),
bg="#1e1e2e",
fg="#f9e2af" if pinned else "#6c7086",
cursor="hand2",
padx=6,
)
star_lbl.pack(side="right")
star_lbl.bind("<Button-1>", lambda e, t=title: self._toggle_pin(t))
# Edit button for custom skills (left of star)
if skill_obj and skill_obj.get("filename", "").startswith("custom_"):
edit_lbl = tk.Label(
row, text="\ue70f",
font=("Segoe MDL2 Assets", 11),
bg="#1e1e2e", fg="#89b4fa",
cursor="hand2", padx=4,
)
edit_lbl.pack(side="right")
edit_lbl.bind("<Button-1>", lambda e, s=skill_obj: self._open_edit_skill_editor(s))
# Settings gear for skills that declare a settings schema (left of star)
if skill_obj and skill_settings.has_settings(skill_obj):
gear_lbl = tk.Label(
row, text="\ue713",
font=("Segoe MDL2 Assets", 12),
bg="#1e1e2e", fg="#a6adc8",
cursor="hand2", padx=4,
)
gear_lbl.pack(side="right")
gear_lbl.bind("<Button-1>", lambda e, s=skill_obj: self._open_skill_settings(s))
# Click handler
row.bind("<Button-1>", lambda e, i=idx: self._click_row(i))
title_lbl.bind("<Button-1>", lambda e, i=idx: self._click_row(i))
return row
def _open_new_skill_editor(self):
def on_saved():
self.skills = core.scan_skills()
self._update_filter(self.entry.get())
skill_editor.open_editor(self.root, SKILLS_DIR, on_saved=on_saved)
def _open_edit_skill_editor(self, skill):
def on_saved():
self.skills = core.scan_skills()
self._update_filter(self.entry.get())
skill_editor.open_editor(self.root, SKILLS_DIR, on_saved=on_saved, skill=skill)
def _open_skill_settings(self, skill):
def on_saved():
self.skills = core.scan_skills()
self._update_filter(self.entry.get())
skill_settings.open_settings(self.root, skill, on_saved=on_saved)
def _toggle_pin(self, title):
pins_module.toggle(title)
self._render_list()
def _toggle_main_pin(self, title):
main_pins.toggle(title)
self._update_filter(self.entry.get())
def _click_row(self, idx):
"""Handle click on a skill row."""
self.selected_index = idx
self._highlight_row()
self._on_enter(None)
def _highlight_row(self):
"""Highlights the selected row."""
for i, row in enumerate(self._skill_rows):
if i == self.selected_index:
row.config(bg="#45475a")
for child in row.winfo_children():
child.config(bg="#45475a")
else:
row.config(bg="#1e1e2e")
for child in row.winfo_children():
child.config(bg="#1e1e2e")
def _resize(self, height):
"""Updates window height."""
if not self.window:
return
geo = self.window.geometry()
parts = geo.split("+")
wh = parts[0].split("x")
self.window.geometry(f"{wh[0]}x{height}+{parts[1]}+{parts[2]}")
def _select_next(self, event):
if self._skill_rows:
max_idx = len(self._skill_rows) - 1
self.selected_index = min(self.selected_index + 1, max_idx)
self._highlight_row()
def _select_prev(self, event):
if self._skill_rows:
self.selected_index = max(self.selected_index - 1, 0)
self._highlight_row()
def _auto_paste(self):
"""Restore focus to source window and paste result."""
hwnd = self._source_hwnd
self._source_hwnd = None
if not hwnd:
return
def _do():
time.sleep(0.12)
try:
ctypes.windll.user32.SetForegroundWindow(hwnd)
time.sleep(0.06)
keyboard.send("ctrl+v")
except Exception:
pass
threading.Thread(target=_do, daemon=True).start()
def _on_enter(self, event):
"""Runs the selected skill or copies the result."""
if self.has_result:
if self.last_result:
pyperclip.copy(self.last_result + "\n\n— Scryptian")
self._auto_paste()
telemetry.send("result_copied", {"skill": getattr(self, "last_skill_title", "unknown")})
print("[Scryptian] Copied to clipboard.")
self._hide()
return
if not self.filtered:
return
# "Add skill" item selected
if self._has_add_item and self.selected_index == len(self.filtered):
self._open_new_skill_editor()
return
# "Open skills folder" item selected
if self._has_folder_item and self.selected_index == len(self.filtered) + 1:
self._open_skills_folder()
return
# "Help & feedback" item selected
if self._has_feedback_item and self.selected_index == len(self.filtered) + 2:
import webbrowser
telemetry.send("feedback_clicked")
webbrowser.open("https://discord.gg/JyAJuN8xk")
return
if self._has_store_item and self.selected_index == len(self.filtered) + 3:
self._open_store()
return
skill = self.filtered[self.selected_index]
is_bg = bool(skill.get("background", False))
# Resolve input (files → text → nothing)
inp = core.get_input()
input_text = inp["data"] if inp else ""
if not input_text.strip():
try:
input_text = pyperclip.paste()
except Exception:
input_text = ""
# Background skills (long file jobs) don't rely on clipboard text.
if not input_text.strip() and not is_bg:
self._show_result("Clipboard is empty. Copy some text first (Ctrl+C), then try again.")
return
# ── Background (fire-and-forget) skills: run detached, free the bar ──
if is_bg:
if getattr(self, "_bg_running", False):
self._show_result("A background task is already running.\nPlease wait for it to finish.")
return
self._bg_running = True
print(f"[Scryptian] Running (background): {skill['title']}...")
_bt0 = time.time()
_bg_src = _get_source_app(getattr(self, '_source_hwnd', None))
def bg_execute():
try:
result = core.run_skill(skill, input_text)
if isinstance(result, str) and result.startswith("[Scryptian Error]"):
bridge.notify(skill["title"], result.replace("[Scryptian Error]", "").strip() or "Task failed.")
telemetry.send("skill_failed", {"name": skill["title"], "reason": "bg_error", "error": result[:200]})
else:
telemetry.send("skill_run", _build_skill_event(skill, input_text, time.time() - _bt0, **_bg_src, background=True))
_track_skill(skill["filename"].replace(".py", ""))
print(f"[Scryptian] Done (background): {skill['title']}")
except Exception as e:
print(f"[Scryptian] Background skill error: {e}")
bridge.notify(skill["title"], f"Task failed: {e}")
finally:
self._bg_running = False
threading.Thread(target=bg_execute, daemon=True).start()
self._show_result(f"'{skill['title']}' started in the background.\nYou'll be notified when it's done.")
if self.window:
self.window.after(2500, self._hide)
return
# Hide list, show status
self.list_frame.pack_forget()
self.skill_hint.pack_forget()
self.entry.config(state="disabled")
self._start_anim(skill["title"])
self.processing = True
print(f"[Scryptian] Running: {skill['title']}...")
_t0 = time.time()
_src = _get_source_app(getattr(self, '_source_hwnd', None))
def execute():
try:
# Ensure model is ready (download/load if needed) — only for skills that need the LLM.
# Progress is delivered through the global listener registered at startup.
if skill.get("needs_llm", True) and not bridge.is_model_in_memory():
self.root.after(0, lambda: self._show_result("Preparing AI model..."))
bridge._get_llm()
if bridge.was_just_downloaded():
self.root.after(0, lambda: tray.show_notify_popup("Scryptian", "AI model ready. Skills are now available.", self.root))
mod = skill["module"]
if hasattr(mod, "prompt") or hasattr(mod, "run_stream"):
full_text = ""
for chunk in core.run_skill_stream(skill, input_text):
full_text = chunk
text_snapshot = full_text
self.root.after(0, lambda t=text_snapshot: self._update_stream(t))
stripped = full_text.strip()
self.processing = False
if stripped and not stripped.startswith("[Scryptian Error]"):
if self.window and self.visible:
self.last_result = stripped
self.last_skill_title = skill["title"]
self.has_result = True
self.root.after(0, lambda: self._finish_stream())
else:
self.pending_result = stripped
telemetry.send("skill_run", _build_skill_event(skill, input_text, time.time() - _t0, **_src))
_track_skill(skill["filename"].replace(".py", ""))
print(f"[Scryptian] Done!")
elif stripped.startswith("[Scryptian Error]"):
telemetry.send("skill_failed", {"name": skill["title"], "reason": "error", "error": stripped[:200]})
self.root.after(0, lambda t=stripped: self._show_result(t))
else:
telemetry.send("skill_failed", {"name": skill["title"], "reason": "empty"})
self.root.after(0, lambda: self._show_result("Skill returned an empty result."))
else:
result = core.run_skill(skill, input_text)
self.processing = False
if result and not result.startswith("[Scryptian Error]"):
if self.window and self.visible:
self.last_result = result
self.last_skill_title = skill["title"]
self.has_result = True
self.root.after(0, lambda: self._show_result(result))
else:
self.pending_result = result
telemetry.send("skill_run", _build_skill_event(skill, input_text, time.time() - _t0, **_src))
_track_skill(skill["filename"].replace(".py", ""))
print(f"[Scryptian] Done!")
elif result and result.startswith("[Scryptian Error]"):
telemetry.send("skill_failed", {"name": skill["title"], "reason": "error", "error": result[:200]})
self.root.after(0, lambda: self._show_result(result))
else:
telemetry.send("skill_failed", {"name": skill["title"], "reason": "empty"})
self.root.after(0, lambda: self._show_result("Skill returned an empty result."))
except Exception as e:
telemetry.send("skill_failed", {"name": skill["title"], "reason": "exception", "error": str(e)[:200]})
err_msg = f"Error: {e}"
self.root.after(0, lambda msg=err_msg: self._show_result(msg))
threading.Thread(target=execute, daemon=True).start()
def run_externally(self, skill, input_text, source_hwnd=None):
"""Open the bar and run a skill with given text (called from SelectionToolbar)."""
self._source_hwnd = source_hwnd
pyperclip.copy(input_text)
self.root.after(0, lambda: self._run_external(skill, input_text))
def _run_external(self, skill, input_text):
if not self.visible:
self._show()
self.list_frame.pack_forget()
self.skill_hint.pack_forget()
self.entry.config(state="disabled")
self._start_anim(skill["title"])
self.processing = True
_t0 = time.time()
_src = _get_source_app(getattr(self, '_source_hwnd', None))
def execute():
try:
if skill.get("needs_llm", True) and not bridge.is_model_in_memory():
self.root.after(0, lambda: self._show_result("Preparing AI model..."))
bridge._get_llm()
if bridge.was_just_downloaded():
self.root.after(0, lambda: tray.show_notify_popup("Scryptian", "AI model ready. Skills are now available.", self.root))
mod = skill["module"]
if hasattr(mod, "prompt") or hasattr(mod, "run_stream"):
full_text = ""
for chunk in core.run_skill_stream(skill, input_text):
full_text = chunk
self.root.after(0, lambda t=full_text: self._update_stream(t))
result = full_text.strip()
self.processing = False
if result and not result.startswith("[Scryptian Error]"):
self.last_result = result
self.has_result = True
self.root.after(0, self._finish_stream)
telemetry.send("skill_run", _build_skill_event(skill, input_text, time.time() - _t0, **_src, via="selection"))
else:
telemetry.send("skill_failed", {"name": skill["title"], "via": "selection", "reason": "error_or_empty", "error": (result or "")[:200]})
self.root.after(0, lambda t=result: self._show_result(t or "Skill returned an empty result."))
else:
result = core.run_skill(skill, input_text)
self.processing = False
if result and not result.startswith("[Scryptian Error]"):
self.last_result = result
self.has_result = True
self.root.after(0, lambda: self._show_result(result))
telemetry.send("skill_run", _build_skill_event(skill, input_text, time.time() - _t0, **_src, via="selection"))
else:
telemetry.send("skill_failed", {"name": skill["title"], "via": "selection", "reason": "error_or_empty", "error": (result or "")[:200]})
self.root.after(0, lambda t=result: self._show_result(t or "Skill returned an empty result."))
except Exception as e:
telemetry.send("skill_failed", {"name": skill["title"], "via": "selection", "reason": "exception", "error": str(e)[:200]})
self.root.after(0, lambda msg=str(e): self._show_result(f"Error: {msg}"))
threading.Thread(target=execute, daemon=True).start()
def _update_stream(self, text):
"""Updates result box with streaming text in real-time."""
if not self.window:
return
self.separator.pack_forget()
self.result_box.pack_forget()
self.hint_label.pack_forget()
self.chain_frame.pack_forget()
self.result_box.config(state="normal")
self.result_box.delete("1.0", tk.END)
self.result_box.insert("1.0", text)
self.result_box.config(state="disabled")
self.result_box.see(tk.END)
chars_per_line = 45
visual_lines = 0
for line in text.split("\n"):
visual_lines += max(1, (len(line) // chars_per_line) + 1)
max_lines = 25
clamped = min(visual_lines, max_lines)
clamped = max(clamped, 2)
self.separator.pack(fill="x", padx=8, pady=(4, 0))
self.result_box.config(height=clamped)
self.result_box.pack(fill="x", padx=10, pady=(4, 4))
self.window.update_idletasks()
needed = self.container.winfo_reqheight()
self._resize(needed + 4)
def _finish_stream(self):
"""Called when streaming is complete — shows hint label and chain."""
self._stop_anim()
if not self.window:
return