-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1846 lines (1565 loc) · 73.6 KB
/
Copy pathmain.py
File metadata and controls
1846 lines (1565 loc) · 73.6 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
"""
Claude Code IDE - Claude on the left, Python editor on the right.
Integrated with Crawl4AI for web scraping.
Scheduler for running code on schedule.
"""
import io
import json
import os
import queue
import sys
import traceback
import threading
import tkinter as tk
import urllib.request
import urllib.error
from tkinter import ttk, scrolledtext, filedialog, messagebox
from contextlib import redirect_stdout, redirect_stderr
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
from claude_code import ClaudeCode, ClaudeResponse
from config_manager import ConfigManager
from discord_notifier import DiscordNotifier
class LiveWriter(io.TextIOBase):
"""Stream that sends text to a queue instead of buffering."""
def __init__(self, output_queue: queue.Queue, tag: str = ""):
self._queue = output_queue
self._tag = tag
def write(self, text: str) -> int:
if text:
self._queue.put((text, self._tag))
return len(text) if text else 0
def flush(self):
pass
@property
def encoding(self):
return "utf-8"
# ============================================================
# Tab: Claude Code
# ============================================================
class ClaudeTab(ttk.Frame):
"""Claude Code console."""
def __init__(self, parent):
super().__init__(parent)
self._build_ui()
self.claude = ClaudeCode(
on_response=self._on_response,
on_error=self._on_error,
)
# Queue + polling - reliable pattern for tkinter + background threads
self._traffic_queue = queue.Queue()
ClaudeCode.add_traffic_listener(self._on_traffic)
self._poll_traffic()
def _build_ui(self):
self.chat = scrolledtext.ScrolledText(
self, wrap=tk.WORD, font=("monospace", 11),
bg="#1e1e2e", fg="#cdd6f4", insertbackground="#cdd6f4",
selectbackground="#45475a", relief=tk.FLAT, padx=8, pady=8,
state=tk.DISABLED,
)
self.chat.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
self.chat.tag_configure("user", foreground="#89b4fa", font=("monospace", 11, "bold"))
self.chat.tag_configure("claude", foreground="#a6e3a1")
self.chat.tag_configure("error", foreground="#f38ba8")
self.chat.tag_configure("system", foreground="#6c7086", font=("monospace", 10, "italic"))
self.chat.tag_configure("prompt_full", foreground="#cba6f7", font=("monospace", 9))
self.chat.tag_configure("traffic_header", foreground="#f9e2af", font=("monospace", 9, "bold"))
self.chat.tag_configure("response_full", foreground="#94e2d5", font=("monospace", 9))
input_frame = ttk.Frame(self)
input_frame.pack(fill=tk.X, padx=4, pady=(0, 4))
self.input_var = tk.StringVar()
self.input_entry = ttk.Entry(input_frame, textvariable=self.input_var, font=("monospace", 11))
self.input_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 4))
self.input_entry.bind("<Return>", self._on_send)
self.send_btn = ttk.Button(input_frame, text="Send", command=self._on_send)
self.send_btn.pack(side=tk.RIGHT)
self._append_text("Type a message for Claude Code.\n", "system")
def _append_text(self, text, tag=None):
self.chat.configure(state=tk.NORMAL)
if tag:
self.chat.insert(tk.END, text, tag)
else:
self.chat.insert(tk.END, text)
self.chat.configure(state=tk.DISABLED)
self.chat.see(tk.END)
def _on_send(self, event=None):
msg = self.input_var.get().strip()
if not msg or self.claude.busy:
return
self.input_var.set("")
# Context injection works globally in ClaudeCode.ask() via message_hook
self._append_text("Claude is thinking...\n", "system")
self.send_btn.configure(state=tk.DISABLED)
self.claude.send_chat(msg)
def _on_traffic(self, direction: str, text: str, meta: dict):
"""Global listener - pushes to queue (called from any thread)."""
self._traffic_queue.put((direction, text, meta))
def _poll_traffic(self):
"""Poll every 100ms - reads queue and displays in chat (main thread)."""
try:
while True:
direction, text, meta = self._traffic_queue.get_nowait()
self._show_traffic_item(direction, text, meta)
except queue.Empty:
pass
self.after(100, self._poll_traffic)
def _show_traffic_item(self, direction: str, text: str, meta: dict):
if direction == "send":
self._append_text(f"\n>>> PROMPT SENT >>>\n", "traffic_header")
if meta.get("system_prompt"):
self._append_text(f"[system_prompt: {meta['system_prompt'][:100]}...]\n", "system")
self._append_text(f"{text}\n", "prompt_full")
self._append_text(f">>> END OF PROMPT >>>\n\n", "traffic_header")
elif direction == "recv":
self._remove_thinking()
self._append_text(f"<<< CLAUDE RESPONSE <<<\n", "traffic_header")
self._append_text(f"{text}\n", "response_full")
meta_parts = []
if meta.get("model"):
meta_parts.append(meta["model"])
if meta.get("cost_usd"):
meta_parts.append(f"${meta['cost_usd']:.4f}")
if meta.get("duration_ms"):
meta_parts.append(f"{meta['duration_ms']:.0f}ms")
if meta_parts:
self._append_text(f" [{' | '.join(meta_parts)}]\n", "system")
self._append_text(f"<<< END OF RESPONSE <<<\n\n", "traffic_header")
self.send_btn.configure(state=tk.NORMAL)
self.input_entry.focus_set()
elif direction == "error":
self._remove_thinking()
self._append_text(f"<<< ERROR <<<\n", "traffic_header")
self._append_text(f"{text}\n", "error")
self._append_text(f"<<< END OF ERROR <<<\n\n", "traffic_header")
self.send_btn.configure(state=tk.NORMAL)
self.input_entry.focus_set()
def _on_response(self, response):
# Response displayed via traffic polling - unlock UI as fallback
pass
def _on_error(self, error):
# Error displayed via traffic polling
pass
def _remove_thinking(self):
self.chat.configure(state=tk.NORMAL)
content = self.chat.get("1.0", tk.END)
idx = content.rfind("Claude is thinking...")
if idx != -1:
ln = content[:idx].count("\n") + 1
self.chat.delete(f"{ln}.0", f"{ln}.end+1c")
self.chat.configure(state=tk.DISABLED)
# ============================================================
# Tab: Scraper (Crawl4AI - 100% local)
# ============================================================
class ScraperTab(ttk.Frame):
"""Scraper panel - scraping and mapping pages.
Uses Crawl4AI - runs locally, no API keys."""
def __init__(self, parent, claude_tab: ClaudeTab):
super().__init__(parent)
self.claude_tab = claude_tab
self._sc = None
self._build_ui()
def _get_sc(self):
if self._sc is None:
try:
from scraper import Scraper
self._sc = Scraper(on_status=self._on_status)
except ImportError:
messagebox.showerror("Error", "Missing scraper module.\npip install crawl4ai && crawl4ai-setup")
return None
return self._sc
def _build_ui(self):
# --- Info ---
info = ttk.Label(
self,
text="Local browser (Crawl4AI) - no API keys, no limits",
font=("monospace", 9, "italic"),
foreground="#a6e3a1",
)
info.pack(fill=tk.X, padx=8, pady=(8, 2))
# --- Actions ---
action_frame = ttk.LabelFrame(self, text="Action")
action_frame.pack(fill=tk.X, padx=4, pady=4)
self.action_var = tk.StringVar(value="scrape")
actions = [
("Scrape", "scrape"),
("Multi-scrape", "multi"),
("Map links", "map"),
("Scrape+Claude", "scrape_ask"),
]
btn_row = ttk.Frame(action_frame)
btn_row.pack(fill=tk.X, padx=4, pady=4)
for text, val in actions:
ttk.Radiobutton(btn_row, text=text, variable=self.action_var, value=val).pack(side=tk.LEFT, padx=4)
# --- URL ---
input_frame = ttk.Frame(action_frame)
input_frame.pack(fill=tk.X, padx=4, pady=(0, 4))
ttk.Label(input_frame, text="URL:").pack(side=tk.LEFT)
self.url_var = tk.StringVar()
url_entry = ttk.Entry(input_frame, textvariable=self.url_var, font=("monospace", 10))
url_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=4)
url_entry.bind("<Return>", lambda e: self._run_action())
self.go_btn = ttk.Button(input_frame, text="Start", command=self._run_action)
self.go_btn.pack(side=tk.RIGHT)
# --- Question for Claude ---
q_frame = ttk.Frame(action_frame)
q_frame.pack(fill=tk.X, padx=4, pady=(0, 4))
ttk.Label(q_frame, text="Question:").pack(side=tk.LEFT)
self.question_var = tk.StringVar()
ttk.Entry(q_frame, textvariable=self.question_var, font=("monospace", 10)).pack(
side=tk.LEFT, fill=tk.X, expand=True, padx=4
)
# --- Result ---
self.result_text = scrolledtext.ScrolledText(
self, wrap=tk.WORD, font=("monospace", 11),
bg="#1e1e2e", fg="#cdd6f4", insertbackground="#cdd6f4",
selectbackground="#45475a", relief=tk.FLAT, padx=8, pady=8,
state=tk.DISABLED,
)
self.result_text.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
self.result_text.tag_configure("title", foreground="#89b4fa", font=("monospace", 11, "bold"))
self.result_text.tag_configure("url", foreground="#f9e2af")
self.result_text.tag_configure("status", foreground="#6c7086", font=("monospace", 10, "italic"))
self.result_text.tag_configure("error", foreground="#f38ba8")
self.result_text.tag_configure("success", foreground="#a6e3a1")
# --- Bottom buttons ---
bottom = ttk.Frame(self)
bottom.pack(fill=tk.X, padx=4, pady=(0, 4))
ttk.Button(bottom, text="Clear", command=self._clear).pack(side=tk.LEFT)
ttk.Button(bottom, text="Send to Claude", command=self._send_to_claude).pack(side=tk.RIGHT)
ttk.Button(bottom, text="Insert into editor", command=self._insert_to_editor).pack(side=tk.RIGHT, padx=4)
def _on_status(self, msg):
self.after(0, self._append_result, f"{msg}\n", "status")
def _append_result(self, text, tag=None):
self.result_text.configure(state=tk.NORMAL)
if tag:
self.result_text.insert(tk.END, text, tag)
else:
self.result_text.insert(tk.END, text)
self.result_text.configure(state=tk.DISABLED)
self.result_text.see(tk.END)
def _clear(self):
self.result_text.configure(state=tk.NORMAL)
self.result_text.delete("1.0", tk.END)
self.result_text.configure(state=tk.DISABLED)
def _run_action(self):
sc = self._get_sc()
if not sc:
return
url = self.url_var.get().strip()
if not url:
self._append_result("Enter a URL.\n", "error")
return
action = self.action_var.get()
self.go_btn.configure(state=tk.DISABLED)
self._append_result(f"\n{'='*40}\n", "status")
threading.Thread(target=self._do_action, args=(action, url), daemon=True).start()
def _do_action(self, action, url):
sc = self._get_sc()
try:
if action == "scrape":
result = sc.scrape(url)
if result.is_error:
self.after(0, self._append_result, f"Error: {result.error_msg}\n", "error")
else:
self.after(0, self._show_scrape, result)
elif action == "multi":
urls = [u.strip() for u in url.split(",") if u.strip()]
if len(urls) < 2:
self.after(0, self._append_result,
"Enter multiple URLs separated by commas.\n"
"E.g.: https://a.com, https://b.com\n", "error")
return
self.after(0, self._append_result, f"Scraping {len(urls)} pages...\n", "status")
results = sc.scrape_many(urls)
for r in results:
if r.is_error:
self.after(0, self._append_result, f"Error {r.url}: {r.error_msg}\n", "error")
else:
self.after(0, self._show_scrape, r)
self.after(0, self._append_result, "\n---\n\n", "status")
elif action == "map":
self.after(0, self._append_result, f"Mapping links on {url}...\n", "status")
urls = sc.map_site(url, max_depth=1)
self.after(0, self._show_urls, url, urls)
elif action == "scrape_ask":
question = self.question_var.get().strip()
if not question:
self.after(0, self._append_result, "Enter a question in the 'Question' field.\n", "error")
return
self.after(0, self._append_result, "Scraping page...\n", "status")
result = sc.scrape(url)
if result.is_error:
self.after(0, self._append_result, f"Scrape error: {result.error_msg}\n", "error")
return
self.after(0, self._append_result,
f"OK ({len(result.markdown)} chars). Asking Claude...\n", "status")
claude = ClaudeCode()
resp = claude.scrape_and_ask(url, question)
self.after(0, self._append_result,
f"\n{resp.text}\n",
"success" if not resp.is_error else "error")
except Exception as e:
self.after(0, self._append_result, f"Exception: {e}\n", "error")
finally:
self.after(0, lambda: self.go_btn.configure(state=tk.NORMAL))
def _show_scrape(self, result):
self._append_result(f"Page: {result.title or '(no title)'}\n", "title")
self._append_result(f"{result.url}\n", "url")
self._append_result(f"[{len(result.markdown)} chars | {len(result.links)} links | {result.elapsed_sec:.1f}s]\n\n", "status")
md = result.markdown
if len(md) > 5000:
self._append_result(md[:5000] + f"\n\n... (truncated, total {len(md)} chars)\n")
else:
self._append_result(md + "\n")
def _show_urls(self, base_url, urls):
self._append_result(f"Links on {base_url}: {len(urls)} found\n\n", "title")
for u in urls[:80]:
self._append_result(f" {u}\n", "url")
if len(urls) > 80:
self._append_result(f"\n ... and {len(urls) - 80} more\n", "status")
def _send_to_claude(self):
content = self.result_text.get("1.0", tk.END).strip()
if not content:
return
if len(content) > 8000:
content = content[:8000] + "\n...(truncated)"
self.claude_tab._append_text(f"\n[Scraper -> Claude]\n", "system")
self.claude_tab.input_var.set(f"Analyze this data from the page:\n{content[:200]}...")
self.claude_tab.input_entry.focus_set()
def _insert_to_editor(self):
content = self.result_text.get("1.0", tk.END).strip()
if not content:
return
self.event_generate("<<InsertToEditor>>", data=content)
# ============================================================
# Scheduler - code execution schedule
# ============================================================
@dataclass
class ScheduledJob:
name: str
code: str
mode: str # "once" | "daily" | "interval" | "weekly"
time_str: str # "14:30"
date_str: str # "2026-03-15" (for once)
interval_min: int # minutes (for interval)
weekdays: list # 0=Mon..6=Sun (for weekly)
timezone: str = "" # e.g. "America/New_York" — times interpreted in this tz
active: bool = True
next_run: datetime = field(default_factory=datetime.now)
last_run: datetime | None = None
class Scheduler:
"""Schedule engine - manages jobs and calculates next_run."""
def __init__(self):
self.jobs: list[ScheduledJob] = []
def add_job(self, job: ScheduledJob):
job.next_run = self._calculate_next_run(job)
self.jobs.append(job)
def remove_job(self, name: str):
self.jobs = [j for j in self.jobs if j.name != name]
def toggle_job(self, name: str):
for j in self.jobs:
if j.name == name:
j.active = not j.active
if j.active:
j.next_run = self._calculate_next_run(j)
return j.active
return None
def get_due_jobs(self) -> list[ScheduledJob]:
now = datetime.now()
due = []
for j in self.jobs:
if j.active and j.next_run <= now:
due.append(j)
return due
def mark_run(self, job: ScheduledJob):
job.last_run = datetime.now()
if job.mode == "once":
job.active = False
else:
job.next_run = self._calculate_next_run(job)
def _calculate_next_run(self, job: ScheduledJob) -> datetime:
now = datetime.now()
tz = ZoneInfo(job.timezone) if job.timezone else None
ref_now = datetime.now(tz) if tz else now
if job.mode == "once":
try:
dt = datetime.strptime(f"{job.date_str} {job.time_str}", "%Y-%m-%d %H:%M")
return dt
except ValueError:
return now
elif job.mode == "daily":
try:
h, m = map(int, job.time_str.split(":"))
target = ref_now.replace(hour=h, minute=m, second=0, microsecond=0)
if target <= ref_now:
target += timedelta(days=1)
return self._to_local(target, tz)
except ValueError:
return now + timedelta(days=1)
elif job.mode == "interval":
return now + timedelta(minutes=max(job.interval_min, 1))
elif job.mode == "weekly":
if not job.weekdays:
return now + timedelta(days=7)
try:
h, m = map(int, job.time_str.split(":"))
except ValueError:
h, m = 0, 0
# Check today first
if ref_now.weekday() in job.weekdays:
target = ref_now.replace(hour=h, minute=m, second=0, microsecond=0)
if target > ref_now:
return self._to_local(target, tz)
# Then look at future days
for delta in range(1, 8):
candidate = ref_now + timedelta(days=delta)
if candidate.weekday() in job.weekdays:
target = candidate.replace(hour=h, minute=m, second=0, microsecond=0)
return self._to_local(target, tz)
return now + timedelta(days=1)
return now + timedelta(hours=1)
@staticmethod
def _to_local(dt: datetime, tz) -> datetime:
"""Convert tz-aware datetime to local naive datetime, or pass through if no tz."""
if tz is None:
return dt
return dt.astimezone().replace(tzinfo=None)
def next_scheduled(self) -> datetime | None:
active = [j for j in self.jobs if j.active]
if not active:
return None
return min(j.next_run for j in active)
class SchedulerTab(ttk.Frame):
"""Scheduler tab - code execution schedule."""
def __init__(self, parent, python_panel_ref, discord_tab=None):
super().__init__(parent)
self.python_panel = python_panel_ref
self.discord_tab = discord_tab
self.scheduler = Scheduler()
self._build_ui()
self._tick()
def _build_ui(self):
# --- Top panel: adding/editing tasks ---
add_frame = ttk.LabelFrame(self, text="Task settings")
add_frame.pack(fill=tk.X, padx=4, pady=4)
# Name
name_row = ttk.Frame(add_frame)
name_row.pack(fill=tk.X, padx=4, pady=(4, 2))
ttk.Label(name_row, text="Name:").pack(side=tk.LEFT)
self.name_var = tk.StringVar()
ttk.Entry(name_row, textvariable=self.name_var, font=("monospace", 10)).pack(
side=tk.LEFT, fill=tk.X, expand=True, padx=4
)
# Mode
mode_row = ttk.Frame(add_frame)
mode_row.pack(fill=tk.X, padx=4, pady=2)
self.mode_var = tk.StringVar(value="interval")
for text, val in [("Once", "once"), ("Daily", "daily"),
("Every X min", "interval"), ("Weekdays", "weekly")]:
ttk.Radiobutton(mode_row, text=text, variable=self.mode_var,
value=val, command=self._on_mode_change).pack(side=tk.LEFT, padx=3)
# Parameters - container
self.params_frame = ttk.Frame(add_frame)
self.params_frame.pack(fill=tk.X, padx=4, pady=2)
# Date (once)
self.date_var = tk.StringVar(value=datetime.now().strftime("%Y-%m-%d"))
# Time
self.hour_var = tk.StringVar(value="12")
self.min_var = tk.StringVar(value="00")
# Interval
self.interval_var = tk.StringVar(value="30")
# Weekdays
self.weekday_vars = [tk.BooleanVar(value=False) for _ in range(7)]
self._on_mode_change()
# Buttons
btn_row = ttk.Frame(add_frame)
btn_row.pack(fill=tk.X, padx=4, pady=(2, 4))
self._add_btn_var = tk.StringVar(value="Add to schedule")
self._add_btn = ttk.Button(btn_row, textvariable=self._add_btn_var, command=self._add_or_update_job)
self._add_btn.pack(side=tk.LEFT, padx=(0, 4))
ttk.Button(btn_row, text="Run now", command=self._run_now).pack(side=tk.LEFT)
self._editing_job_name: str | None = None
# --- Task list ---
list_frame = ttk.LabelFrame(self, text="Scheduled tasks")
list_frame.pack(fill=tk.X, padx=4, pady=4)
cols = ("name", "mode", "next_run", "status")
self.tree = ttk.Treeview(list_frame, columns=cols, show="headings", height=5)
self.tree.heading("name", text="Name")
self.tree.heading("mode", text="Mode")
self.tree.heading("next_run", text="Next run")
self.tree.heading("status", text="Status")
self.tree.column("name", width=100)
self.tree.column("mode", width=80)
self.tree.column("next_run", width=140)
self.tree.column("status", width=70)
self.tree.pack(fill=tk.X, padx=4, pady=4)
# Treeview styles
style = ttk.Style()
style.configure("Treeview", background="#1e1e2e", foreground="#cdd6f4",
fieldbackground="#1e1e2e", rowheight=22)
style.configure("Treeview.Heading", background="#313244", foreground="#cdd6f4")
self.tree.bind("<<TreeviewSelect>>", self._on_tree_select)
tree_btns = ttk.Frame(list_frame)
tree_btns.pack(fill=tk.X, padx=4, pady=(0, 4))
ttk.Button(tree_btns, text="Pause/Resume", command=self._toggle_selected).pack(side=tk.LEFT, padx=(0, 4))
ttk.Button(tree_btns, text="Remove", command=self._remove_selected).pack(side=tk.LEFT, padx=(0, 4))
ttk.Button(tree_btns, text="Deselect", command=self._deselect).pack(side=tk.LEFT)
# --- Execution log ---
log_frame = ttk.LabelFrame(self, text="Execution log")
log_frame.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
self.log_text = scrolledtext.ScrolledText(
log_frame, wrap=tk.WORD, font=("monospace", 10),
bg="#11111b", fg="#cdd6f4", insertbackground="#cdd6f4",
selectbackground="#45475a", relief=tk.FLAT, padx=6, pady=6,
state=tk.DISABLED,
)
self.log_text.pack(fill=tk.BOTH, expand=True)
self.log_text.tag_configure("error", foreground="#f38ba8")
self.log_text.tag_configure("info", foreground="#a6e3a1")
self.log_text.tag_configure("time", foreground="#f9e2af")
self.log_text.tag_configure("status", foreground="#6c7086", font=("monospace", 9, "italic"))
# --- Status bar ---
self.status_var = tk.StringVar(value="No scheduled tasks")
status_bar = ttk.Label(self, textvariable=self.status_var,
font=("monospace", 9, "italic"), foreground="#6c7086")
status_bar.pack(fill=tk.X, padx=8, pady=(0, 4))
def _on_mode_change(self):
for w in self.params_frame.winfo_children():
w.destroy()
mode = self.mode_var.get()
if mode == "once":
ttk.Label(self.params_frame, text="Date:").pack(side=tk.LEFT)
ttk.Entry(self.params_frame, textvariable=self.date_var, width=12,
font=("monospace", 10)).pack(side=tk.LEFT, padx=4)
ttk.Label(self.params_frame, text="Time:").pack(side=tk.LEFT)
ttk.Entry(self.params_frame, textvariable=self.hour_var, width=3,
font=("monospace", 10)).pack(side=tk.LEFT, padx=2)
ttk.Label(self.params_frame, text=":").pack(side=tk.LEFT)
ttk.Entry(self.params_frame, textvariable=self.min_var, width=3,
font=("monospace", 10)).pack(side=tk.LEFT, padx=2)
elif mode == "daily":
ttk.Label(self.params_frame, text="Time:").pack(side=tk.LEFT)
ttk.Entry(self.params_frame, textvariable=self.hour_var, width=3,
font=("monospace", 10)).pack(side=tk.LEFT, padx=2)
ttk.Label(self.params_frame, text=":").pack(side=tk.LEFT)
ttk.Entry(self.params_frame, textvariable=self.min_var, width=3,
font=("monospace", 10)).pack(side=tk.LEFT, padx=2)
elif mode == "interval":
ttk.Label(self.params_frame, text="Every").pack(side=tk.LEFT)
ttk.Entry(self.params_frame, textvariable=self.interval_var, width=5,
font=("monospace", 10)).pack(side=tk.LEFT, padx=4)
ttk.Label(self.params_frame, text="minutes").pack(side=tk.LEFT)
elif mode == "weekly":
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
for i, day in enumerate(days):
ttk.Checkbutton(self.params_frame, text=day,
variable=self.weekday_vars[i]).pack(side=tk.LEFT, padx=1)
ttk.Label(self.params_frame, text=" at").pack(side=tk.LEFT)
ttk.Entry(self.params_frame, textvariable=self.hour_var, width=3,
font=("monospace", 10)).pack(side=tk.LEFT, padx=2)
ttk.Label(self.params_frame, text=":").pack(side=tk.LEFT)
ttk.Entry(self.params_frame, textvariable=self.min_var, width=3,
font=("monospace", 10)).pack(side=tk.LEFT, padx=2)
def _on_tree_select(self, event=None):
"""Load selected job's settings into the form fields."""
sel = self.tree.selection()
if not sel:
return
name = self.tree.item(sel[0])["values"][0]
job = next((j for j in self.scheduler.jobs if j.name == name), None)
if not job:
return
self._editing_job_name = name
self._add_btn_var.set("Update task")
# Populate form
self.name_var.set(job.name)
self.mode_var.set(job.mode)
# Parse time
parts = job.time_str.split(":")
self.hour_var.set(parts[0] if len(parts) >= 1 else "00")
self.min_var.set(parts[1] if len(parts) >= 2 else "00")
self.date_var.set(job.date_str or datetime.now().strftime("%Y-%m-%d"))
self.interval_var.set(str(job.interval_min))
for i in range(7):
self.weekday_vars[i].set(i in job.weekdays)
# Rebuild mode-specific widgets so they show updated values
self._on_mode_change()
def _deselect(self):
"""Clear selection and reset form to add mode."""
self.tree.selection_remove(*self.tree.selection())
self._editing_job_name = None
self._add_btn_var.set("Add to schedule")
self.name_var.set("")
def _add_or_update_job(self):
"""Add a new job or update the currently selected one."""
if self._editing_job_name:
self._update_selected_job()
else:
self._add_job()
def _add_job(self):
name = self.name_var.get().strip()
if not name:
messagebox.showwarning("Scheduler", "Enter a task name.")
return
# Check for duplicate
if any(j.name == name for j in self.scheduler.jobs):
messagebox.showwarning("Scheduler", f"Task '{name}' already exists.")
return
code = self.python_panel.editor.get("1.0", tk.END).strip()
if not code:
messagebox.showwarning("Scheduler", "Editor is empty - enter code to run.")
return
mode = self.mode_var.get()
time_str = f"{self.hour_var.get().zfill(2)}:{self.min_var.get().zfill(2)}"
date_str = self.date_var.get().strip()
try:
interval_min = int(self.interval_var.get())
except ValueError:
interval_min = 30
weekdays = [i for i, v in enumerate(self.weekday_vars) if v.get()]
job = ScheduledJob(
name=name, code=code, mode=mode,
time_str=time_str, date_str=date_str,
interval_min=interval_min, weekdays=weekdays,
)
self.scheduler.add_job(job)
self._refresh_tree()
self._update_status()
self._log(f"Added task '{name}' ({mode}), next: {job.next_run.strftime('%Y-%m-%d %H:%M:%S')}", "info")
self.name_var.set("")
def _update_selected_job(self):
"""Update the currently selected job with form values."""
old_name = self._editing_job_name
job = next((j for j in self.scheduler.jobs if j.name == old_name), None)
if not job:
return
new_name = self.name_var.get().strip()
if not new_name:
messagebox.showwarning("Scheduler", "Enter a task name.")
return
# Check name conflict (if renamed)
if new_name != old_name and any(j.name == new_name for j in self.scheduler.jobs):
messagebox.showwarning("Scheduler", f"Task '{new_name}' already exists.")
return
job.name = new_name
job.mode = self.mode_var.get()
job.time_str = f"{self.hour_var.get().zfill(2)}:{self.min_var.get().zfill(2)}"
job.date_str = self.date_var.get().strip()
try:
job.interval_min = int(self.interval_var.get())
except ValueError:
job.interval_min = 30
job.weekdays = [i for i, v in enumerate(self.weekday_vars) if v.get()]
job.code = self.python_panel.editor.get("1.0", tk.END).strip()
job.next_run = self.scheduler._calculate_next_run(job)
self._refresh_tree()
self._update_status()
self._log(f"Updated task '{new_name}' ({job.mode})", "info")
# Reset to add mode
self._editing_job_name = None
self._add_btn_var.set("Add to schedule")
def _run_now(self):
code = self.python_panel.editor.get("1.0", tk.END).strip()
if not code:
messagebox.showwarning("Scheduler", "Editor is empty.")
return
name = self.name_var.get().strip() or "test"
self._log(f"Running '{name}' immediately...", "info")
threading.Thread(target=self._execute_job_code, args=(name, code), daemon=True).start()
def _toggle_selected(self):
sel = self.tree.selection()
if not sel:
return
name = self.tree.item(sel[0])["values"][0]
result = self.scheduler.toggle_job(name)
if result is not None:
state = "active" if result else "paused"
self._log(f"Task '{name}' -> {state}", "info")
self._refresh_tree()
self._update_status()
def _remove_selected(self):
sel = self.tree.selection()
if not sel:
return
name = self.tree.item(sel[0])["values"][0]
self.scheduler.remove_job(name)
self._log(f"Removed task '{name}'", "info")
self._refresh_tree()
self._update_status()
def _refresh_tree(self):
for item in self.tree.get_children():
self.tree.delete(item)
mode_labels = {"once": "Once", "daily": "Daily",
"interval": "Recurring", "weekly": "Weekly"}
for j in self.scheduler.jobs:
status = "Active" if j.active else "Paused"
next_str = j.next_run.strftime("%Y-%m-%d %H:%M") if j.active else "-"
self.tree.insert("", tk.END, values=(j.name, mode_labels.get(j.mode, j.mode),
next_str, status))
def _update_status(self):
active = sum(1 for j in self.scheduler.jobs if j.active)
nxt = self.scheduler.next_scheduled()
if active == 0:
self.status_var.set("No active tasks")
elif nxt:
self.status_var.set(f"Active: {active} | Next: {nxt.strftime('%H:%M:%S')}")
else:
self.status_var.set(f"Active: {active}")
def _tick(self):
"""Check every second if a task needs to run."""
due = self.scheduler.get_due_jobs()
for job in due:
self._log(f"Running '{job.name}'...", "time")
self.scheduler.mark_run(job)
threading.Thread(target=self._execute_job_code,
args=(job.name, job.code), daemon=True).start()
if due:
self._refresh_tree()
self._update_status()
self.after(1000, self._tick)
def _execute_job_code(self, name: str, code: str):
"""Run code in a thread, output to log."""
output_queue = queue.Queue()
live_stdout = LiveWriter(output_queue, tag="")
live_stderr = LiveWriter(output_queue, tag="error")
project_dir = os.path.dirname(os.path.abspath(__file__))
if project_dir not in sys.path:
sys.path.insert(0, project_dir)
venv_sp = os.path.join(project_dir, ".venv", "lib")
if os.path.isdir(venv_sp):
import glob as g
for sp in g.glob(os.path.join(venv_sp, "python*", "site-packages")):
if sp not in sys.path:
sys.path.insert(0, sp)
try:
with redirect_stdout(live_stdout), redirect_stderr(live_stderr):
exec(code, {"__name__": "__main__", "__builtins__": __builtins__})
except Exception:
output_queue.put((traceback.format_exc(), "error"))
finally:
output_queue.put(("__DONE__", ""))
# Read all output
lines = []
while True:
try:
text, tag = output_queue.get_nowait()
if text == "__DONE__":
break
lines.append((text, tag))
except queue.Empty:
break
# Display in log (from main thread)
def show():
self._log(f"--- [{name}] {datetime.now().strftime('%H:%M:%S')} ---", "time")
for text, tag in lines:
self._log_raw(text, tag if tag else None)
self.after(0, show)
# Discord - send result if configured
if self.discord_tab and lines:
output_text = "".join(text for text, _ in lines)
self.discord_tab.notify_scheduler_result(name, output_text)
def _log(self, msg: str, tag: str = None):
self.log_text.configure(state=tk.NORMAL)
self.log_text.insert(tk.END, msg + "\n", tag)
self.log_text.configure(state=tk.DISABLED)
self.log_text.see(tk.END)
def _log_raw(self, text: str, tag: str = None):
self.log_text.configure(state=tk.NORMAL)
if tag:
self.log_text.insert(tk.END, text, tag)
else:
self.log_text.insert(tk.END, text)
self.log_text.configure(state=tk.DISABLED)
self.log_text.see(tk.END)
# --- JSON Configuration ---
def save_to_config(self, cm: ConfigManager):
cm.save_scheduler_jobs(self.scheduler.jobs)
def load_from_config(self, cm: ConfigManager):
jobs_data = cm.get_scheduler_jobs()
# Remove existing jobs
self.scheduler.jobs.clear()
for jd in jobs_data:
job = ScheduledJob(
name=jd.get("name", "unnamed"),
code=jd.get("code", ""),
mode=jd.get("mode", "interval"),
time_str=jd.get("time_str", "00:00"),
date_str=jd.get("date_str", ""),
interval_min=jd.get("interval_min", 30),
weekdays=jd.get("weekdays", []),
timezone=jd.get("timezone", ""),
active=jd.get("active", True),
)
self.scheduler.add_job(job)
self._refresh_tree()
self._update_status()
if jobs_data:
self._log(f"Loaded {len(jobs_data)} tasks from configuration", "info")
# ============================================================
# Context Keeper - automatic context reminders
# ============================================================
_DEFAULT_CONTEXT = """=== SYSTEM CONTEXT ===
You are an autonomous assistant working in a task automation environment. \
The user uses you as a pipeline element - your responses may be \
processed automatically, cyclically, and without supervision.
Environment: {pwd}
Available tools: Python script execution, web scraper (Crawl4AI), \
task scheduler (Scheduler), external API integration.
Typical use cases:
- Data monitoring and analysis (stock market, statistics)
- Automatic checking and processing of information (emails, notifications, RSS)
- Periodic reports and summaries
- Pipelines combining scraping -> analysis -> decision -> action
- Any repetitive tasks run on schedule
Rules:
- You operate in automatic mode - respond concretely, without unnecessary preamble
- Priority: user security and privacy > correctness > speed
- Do not send user data externally without their knowledge
- Do not perform destructive operations without confirmation
- If something is unclear and you're in manual mode - ask; in auto mode - \
use safe default behavior
=== END OF CONTEXT ==="""
class ContextKeeperTab(ttk.Frame):
"""Context Keeper tab - manage context and reminders for Claude."""
def __init__(self, parent, claude_tab: ClaudeTab):
super().__init__(parent)
self.claude_tab = claude_tab
self._call_count = 0
self._lock = threading.Lock()
self._build_ui()
# Global hook - injects context into EVERY ClaudeCode.ask()
ClaudeCode.set_message_hook(self._message_hook)
def _build_ui(self):
# --- Active toggle (top) ---
top_row = ttk.Frame(self)
top_row.pack(side=tk.TOP, fill=tk.X, padx=8, pady=(8, 4))
self.active_var = tk.BooleanVar(value=True)
ttk.Checkbutton(top_row, text="Context Keeper active",
variable=self.active_var).pack(side=tk.LEFT)
self.counter_var = tk.StringVar(value="Calls: 0")
ttk.Label(top_row, textvariable=self.counter_var,
font=("monospace", 9, "italic"), foreground="#6c7086").pack(side=tk.RIGHT)
# --- Buttons (bottom) - pack from bottom to guarantee space ---
btn_frame = ttk.Frame(self)
btn_frame.pack(side=tk.BOTTOM, fill=tk.X, padx=4, pady=(0, 4))
ttk.Button(btn_frame, text="Send context now",
command=self._send_now).pack(side=tk.LEFT, padx=(0, 4))
ttk.Button(btn_frame, text="Reset counter",
command=self._reset_counter).pack(side=tk.LEFT, padx=(0, 4))
ttk.Button(btn_frame, text="Restore default prompt",