-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
6068 lines (5540 loc) · 264 KB
/
Copy pathmain.py
File metadata and controls
6068 lines (5540 loc) · 264 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
# -- coding: utf-8 --
"""
main.py — FRIDAY Autonomous AI Assistant (patched v10.6)
Changes from v10.5:
[FIX-11] record_interaction() called after every tool
[FIX-12] Confidence synced to curiosity module after each tool execution
[FIX-13] Dreaming system notified of user activity (tool + text)
[FIX-14] User topics tracked for curiosity mirroring
[FIX-15] Idle exploration check runs during active sessions
[FIX-16] Audit logger flushed on shutdown
[FIX-17] Permission manager cleanup thread stopped on shutdown
[FIX-18] Removed duplicate curiosity.encounter() call
[FIX-19] Shutdown flag checked even when tool response send fails
[FIX-20] Runner thread logs message on normal exit
"""
import asyncio
import json
import os
import re
import struct
import sys
import threading
import time
import traceback
import unicodedata
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta
from pathlib import Path
_project_root = Path(__file__).resolve().parent
if str(_project_root) not in sys.path:
sys.path.insert(0, str(_project_root))
import sounddevice as sd
from google import genai
from google.genai import types
def _is_ws_dead_error(err_str: str) -> bool:
"""Detect WebSocket dead errors (e.g., 1006, 1011, closed)."""
return any(k in err_str for k in (
"1006", "1011", "closed", "not connected",
"connection reset", "broken pipe",
))
try:
from ui import FridayUI
except Exception as e:
print(f"[FRIDAY] UI import failed: {e}", flush=True)
raise
# ── Brain module imports (all wrapped) ────────────────────────────────
_brain_neural_memory_ok = False
try:
from brain.neural_memory import (
load_memory, update_memory, format_memory_for_prompt, get_brain,
)
_brain_neural_memory_ok = True
except Exception as e:
print(f"[FRIDAY] brain.neural_memory: {e}", flush=True)
load_memory = update_memory = format_memory_for_prompt = get_brain = None
_brain_learning_ok = False
try:
from brain.learning import (
get_learning_engine, init_learnings_file, EventType,
)
_brain_learning_ok = True
except Exception as e:
print(f"[FRIDAY] brain.learning: {e}", flush=True)
get_learning_engine = init_learnings_file = EventType = None
_brain_self_model_ok = False
try:
from brain.self_model import get_self_model
_brain_self_model_ok = True
except Exception as e:
print(f"[FRIDAY] brain.self_model: {e}", flush=True)
get_self_model = None
_brain_active_inference_ok = False
try:
from brain.active_inference import get_active_inference
_brain_active_inference_ok = True
except Exception as e:
print(f"[FRIDAY] brain.active_inference: {e}", flush=True)
get_active_inference = None
_brain_dreaming_ok = False
try:
from brain.dreaming import get_dreaming_system
_brain_dreaming_ok = True
except Exception as e:
print(f"[FRIDAY] brain.dreaming: {e}", flush=True)
get_dreaming_system = None
_brain_curiosity_ok = False
try:
from brain.curiosity import get_curiosity_module
_brain_curiosity_ok = True
except Exception as e:
print(f"[FRIDAY] brain.curiosity: {e}", flush=True)
get_curiosity_module = None
_brain_self_awareness_ok = False
try:
from brain.self_awareness import get_self_awareness, CognitiveEvent
_brain_self_awareness_ok = True
except Exception as e:
print(f"[FRIDAY] brain.self_awareness: {e}", flush=True)
get_self_awareness = CognitiveEvent = None
_brain_coordinator_ok = False
try:
from brain.memory_coordinator import get_memory_coordinator
_brain_coordinator_ok = True
except Exception as e:
print(f"[FRIDAY] brain.memory_coordinator: {e}", flush=True)
get_memory_coordinator = None
_brain_procedural_ok = False
try:
from brain.procedural_memory import get_procedural_memory
_brain_procedural_ok = True
except Exception as e:
print(f"[FRIDAY] brain.procedural_memory: {e}", flush=True)
get_procedural_memory = None
_brain_episodic_ok = False
try:
from brain.episodic_memory import get_episodic_memory
_brain_episodic_ok = True
except Exception as e:
print(f"[FRIDAY] brain.episodic_memory: {e}", flush=True)
get_episodic_memory = None
_brain_vector_ok = False
try:
from brain.vector_memory import get_vector_memory
_brain_vector_ok = True
except Exception as e:
print(f"[FRIDAY] brain.vector_memory: {e}", flush=True)
get_vector_memory = None
# ── Global Workspace (Thalamus) ───────────────────────────────────────
_brain_workspace_ok = False
try:
from brain.global_workspace import get_global_workspace, GlobalWorkspace
from brain.workspace_events import EventType as WsEventType, WorkspaceEvent
from brain.workspace_context import inject_workspace_context
from brain.workspace_adapters import (
SelfAwarenessAdapter, LearningAdapter, ActiveInferenceAdapter,
CuriosityAdapter, DreamingAdapter, SelfModelAdapter,
NeuralMemoryAdapter, EpisodicMemoryAdapter, ProceduralMemoryAdapter,
MetaCognitionAdapter, MemoryCoordinatorAdapter,
)
_brain_workspace_ok = True
_brain_voice_modulator_ok = False
try:
from brain.voice_modulator import get_voice_modulator, VoiceEmotion
_brain_voice_modulator_ok = True
except Exception as e:
print(f"[FRIDAY] brain.voice_modulator: {e}", flush=True)
get_voice_modulator = None
VoiceEmotion = None
_brain_proactive_ok = False
try:
from brain.proactive_engine import get_proactive_engine
_brain_proactive_ok = True
except Exception as e:
print(f"[FRIDAY] brain.proactive_engine: {e}", flush=True)
get_proactive_engine = None
_brain_proactive_checkin_ok = False
try:
from brain.proactive_checkin import get_proactive_checkin
_brain_proactive_checkin_ok = True
except Exception as e:
print(f"[FRIDAY] brain.proactive_checkin: {e}", flush=True)
get_proactive_checkin = None
_brain_agi_orch_ok = False
try:
from brain.agi_orchestrator import get_agi_orchestrator
_brain_agi_orch_ok = True
except Exception as e:
print(f"[FRIDAY] brain.agi_orchestrator: {e}", flush=True)
get_agi_orchestrator = None
except Exception as e:
print(f"[FRIDAY] brain.global_workspace: {e}", flush=True)
get_global_workspace = GlobalWorkspace = None
WsEventType = WorkspaceEvent = inject_workspace_context = None
SelfAwarenessAdapter = LearningAdapter = ActiveInferenceAdapter = None
CuriosityAdapter = DreamingAdapter = SelfModelAdapter = None
NeuralMemoryAdapter = EpisodicMemoryAdapter = ProceduralMemoryAdapter = None
MetaCognitionAdapter = MemoryCoordinatorAdapter = None
_telegram_ok = False
try:
from friday_telegram_patch import TelegramBridge
_telegram_ok = True
except Exception as e:
print(f"[FRIDAY] TelegramBridge: {e}", flush=True)
TelegramBridge = None
# ── Action imports ────────────────────────────────────────────────────
def _safe_action_import(module_path, names):
try:
mod = __import__(module_path, fromlist=[names] if isinstance(names, str) else names)
if isinstance(names, str):
return getattr(mod, names), True
return {n: getattr(mod, n) for n in names}, True
except Exception as e:
print(f"[FRIDAY] {module_path}: {e}", flush=True)
return None, False
flight_finder, _ = _safe_action_import("actions.flight_finder", "flight_finder")
open_app, _ = _safe_action_import("actions.open_app", "open_app")
weather_action, _ = _safe_action_import("actions.weather_report", "weather_action")
send_message, _ = _safe_action_import("actions.send_message", "send_message")
reminder, _ = _safe_action_import("actions.reminder", "reminder")
computer_settings, _ = _safe_action_import("actions.computer_settings", "computer_settings")
screen_process, _ = _safe_action_import("actions.screen_processor", "screen_process")
youtube_video, _ = _safe_action_import("actions.youtube_video", "youtube_video")
desktop_control, _ = _safe_action_import("actions.desktop", "desktop_control")
browser_control, _ = _safe_action_import("actions.browser_control", "browser_control")
file_controller, _ = _safe_action_import("actions.file_controller", "file_controller")
code_helper, _ = _safe_action_import("actions.code_helper", "code_helper")
dev_agent, _ = _safe_action_import("actions.dev_agent", "dev_agent")
web_search_action, _ = _safe_action_import("actions.web_search", "web_search")
computer_control, _ = _safe_action_import("actions.computer_control", "computer_control")
game_updater, _ = _safe_action_import("actions.game_updater", "game_updater")
web_research, _ = _safe_action_import("actions.web_research", "web_research")
agency_agent_action, _ = _safe_action_import("actions.agency_agent", "agency_agent")
agency_list_agents, _ = _safe_action_import("actions.agency_agent", "list_agents")
# ── Cognitive Coding Engine imports ─────────────────────────────────────
_cognitive_coding_ok = False
try:
from actions.cognitive_coder import cognitive_code
_cognitive_coding_ok = True
except Exception as e:
print(f"[FRIDAY] cognitive_coder: {e}", flush=True)
cognitive_code = None
_brain_code_intelligence_ok = False
try:
from brain.code_intelligence import get_code_intelligence
_brain_code_intelligence_ok = True
except Exception as e:
print(f"[FRIDAY] brain.code_intelligence: {e}", flush=True)
get_code_intelligence = None
_brain_code_planner_ok = False
try:
from brain.code_planner import get_code_planner
_brain_code_planner_ok = True
except Exception as e:
print(f"[FRIDAY] brain.code_planner: {e}", flush=True)
get_code_planner = None
_brain_code_simulator_ok = False
try:
from brain.code_simulator import get_code_simulator
_brain_code_simulator_ok = True
except Exception as e:
print(f"[FRIDAY] brain.code_simulator: {e}", flush=True)
get_code_simulator = None
_brain_code_reflector_ok = False
try:
from brain.code_reflector import get_code_reflector
_brain_code_reflector_ok = True
except Exception as e:
print(f"[FRIDAY] brain.code_reflector: {e}", flush=True)
get_code_reflector = None
_brain_self_modifier_ok = False
try:
from brain.self_modifier import get_self_modifier
_brain_self_modifier_ok = True
except Exception as e:
print(f"[FRIDAY] brain.self_modifier: {e}", flush=True)
get_self_modifier = None
# ── Disconnected cognitive module imports ──────────────────────────────
_brain_analogy_ok = False
try:
from brain.analogy_engine import get_analogy_engine
_brain_analogy_ok = True
except Exception as e:
print(f"[FRIDAY] brain.analogy_engine: {e}", flush=True)
get_analogy_engine = None
_brain_causal_ok = False
try:
from brain.causal_reasoner import get_causal_reasoner
_brain_causal_ok = True
except Exception as e:
print(f"[FRIDAY] brain.causal_reasoner: {e}", flush=True)
get_causal_reasoner = None
_brain_creativity_ok = False
try:
from brain.creativity_engine import get_creativity_engine
_brain_creativity_ok = True
except Exception as e:
print(f"[FRIDAY] brain.creativity_engine: {e}", flush=True)
get_creativity_engine = None
_brain_meta_learner_ok = False
try:
from brain.meta_learner import get_meta_learner
_brain_meta_learner_ok = True
except Exception as e:
print(f"[FRIDAY] brain.meta_learner: {e}", flush=True)
get_meta_learner = None
_brain_module_competition_ok = False
try:
from brain.module_competition import get_module_competition
_brain_module_competition_ok = True
except Exception as e:
print(f"[FRIDAY] brain.module_competition: {e}", flush=True)
get_module_competition = None
_brain_neurosymbolic_ok = False
try:
from brain.neurosymbolic_reasoner import get_neurosymbolic_reasoner
_brain_neurosymbolic_ok = True
except Exception as e:
print(f"[FRIDAY] brain.neurosymbolic_reasoner: {e}", flush=True)
get_neurosymbolic_reasoner = None
_brain_narrative_ok = False
try:
from brain.narrative_intelligence import get_narrative_intelligence
_brain_narrative_ok = True
except Exception as e:
print(f"[FRIDAY] brain.narrative_intelligence: {e}", flush=True)
get_narrative_intelligence = None
_brain_world_model_ok = False
try:
from brain.world_model import get_world_model
_brain_world_model_ok = True
except Exception as e:
print(f"[FRIDAY] brain.world_model: {e}", flush=True)
get_world_model = None
_brain_enhanced_wm_ok = False
try:
from brain.enhanced_world_model import get_enhanced_world_model
_brain_enhanced_wm_ok = True
except Exception as e:
print(f"[FRIDAY] brain.enhanced_world_model: {e}", flush=True)
get_enhanced_world_model = None
_brain_hierarchical_aif_ok = False
try:
from brain.hierarchical_active_inference import get_hierarchical_aif
_brain_hierarchical_aif_ok = True
except Exception as e:
print(f"[FRIDAY] brain.hierarchical_active_inference: {e}", flush=True)
get_hierarchical_aif = None
_brain_integrated_info_ok = False
try:
from brain.integrated_info import get_integrated_info
_brain_integrated_info_ok = True
except Exception as e:
print(f"[FRIDAY] brain.integrated_info: {e}", flush=True)
get_integrated_info = None
_brain_transfer_learning_ok = False
try:
from brain.transfer_learning import get_transfer_learning
_brain_transfer_learning_ok = True
except Exception as e:
print(f"[FRIDAY] brain.transfer_learning: {e}", flush=True)
get_transfer_learning = None
_brain_self_improve_ok = False
try:
from brain.self_improve_engine import get_self_improve_engine
_brain_self_improve_ok = True
except Exception as e:
print(f"[FRIDAY] brain.self_improve_engine: {e}", flush=True)
get_self_improve_engine = None
_brain_findings_bus_ok = False
try:
from brain.findings_bus import get_findings_bus
_brain_findings_bus_ok = True
except Exception as e:
print(f"[FRIDAY] brain.findings_bus: {e}", flush=True)
get_findings_bus = None
_brain_model_router_ok = False
try:
from brain.model_router import get_model_router
_brain_model_router_ok = True
except Exception as e:
print(f"[FRIDAY] brain.model_router: {e}", flush=True)
get_model_router = None
_brain_intuition_ok = False
try:
from brain.intuition_engine import get_intuition_engine
_brain_intuition_ok = True
except Exception as e:
print(f"[FRIDAY] brain.intuition_engine: {e}", flush=True)
get_intuition_engine = None
_brain_metacognitive_ok = False
try:
from brain.metacognitive_monitor import get_metacognitive_monitor
_brain_metacognitive_ok = True
except Exception as e:
print(f"[FRIDAY] brain.metacognitive_monitor: {e}", flush=True)
get_metacognitive_monitor = None
_brain_emotional_regulation_ok = False
try:
from brain.emotional_regulation import get_emotional_regulation
_brain_emotional_regulation_ok = True
except Exception as e:
print(f"[FRIDAY] brain.emotional_regulation: {e}", flush=True)
get_emotional_regulation = None
_brain_cognitive_integration_ok = False
try:
from brain.cognitive_integration import get_cognitive_integration
_brain_cognitive_integration_ok = True
except Exception as e:
print(f"[FRIDAY] brain.cognitive_integration: {e}", flush=True)
get_cognitive_integration = None
_brain_cognitive_appraisal_ok = False
try:
from brain.cognitive_appraisal import get_cognitive_appraisal
_brain_cognitive_appraisal_ok = True
except Exception as e:
print(f"[FRIDAY] brain.cognitive_appraisal: {e}", flush=True)
get_cognitive_appraisal = None
_brain_cognitive_load_ok = False
try:
from brain.cognitive_load import get_cognitive_load_manager
_brain_cognitive_load_ok = True
except Exception as e:
print(f"[FRIDAY] brain.cognitive_load: {e}", flush=True)
get_cognitive_load_manager = None
_agi_multi_agent_ok = False
try:
from brain.multi_agent_orchestrator import get_multi_agent_orchestrator
_agi_multi_agent_ok = True
except Exception as e:
print(f"[FRIDAY] brain.multi_agent_orchestrator: {e}", flush=True)
get_multi_agent_orchestrator = None
_agi_goal_ok = False
try:
from brain.goal_engine import get_goal_engine
_agi_goal_ok = True
except Exception as e:
print(f"[FRIDAY] brain.goal_engine: {e}", flush=True)
get_goal_engine = None
_agi_motivation_ok = False
try:
from brain.intrinsic_motivation import get_intrinsic_motivation
_agi_motivation_ok = True
except Exception as e:
print(f"[FRIDAY] brain.intrinsic_motivation: {e}", flush=True)
get_intrinsic_motivation = None
_agi_planner_ok = False
try:
from brain.autonomous_planner import get_autonomous_planner
_agi_planner_ok = True
except Exception as e:
print(f"[FRIDAY] brain.autonomous_planner: {e}", flush=True)
get_autonomous_planner = None
_agi_mem_consolidation_ok = False
try:
from brain.memory_consolidation import get_memory_consolidation
_agi_mem_consolidation_ok = True
except Exception as e:
print(f"[FRIDAY] brain.memory_consolidation: {e}", flush=True)
get_memory_consolidation = None
_agi_associative_ok = False
try:
from brain.associative_memory import get_associative_memory
_agi_associative_ok = True
except Exception as e:
print(f"[FRIDAY] brain.associative_memory: {e}", flush=True)
get_associative_memory = None
_agi_predictive_ok = False
try:
from brain.predictive_memory import get_predictive_memory
_agi_predictive_ok = True
except Exception as e:
print(f"[FRIDAY] brain.predictive_memory: {e}", flush=True)
get_predictive_memory = None
_agi_tom_ok = False
try:
from brain.theory_of_mind import get_theory_of_mind
_agi_tom_ok = True
except Exception as e:
print(f"[FRIDAY] brain.theory_of_mind: {e}", flush=True)
get_theory_of_mind = None
_agi_abstraction_ok = False
try:
from brain.abstraction_engine import get_abstraction_engine
_agi_abstraction_ok = True
except Exception as e:
print(f"[FRIDAY] brain.abstraction_engine: {e}", flush=True)
get_abstraction_engine = None
_agi_introspection_ok = False
try:
from brain.introspection_engine import get_introspection_engine
_agi_introspection_ok = True
except Exception as e:
print(f"[FRIDAY] brain.introspection_engine: {e}", flush=True)
get_introspection_engine = None
_agi_world_sim_ok = False
try:
from brain.world_simulation import get_world_simulation
_agi_world_sim_ok = True
except Exception as e:
print(f"[FRIDAY] brain.world_simulation: {e}", flush=True)
get_world_simulation = None
_agi_code_evolution_ok = False
try:
from brain.code_evolution import get_code_evolution
_agi_code_evolution_ok = True
except Exception as e:
print(f"[FRIDAY] brain.code_evolution: {e}", flush=True)
get_code_evolution = None
_verification_ok = False
try:
from actions.verification import (
is_window_focused, ensure_window_focused, verify_app_opened,
verify_message_sent_in_chat, vision_query, screenshot_as_part,
ActionVerifier,
)
_verification_ok = True
except Exception as e:
print(f"[FRIDAY] verification module: {e}", flush=True)
_thinking_loop_ok = False
try:
from thinking_loop import think as thinking_loop_think
from thinking_loop import reflect_on_outcome as thinking_loop_reflect
_thinking_loop_ok = True
except Exception as e:
print(f"[FRIDAY] thinking_loop: {e}", flush=True)
_ai_pipeline_ok = False
try:
from actions.ai_pipeline import (
summarize_text, analyze_sentiment, extract_entities,
translate_text, process_document,
)
_ai_pipeline_ok = True
except Exception:
pass
_integrations_ok = False
try:
from brain.integrations import (
analyze_data, query_data, generate_chart,
integration_status, get_system_dashboard,
)
_integrations_ok = True
except Exception:
pass
# ── Security imports ──────────────────────────────────────────────────
_security_ok = False
try:
from security import (
get_permission_manager, get_audit_logger, get_config_validator,
get_lock_state, RiskTier, Decision,
)
from security.audit_logger import redact_params
from security.config_validator import ConfigValidationError
_security_ok = True
except Exception as e:
print(f"[FRIDAY] Security: {e}", flush=True)
_rate_limiter_available = False
try:
from security.tools_guard import get_rate_limiter
_rate_limiter_available = True
except ImportError:
pass
if not _security_ok:
print("[FRIDAY] Security module not available — using permissive fallback", flush=True)
class _FakePermMgr:
def check_tool(self, *a, **kw): return "allow", "no security module"
def get_risk_tier(self, *a, **kw): return 0
def shutdown(self): pass
class _FakeAudit:
def log(self, **kw): pass
def shutdown(self): pass
class _FakeLockState:
def check_and_log(self, *a, **kw): return True, ""
class _FakeDecision:
ALLOW = "allow"
DENY = "deny"
ASK = "ask"
get_permission_manager = lambda: _FakePermMgr()
get_audit_logger = lambda: _FakeAudit()
get_lock_state = lambda: _FakeLockState()
Decision = _FakeDecision()
RiskTier = type('RiskTier', (), {'HIGH': 2, 'MEDIUM': 1, 'LOW': 0})()
redact_params = lambda x: x
class ConfigValidationError(Exception): pass
def get_config_validator():
class _V:
def load(self, p): pass
def validate(self): return []
def get_api_key(self): return ""
return _V()
# ── Optional imports ──────────────────────────────────────────────────
try:
from actions.holo_builder import holo_builder as holo_builder_action
_holo_available = True
except ImportError:
_holo_available = False
# ── Cyber features gated behind config flag (disabled by default) ──
_cyber_enabled = False
try:
_cfg_data = json.loads((BASE_DIR / "config" / "api_keys.json").read_text(encoding="utf-8"))
_cyber_enabled = bool(_cfg_data.get("cyber_enabled", False))
except Exception:
pass
# ── Cyber authorization (consent gate for live operations) ──
_cyber_auth_manager = None
if _cyber_enabled:
try:
from cyber.authorization import (
get_auth_manager as _get_auth_manager,
grant_consent as _grant_consent,
is_live_operation as _is_live_op,
CONSENT_PHRASE as _CONSENT_PHRASE,
)
_cyber_auth_manager = _get_auth_manager()
except ImportError:
pass
if _cyber_enabled:
try:
from actions.security_tools import security_tools
_security_tools_available = True
except ImportError:
_security_tools_available = False
else:
_security_tools_available = False
try:
from actions.holographic_map import holographic_map as holo_map_action
_holo_map_available = True
except ImportError:
_holo_map_available = False
try:
from actions.holo_earth import holo_earth as holo_earth_action
_holo_earth_available = True
except ImportError:
_holo_earth_available = False
try:
from actions.ac_controller import (
turn_on as ac_turn_on, turn_off as ac_turn_off,
set_temperature as ac_set_temp, set_fan_speed as ac_set_fan,
set_mode as ac_set_mode, get_status as ac_get_status,
)
_ac_available = True
except ImportError:
_ac_available = False
try:
from agent.task_queue import get_queue, TaskPriority
_task_queue_available = True
except ImportError:
_task_queue_available = False
try:
from gesture_music_system.main import GestureMusicSystem
_gesture_available = True
except ImportError:
_gesture_available = False
try:
from gesture_music_system.actions import MusicController
_music_ctrl = MusicController()
except Exception:
_music_ctrl = None
_skills_ok = False
try:
from skills.deep_dive import DeepDiveAgent
from skills.sentinel import SystemSentinel
from skills.neural_clipboard import NeuralClipboard
from skills.social_pulse import SocialPulse
from skills.auto_doc import AutoDocEngine
from skills.digital_twin import DigitalTwin
from skills.cognitive_gating import assess_complexity
from skills.working_memory import get_working_memory
from skills.meta_reflect import get_meta_reflection
from skills.decision_journal import get_decision_journal
from skills.experience_replay import get_experience_replay
from skills.adaptive_planner import get_adaptive_planner
from skills.screen_watcher import ScreenWatcher
from skills.research_agent import get_research_agent
from skills.creative_studio import get_creative_studio
from skills.document_intelligence import get_document_intelligence
_skills_ok = True
except Exception:
pass
try:
import cv2
except ImportError:
pass
# ── Force unbuffered stdout ───────────────────────────────────────────
try:
sys.stdout.reconfigure(line_buffering=True)
sys.stderr.reconfigure(line_buffering=True)
except Exception:
pass
# ── Constants ─────────────────────────────────────────────────────────
def get_base_dir():
if getattr(sys, "frozen", False):
return Path(sys.executable).parent
return Path(__file__).resolve().parent
BASE_DIR = get_base_dir()
API_CONFIG_PATH = BASE_DIR / "config" / "api_keys.json"
PROMPT_PATH = BASE_DIR / "core" / "prompt.txt"
LIVE_MODEL = "models/gemini-2.5-flash-native-audio-preview-12-2025"
CHANNELS = 1
SEND_SAMPLE_RATE = 16000
RECEIVE_SAMPLE_RATE = 24000
CHUNK_SIZE = 1024
KEEPALIVE_INTERVAL = 5
MAX_INSTRUCTION_LEN = 28000
MAX_RECONNECT_DELAY = 120
MAX_TOOL_RESULT_LEN = 2000
VALID_MEMORY_CATEGORIES = {
"identity", "preferences", "projects",
"relationships", "wishes", "notes",
}
_VALID_PARAMS = {
"browser_control": {
"action", "browser", "url", "query", "engine", "selector",
"text", "description", "direction", "amount", "key", "path",
"incognito", "clear_first",
},
"computer_control": {
"action", "text", "x", "y", "keys", "key", "direction",
"amount", "seconds", "title", "description", "data_type",
"field", "clear_first", "path",
},
"computer_settings": {
"action", "description", "value",
},
}
class _SessionDead(Exception):
pass
class _NullCallable:
def __call__(self, *a, **kw):
return None
def __await__(self):
if False:
yield
return None
class _NullModule:
# ── Security rate limiter import ───────────────────────────────────────
try:
from security.tools_guard import get_rate_limiter
_rate_limiter_available = True
except ImportError:
_rate_limiter_available = False
def __getattr__(self, name):
return _NullCallable()
# ── Config & Prompt Helpers ───────────────────────────────────────────
def _get_api_key() -> str:
try:
validator = get_config_validator()
validator.load(API_CONFIG_PATH)
errors = validator.validate()
if not errors:
return validator.get_api_key()
except Exception:
pass
try:
data = json.loads(API_CONFIG_PATH.read_text(encoding="utf-8"))
for key_name in ("GOOGLE_API_KEY", "google_api_key", "api_key", "gemini_api_key"):
if key_name in data and data[key_name]:
return data[key_name]
for v in data.values():
if isinstance(v, str) and len(v) > 20:
return v
except Exception:
pass
raise ConfigValidationError(f"Cannot read API key from {API_CONFIG_PATH}")
def _load_system_prompt() -> str:
try:
return PROMPT_PATH.read_text(encoding="utf-8-sig").strip()
except Exception:
return (
"You are FRIDAY, Tony Stark's AI assistant. "
"Be concise, direct, and always use the provided tools to complete tasks. "
"Never simulate or guess results — always call the appropriate tool."
)
_CTRL_RE = re.compile(r"<ctrl\d+>", re.IGNORECASE)
def _clean_transcript(text: str) -> str:
text = _CTRL_RE.sub("", text)
text = re.sub(r"[\x00-\x08\x0b-\x1f\x7f]", "", text)
return text.strip()
def _check_audio_devices():
try:
inp = sd.query_devices(kind="input")
out = sd.query_devices(kind="output")
has_input = inp is not None
has_output = out is not None
if isinstance(inp, list):
has_input = len(inp) > 0
if isinstance(out, list):
has_output = len(out) > 0
return has_input, has_output
except Exception:
return False, False
def _safe_queue_put(q, item):
try:
q.put_nowait(item)
except asyncio.QueueFull:
try:
q.get_nowait()
except asyncio.QueueEmpty:
pass
try:
q.put_nowait(item)
except asyncio.QueueFull:
pass
def _call_with_optional_speak(fn, speak_fn, **kwargs):
try:
return fn(speak=speak_fn, **kwargs)
except TypeError:
return fn(**kwargs)
def _safe_thread(fn, tool_name, **kwargs):
"""Run *fn* in a thread, silently dropping kwargs it doesn't accept.
If the first call raises TypeError (unexpected kwarg), we introspect
the function signature and retry with only the kwargs it actually
supports. This prevents tool dispatch from crashing when an action
module hasn't been updated to accept ``player`` or other new args.
"""
import inspect
def _run():
try:
fn(**kwargs)
except TypeError as te:
# Likely an unsupported kwarg — retry with only accepted params
try:
sig = inspect.signature(fn)
supported = set(sig.parameters.keys())
# If it accepts **kwargs, everything is supported — so the
# error is something else; re-raise.
has_var_keyword = any(
p.kind == inspect.Parameter.VAR_KEYWORD
for p in sig.parameters.values()
)
if has_var_keyword:
print(f"[FRIDAY] {tool_name} thread error: {te}")
traceback.print_exc()
return
filtered = {k: v for k, v in kwargs.items() if k in supported}
fn(**filtered)
except Exception as e2:
print(f"[FRIDAY] {tool_name} thread error: {e2}")
traceback.print_exc()
except Exception as e:
print(f"[FRIDAY] {tool_name} thread error: {e}")
traceback.print_exc()
return _run
def _truncate(text, max_len=MAX_TOOL_RESULT_LEN):
s = str(text)
if len(s) <= max_len:
return s
return s[:max_len] + "\n[truncated]"
# ── Tool Registry ─────────────────────────────────────────────────────
TOOL_REGISTRY = {}
def register_tool(name):
def decorator(fn):
TOOL_REGISTRY[name] = fn
return fn
return decorator
# ── TOOL DECLARATIONS ────────────────────────────────────────────────
TOOL_DECLARATIONS = [
{
"name": "open_app",
"description": "Opens any application on the computer. Use this whenever the user asks to open, launch, or start any app, website, or program. Always call this tool — never just say you opened it.",
"parameters": {
"type": "OBJECT",
"properties": {
"app_name": {"type": "STRING", "description": "Exact name of the application (e.g. 'WhatsApp', 'Chrome', 'Spotify')"}
},
"required": ["app_name"]
}
},
{
"name": "web_search",
"description": "Quick web search for factual answers, current events, or simple lookups. Returns snippets and links. Use this FIRST for any search — only use web_research if web_search results are insufficient.",
"parameters": {
"type": "OBJECT",
"properties": {
"query": {"type": "STRING", "description": "Search query"},
"mode": {"type": "STRING", "description": "search (default) for normal search. compare to compare items side-by-side — requires 'items' parameter."},
"items": {"type": "ARRAY", "items": {"type": "STRING"}, "description": "Items to compare. Only used when mode=compare."},
"aspect": {"type": "STRING", "description": "Comparison aspect: price | specs | reviews. Only used when mode=compare."}
},
"required": ["query"]
}
},
{
"name": "weather_report",
"description": "Gives the weather report to user",
"parameters": {
"type": "OBJECT",
"properties": {"city": {"type": "STRING", "description": "City name"}},
"required": ["city"]
}
},
{
"name": "send_message",
"description": "Sends a text message via WhatsApp, Telegram, or other messaging platform.",
"parameters": {
"type": "OBJECT",
"properties": {
"receiver": {"type": "STRING", "description": "Recipient contact name"},
"message_text": {"type": "STRING", "description": "The message to send"},
"platform": {"type": "STRING", "description": "Platform: WhatsApp, Telegram, etc."}
},
"required": ["receiver", "message_text", "platform"]
}
},
{
"name": "reminder",
"description": "Sets a timed reminder using Task Scheduler.",
"parameters": {
"type": "OBJECT",
"properties": {
"date": {"type": "STRING", "description": "Date in YYYY-MM-DD format"},
"time": {"type": "STRING", "description": "Time in HH:MM format (24h)"},
"message": {"type": "STRING", "description": "Reminder message text"}
},