-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand_handler.py
More file actions
5914 lines (5460 loc) · 279 KB
/
command_handler.py
File metadata and controls
5914 lines (5460 loc) · 279 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
"""
Command Handler — Routes and executes all /commands for the agent.
Extracted from ultimate_agent.py for modularity.
"""
import os
import sys
import json
import asyncio
from typing import List
from config import CONFIG
class CommandHandler:
"""Handles all /command routing and execution."""
def __init__(self, agent):
self.agent = agent
async def handle(self, cmd_full: str):
"""Main command router."""
agent = self.agent
parts = cmd_full.strip().split()
if not parts:
return
cmd = parts[0].lower()
args = parts[1:]
if cmd == "/omega":
await self._cmd_omega()
return
agent.log_ui(f"Command: {cmd_full}")
# --- OpenClaw-style commands ---
if cmd == "/skills":
self._cmd_skills()
elif cmd == "/tools":
self._cmd_tools()
elif cmd == "/heartbeat":
await asyncio.to_thread(self._cmd_heartbeat)
elif cmd == "/react":
await self._cmd_react(args)
elif cmd == "/voice":
agent.voice_mode = not agent.voice_mode
print(f"🎤 Voice: {'ON' if agent.voice_mode else 'OFF'}")
elif cmd == "/live":
agent.live_mode = not agent.live_mode
print(f"📡 Live: {'ON' if agent.live_mode else 'OFF'}")
elif cmd == "/status":
self._show_status()
elif cmd == "/eval":
self._show_eval()
elif cmd == "/analyze":
await self._show_analysis()
elif cmd == "/improve":
print("Improvement goal (or Enter for auto): ", end="", flush=True)
goal = (await asyncio.to_thread(input)).strip()
print("🧠 Self-improving...", flush=True)
r = await asyncio.to_thread(agent.self_improve, goal)
print(json.dumps(r, indent=2), flush=True)
elif cmd == "/add":
await asyncio.to_thread(self._interactive_add)
elif cmd == "/modify":
await asyncio.to_thread(self._interactive_modify)
elif cmd == "/backups":
for b in agent.self_mod.list_backups()[-10:]:
print(f" 📁 {b['file']} ({b['size']} bytes)")
elif cmd == "/rollback":
await asyncio.to_thread(self._interactive_rollback)
elif cmd == "/export":
r = agent.self_mod.export_log()
print(f"📦 {r}")
elif cmd == "/search":
if not args:
print("Search memory: ", end="", flush=True)
q = await asyncio.to_thread(input)
else:
q = " ".join(args)
results = await asyncio.to_thread(agent.vmem.search, agent.default_tid, q, n_results=5)
for r in results:
print(f" • {r['text'][:200]}", flush=True)
elif cmd == "/tasks":
for t in agent.db.get_pending_tasks(agent.default_tid):
print(f" [{t['id']}] {t['title']} (P{t['priority']})")
elif cmd == "/dashboard":
stats = await asyncio.to_thread(agent.db.get_dashboard_stats, agent.default_tid)
tech_stats = {k: v for k, v in stats.items() if "revenue" not in k and "client" not in k}
print(json.dumps(tech_stats, indent=2), flush=True)
elif cmd == "/ui":
if not args:
query = await asyncio.to_thread(input, "What kind of UI do you want me to generate? ")
else:
query = " ".join(args)
if query:
# Pass stats context for data viz
stats = await asyncio.to_thread(agent.db.get_dashboard_stats, agent.default_tid)
await asyncio.to_thread(agent.gen_ui.generate_dashboard, query, data=stats)
elif cmd == "/provider":
await asyncio.to_thread(self._change_provider, args[0] if args else None)
elif cmd == "/model":
if not args:
cur = CONFIG.get_active_model()
print(f"🤖 Current Model: {cur}")
print("Usage: /model <name> | Example: /model phi3-mini")
else:
new_model = args[0]
if CONFIG.api_provider == "ollama":
CONFIG.ollama.model = new_model
elif CONFIG.api_provider == "openai":
CONFIG.openai.model = new_model
elif CONFIG.api_provider == "anthropic":
CONFIG.anthropic.model = new_model
agent.llm.model = new_model
print(f"✅ Model switched to: {new_model}")
agent.log_ui(f"Switched to model {new_model}")
elif cmd == "/models":
info = agent.llm.check_connection()
if info.get("connected") and "models" in info:
print("+----------------------------------------+")
print("| AVAILABLE OLLAMA MODELS |")
print("+----------------------------------------+")
for m in info["models"]:
star = "*" if m == agent.llm.model else " "
print(f"| {star} {m:<36} |")
print("+----------------------------------------+")
print(" (*) Current active model")
else:
print(f"❌ Could not retrieve models: {info.get('error', 'Unknown error')}")
elif cmd == "/lite":
if args and args[0].lower() in ["on", "true", "1"]:
CONFIG.lite_mode = True
elif args and args[0].lower() in ["off", "false", "0"]:
CONFIG.lite_mode = False
else:
CONFIG.lite_mode = not CONFIG.lite_mode
print(f"🚀 Performance (Lite) Mode: {'ON' if CONFIG.lite_mode else 'OFF'}")
elif cmd == "/setkey":
await asyncio.to_thread(self._set_api_key, args[0] if args else None, args[1] if len(args) > 1 else None)
elif cmd in ("/help", "/?"):
self._print_help()
elif cmd == "/learn":
await asyncio.to_thread(self._cmd_learn_text)
elif cmd == "/learnurl":
await asyncio.to_thread(self._cmd_learn_url)
elif cmd == "/learnfile":
await asyncio.to_thread(self._cmd_learn_file)
elif cmd == "/learndir":
await asyncio.to_thread(self._cmd_learn_dir)
elif cmd == "/learnskill":
await asyncio.to_thread(self._cmd_learn_skill)
elif cmd == "/learnpref":
await asyncio.to_thread(self._cmd_learn_pref)
elif cmd == "/teach":
await asyncio.to_thread(self._cmd_teach)
elif cmd == "/knowledge":
await asyncio.to_thread(self._cmd_knowledge)
elif cmd == "/correct":
await asyncio.to_thread(self._cmd_correct)
elif cmd == "/rate":
await asyncio.to_thread(self._cmd_rate)
elif cmd == "/introspect":
print(agent.mind.introspect())
elif cmd == "/mood":
print(f" 🧠 Mood: {agent.mind.get_mood_label()} ({agent.mind.emotions['mood']:.2f})")
print(f" ⚡ Energy: {agent.mind.emotions['energy']:.2f}")
print(f" 🔎 Curiosity: {agent.mind.emotions['curiosity']:.2f}")
elif cmd == "/goals":
await asyncio.to_thread(self._cmd_goals, args)
elif cmd == "/godmode":
self._cmd_godmode()
elif cmd == "/reflect":
await asyncio.to_thread(self._cmd_reflect)
elif cmd == "/research":
await asyncio.to_thread(self._cmd_research)
elif cmd == "/buildtool":
await asyncio.to_thread(self._cmd_buildtool)
elif cmd == "/runtool":
await asyncio.to_thread(self._cmd_runtool)
elif cmd == "/see":
await asyncio.to_thread(self._cmd_see)
elif cmd == "/screenshot":
await asyncio.to_thread(self._cmd_screenshot)
elif cmd == "/click":
await asyncio.to_thread(self._cmd_click)
elif cmd == "/reality":
await asyncio.to_thread(self._cmd_reality, args)
elif cmd == "/ethics":
await asyncio.to_thread(self._cmd_ethics, args)
elif cmd == "/memory":
self._cmd_memory(args)
elif cmd == "/avatar":
await asyncio.to_thread(self._cmd_avatar, args)
elif cmd == "/swarm":
await asyncio.to_thread(self._cmd_swarm)
elif cmd == "/delegate":
await asyncio.to_thread(self._cmd_delegate)
elif cmd == "/mission":
target = args[0].lower() if args else "create"
if target == "create":
await asyncio.to_thread(self._cmd_mission)
elif target == "status":
await asyncio.to_thread(self._cmd_missions)
else:
print("Usage: /mission create", flush=True)
elif cmd == "/missions":
await asyncio.to_thread(self._cmd_missions)
elif cmd == "/track":
agent.autonomous_missions = not agent.autonomous_missions
print(f" Autonomous mission tracking: {'ON' if agent.autonomous_missions else 'OFF'}", flush=True)
elif cmd == "/evolve":
await self._cmd_evolve()
elif cmd == "/hive":
if not args:
print("Usage: /hive share <subj> <pred> <obj> OR /hive query <topic>", flush=True)
return
subcmd = args[0].lower()
if subcmd == "share" and len(args) >= 4:
await asyncio.to_thread(agent.hive.share_fact, args[1], args[2], " ".join(args[3:]))
print(f"✅ Fact shared to hive.", flush=True)
elif subcmd == "query" and len(args) >= 2:
q = " ".join(args[1:])
res = await asyncio.to_thread(agent.hive.consult, q)
print(f"Hive Knowledge about '{q}':", flush=True)
for r in res:
print(f" • {r['subject']} {r['predicate']} {r['object']} (Conf: {r['confidence']:.2f})", flush=True)
else:
print("Invalid /hive usage.", flush=True)
elif cmd == "/security":
sub = args[0].lower() if args else "status"
if sub == "status":
s = await asyncio.to_thread(agent.security.get_status)
print(f"🛡️ Security Status: {json.dumps(s, indent=2)}", flush=True)
elif sub == "integrity":
print("Verifying Code Integrity...", flush=True)
anomalies = await asyncio.to_thread(agent.ledger.verify_integrity)
if not anomalies:
print("✅ All core files matched Code Ledger hashes.", flush=True)
else:
print(f"❌ TAMPERING DETECTED: {anomalies}", flush=True)
elif sub == "update":
desc = " ".join(args[1:]) if len(args) > 1 else await asyncio.to_thread(input, "Reason for update: ")
await asyncio.to_thread(agent.ledger.register_update, desc)
print("✅ Ledger updated with new file hashes.", flush=True)
else:
print("Usage: /security <status|integrity|update>", flush=True)
elif cmd == "/replicate":
sub = args[0].lower() if args else "local"
if sub == "local":
print("🧬 Initiating Self-Replication Sequence...", flush=True)
res = await asyncio.to_thread(agent.replicator.replicate_local, agent.session_id, agent.generation)
if res['success']:
print(f"✅ Child Spawned: {res['child_id']} (Gen {res['generation']})", flush=True)
print(f" Location: {res['path']}", flush=True)
else:
print(f"❌ Replication Failed: {res['error']}", flush=True)
else:
print("Usage: /replicate local", flush=True)
elif cmd == "/colony":
census = await asyncio.to_thread(agent.db.get_colony_census)
print(f"🌍 Colony Census ({len(census)} agents):", flush=True)
for c in census:
print(f" [{c['generation']}] {c['id']} -> {c['location']}", flush=True)
elif cmd == "/singularity":
sub = args[0].lower() if args else "start"
if sub == "start":
asyncio.create_task(agent.evolution.start_loop())
elif sub == "stop":
agent.evolution.stop_loop()
else:
print("Usage: /singularity <start|stop>")
elif cmd == "/hologram":
self._cmd_hologram(args)
elif cmd == "/resources":
print(agent.resources.get_status_report())
elif cmd == "/connect":
if not args:
print("Usage: /connect <google|github>")
else:
service = args[0].lower()
url = agent.oauth.get_auth_url(service)
if url:
print(f"🔗 Please authorize at: {url}")
else:
print(f"❌ Unknown service: {service}")
elif cmd == "/worldsim":
await self._cmd_worldsim(args)
elif cmd == "/dao":
await asyncio.to_thread(self._cmd_dao, args)
elif cmd == "/wallet":
await asyncio.to_thread(self._cmd_wallet, args)
# ── Phase 15 Commands ──
elif cmd == "/bounty":
await asyncio.to_thread(self._cmd_bounty, args)
elif cmd == "/social":
await self._cmd_social(args)
elif cmd == "/godmode2":
await asyncio.to_thread(self._cmd_godmode2, args)
elif cmd == "/dream":
await asyncio.to_thread(self._cmd_dream, args)
elif cmd == "/voxelworld":
await self._cmd_voxelworld(args)
# ══ Phase 16 Commands ══
elif cmd == "/debate":
await self._cmd_debate(args)
elif cmd == "/why":
await asyncio.to_thread(self._cmd_why, args)
elif cmd == "/profile":
await asyncio.to_thread(self._cmd_profile, args)
elif cmd == "/mode":
await asyncio.to_thread(self._cmd_mode, args)
elif cmd == "/oracle":
await self._cmd_oracle(args)
elif cmd == "/crypto":
await self._cmd_crypto(args)
elif cmd == "/saas":
await self._cmd_saas(args)
elif cmd == "/youtube":
await self._cmd_youtube(args)
elif cmd == "/redteam":
await self._cmd_redteam(args)
elif cmd == "/history":
await asyncio.to_thread(self._cmd_history, args)
elif cmd == "/news":
await self._cmd_news(args)
elif cmd == "/call":
await self._cmd_call(args)
elif cmd == "/home":
await self._cmd_home(args)
# ══ Phase 17 Commands ══
elif cmd == "/autogpt":
await self._cmd_autogpt(args)
elif cmd == "/rag":
await asyncio.to_thread(self._cmd_rag, args)
elif cmd == "/summarize":
await asyncio.to_thread(self._cmd_summarize, args)
elif cmd == "/stocks":
await self._cmd_stocks(args)
elif cmd == "/emailcampaign":
await asyncio.to_thread(self._cmd_emailcampaign, args)
elif cmd == "/codereview":
await asyncio.to_thread(self._cmd_codereview, args)
elif cmd == "/bughunt":
await asyncio.to_thread(self._cmd_bughunt, args)
elif cmd == "/bugbounty":
await asyncio.to_thread(self._cmd_bugbounty, args)
elif cmd == "/autotest":
await asyncio.to_thread(self._cmd_autotest, args)
elif cmd == "/browse":
await self._cmd_browse(args)
elif cmd == "/email":
await asyncio.to_thread(self._cmd_email, args)
elif cmd == "/calendar":
await asyncio.to_thread(self._cmd_calendar, args)
elif cmd == "/voiceclone":
await asyncio.to_thread(self._cmd_voiceclone, args)
elif cmd == "/companion":
await asyncio.to_thread(self._cmd_companion, args)
elif cmd == "/briefing":
await self._cmd_briefing(args)
# ══ Phase 18 Commands ══
# --- AI Productivity Suite ---
elif cmd == "/focus":
await asyncio.to_thread(self._cmd_focus, args)
elif cmd == "/habit":
await asyncio.to_thread(self._cmd_habit, args)
elif cmd == "/meeting":
await asyncio.to_thread(self._cmd_meeting, args)
elif cmd == "/note":
await asyncio.to_thread(self._cmd_note, args)
# --- Money-Making Features ---
elif cmd == "/invoice":
await asyncio.to_thread(self._cmd_invoice, args)
elif cmd == "/pricing":
await asyncio.to_thread(self._cmd_pricing, args)
elif cmd == "/leads":
await asyncio.to_thread(self._cmd_leads, args)
elif cmd == "/affiliate":
await asyncio.to_thread(self._cmd_affiliate, args)
# --- AI Power Features ---
elif cmd == "/panel":
await self._cmd_panel(args)
elif cmd == "/optimize":
await asyncio.to_thread(self._cmd_optimize, args)
elif cmd == "/finetune":
await asyncio.to_thread(self._cmd_finetune, args)
elif cmd == "/mindmap":
await asyncio.to_thread(self._cmd_mindmap, args)
elif cmd == "/createpersona":
await asyncio.to_thread(self._cmd_createpersona, args)
elif cmd == "/persona":
await asyncio.to_thread(self._cmd_persona, args)
# --- Real-World Integrations ---
elif cmd == "/github":
await asyncio.to_thread(self._cmd_github, args)
elif cmd == "/notion":
await asyncio.to_thread(self._cmd_notion, args)
elif cmd == "/discord":
await asyncio.to_thread(self._cmd_discord, args)
elif cmd == "/telegram":
await asyncio.to_thread(self._cmd_telegram, args)
elif cmd == "/webhook":
await asyncio.to_thread(self._cmd_webhook, args)
# --- Fun / Immersive ---
elif cmd == "/rpg":
await asyncio.to_thread(self._cmd_rpg, args)
elif cmd == "/therapy":
await asyncio.to_thread(self._cmd_therapy, args)
elif cmd == "/story":
await asyncio.to_thread(self._cmd_story, args)
elif cmd == "/face":
await asyncio.to_thread(self._cmd_face, args)
elif cmd == "/compose":
await asyncio.to_thread(self._cmd_compose, args)
# ══ PRACTICAL AGI — NEW COMMANDS ══
elif cmd == "/verify":
await asyncio.to_thread(self._cmd_verify, args)
elif cmd == "/agi":
await asyncio.to_thread(self._cmd_agi, args)
# ══ AGI LIMITATION OVERRIDES ══
elif cmd == "/causal":
await asyncio.to_thread(self._cmd_causal, args)
elif cmd == "/transfer":
await asyncio.to_thread(self._cmd_transfer, args)
elif cmd == "/world":
await asyncio.to_thread(self._cmd_world, args)
elif cmd == "/novelty":
await asyncio.to_thread(self._cmd_novelty, args)
elif cmd == "/context":
await asyncio.to_thread(self._cmd_context, args)
# ══ AGI LIMITATION OVERRIDES 2.0 ══
elif cmd == "/grounded":
await asyncio.to_thread(self._cmd_grounded, args)
elif cmd == "/curiosity":
await asyncio.to_thread(self._cmd_curiosity, args)
elif cmd == "/ground":
await asyncio.to_thread(self._cmd_ground, args)
elif cmd == "/architect":
await asyncio.to_thread(self._cmd_architect, args)
elif cmd == "/motivation":
await asyncio.to_thread(self._cmd_motivation, args)
else:
print(f"❓ Unknown command: {cmd}. Type /help for assistance.")
# ==================================================
# PRACTICAL AGI COMMANDS
# ==================================================
def _cmd_verify(self, args):
"""
/verify code — Verify code in clipboard/paste
/verify tool — Test a tool with params
/verify stats — Show VerificationEngine statistics
"""
agent = self.agent
verifier = getattr(agent, "verifier", None)
if verifier is None:
print("❌ VerificationEngine not loaded. Check imports.")
return
sub = args[0].lower() if args else "stats"
if sub == "stats":
stats = verifier.get_stats()
log = verifier.get_recent_log(5)
print("\n╔══════════════════════════════════════════╗")
print("║ VERIFICATION ENGINE STATS ║")
print("╠══════════════════════════════════════════╣")
print(f"║ Total Checks : {stats['total_checks']:<26}║")
print(f"║ Passed : {stats['passed']:<26}║")
print(f"║ Failed : {stats['failed']:<26}║")
print(f"║ Auto-Fixed : {stats['auto_corrected']:<26}║")
print(f"║ Pass Rate : {stats['pass_rate']:<26}║")
print("╚══════════════════════════════════════════╝")
if log:
print("\n Recent Verifications:")
for entry in log:
icon = "✅" if entry["passed"] else "❌"
print(f" {icon} [{entry['tool']}] conf={entry['confidence']:.2f} — {entry['reason'][:60]}")
elif sub == "code":
print("Paste your Python code (empty line to finish):")
lines = []
try:
while True:
line = input()
if not line:
break
lines.append(line)
except EOFError:
pass
code = "\n".join(lines)
if code.strip():
print("\n⚡ Verifying code...")
vr = verifier.verify_code(code, language="python")
icon = "✅" if vr.passed else "❌"
print(f"\n{icon} {vr}")
else:
print("No code provided.")
elif sub == "tool":
tool_name = input("Tool name: ").strip()
print("Params JSON (or Enter for {}): ", end="")
params_str = input().strip()
try:
import json
params = json.loads(params_str) if params_str else {}
except Exception:
params = {}
intent = input("Intent/goal (optional): ").strip()
if hasattr(agent, "tool_registry"):
result = agent.tool_registry.execute(tool_name, params)
print(f"Tool result: {result}")
vr = verifier.verify_tool_result(tool_name, params, result, intent)
icon = "✅" if vr.passed else "❌"
print(f"\n{icon} Verification: {vr}")
else:
print("❌ No tool_registry on agent.")
else:
print("Usage: /verify <stats|code|tool>")
def _cmd_agi(self, args):
"""
/agi goal — Execute a custom goal in AGI decomposition mode
/agi list — List sub-tasks for recent goals
/agi status — Show AGI engine status
"""
agent = self.agent
sub = args[0].lower() if args else "status"
if sub == "status":
ge = agent.goal_engine
v = agent.verifier
active = len(ge.active_goals)
completed = ge._goals_completed_count
generated = ge._goals_generated_count
v_stats = v.get_stats() if v else {"total_checks": 0, "pass_rate": "N/A"}
print("\n╔══════════════════════════════════════════╗")
print("║ PRACTICAL AGI ENGINE STATUS ║")
print("╠══════════════════════════════════════════╣")
print(f"║ Active Goals : {active:<23}║")
print(f"║ Goals Generated : {generated:<23}║")
print(f"║ Goals Completed : {completed:<23}║")
print(f"║ Verifier Checks : {v_stats['total_checks']:<23}║")
print(f"║ Verifier Rate : {v_stats['pass_rate']:<23}║")
print(f"║ Decomposition : ENABLED ║")
print(f"║ Confidence Gate : 0.65 threshold ║")
print("╚══════════════════════════════════════════╝")
elif sub == "goal":
title = input("Goal title: ").strip()
objective = input("Objective/details: ").strip()
if not title:
print("No title provided.")
return
goal = {
"id": None, # Will be set after DB insert
"title": title,
"objective": objective or title,
"category": "custom",
"priority": 10,
"status": "active",
}
# Insert into DB
try:
cursor = agent.db.conn.execute(
"""INSERT INTO autonomous_goals
(title, objective, category, priority, status, created_at)
VALUES (?, ?, ?, ?, 'active', ?)""",
(title, objective, "custom", 10, __import__("datetime").datetime.now().isoformat())
)
agent.db.conn.commit()
goal["id"] = cursor.lastrowid
except Exception as e:
print(f"⚠️ Could not persist goal: {e}")
print(f"\n⚡ Executing goal in AGI decomposition mode...")
result = agent.goal_engine.execute_with_decomposition(goal, agent, agent.default_tid)
print(f"\n{'✅' if result['status']=='completed' else '❌'} Result:")
print(f" Status: {result['status'].upper()}")
print(f" Sub-tasks: {result['subtasks_completed']}/{result['subtasks_total']}")
print(f" Summary: {result['summary'][:200]}")
elif sub == "list":
try:
rows = agent.db.conn.execute(
"""SELECT s.*, g.title as goal_title
FROM autonomous_subtasks s
JOIN autonomous_goals g ON s.goal_id=g.id
ORDER BY s.id DESC LIMIT 20"""
).fetchall()
if not rows:
print("No sub-tasks found yet. Run /agi goal to execute a goal.")
return
print("\n Recent Sub-tasks:")
for r in rows:
r = dict(r)
icon = {"completed": "✅", "failed": "❌", "running": "🔄", "pending": "⏳"}.get(r["status"], "❓")
print(f" {icon} [{r['goal_title'][:20]}] Step {r['step']}: {r['action'][:60]}")
except Exception as e:
print(f"❌ Could not query sub-tasks: {e}")
else:
print("Usage: /agi <status|goal|list>")
# ══════════════════════════════════════════════════════════════════════
# AGI LIMITATION OVERRIDE COMMANDS
# ══════════════════════════════════════════════════════════════════════
def _cmd_causal(self, args):
"""
/causal infer <effect> — Trace root causes of an observed effect
/causal predict <action> — Predict consequences of an action
/causal link <c> > <e> — Manually assert a causal link
/causal extract <text> — Auto-extract causal links from text
/causal stats — Show causal graph statistics
/causal counterfactual <c> — What-if analysis
"""
agent = self.agent
causal = getattr(agent, "causal", None)
if not causal:
print("❌ CausalEngine not loaded.")
return
sub = args[0].lower() if args else "stats"
if sub == "stats":
stats = causal.get_graph_stats()
print("\n╔══════════════════════════════════════╗")
print("║ CAUSAL GRAPH STATS ║")
print("╠══════════════════════════════════════╣")
print(f"║ Nodes (events/states) : {stats['total_nodes']:<14}║")
print(f"║ Edges (causal links) : {stats['total_edges']:<14}║")
print(f"║ Root causes : {stats['root_causes']:<14}║")
print(f"║ Terminal effects : {stats['terminal_effects']:<14}║")
print("╚══════════════════════════════════════╝")
if stats.get("most_connected"):
print("\n Most Connected Nodes:")
for node in stats["most_connected"]:
print(f" • {node['node']} ({node['connections']} connections)")
elif sub == "infer":
effect = " ".join(args[1:])
if not effect:
effect = input("Observed effect: ").strip()
print(f"\n⚡ Tracing root causes of: '{effect}'...")
result = causal.infer_cause(effect)
print(f"\n Observed Effect: {result['observed_effect']}")
root = result.get("root_causes", [])
if root:
print(f"\n Root Causes:")
for c in root:
print(f" ⚡ {c['cause']} (prob={c['probability']:.2f})")
all_causes = result.get("all_causes", [])
if all_causes:
print(f"\n Full Causal Chain ({len(all_causes)} nodes):")
for c in all_causes[:8]:
marker = "🔴" if c.get("is_root_cause") else "🔗"
print(f" {marker} {c['cause']} (depth={c['depth']}, p={c['probability']:.2f})")
elif sub == "predict":
action = " ".join(args[1:])
if not action:
action = input("Action to predict: ").strip()
print(f"\n⚡ Predicting consequences of: '{action}'...")
result = causal.predict_effect(action)
effects = result.get("predicted_effects", [])
if effects:
print(f"\n Predicted Effects ({len(effects)}):")
for e in effects:
print(f" → [{e['depth']}] {e['effect']} (p={e['probability']:.2f})")
else:
print(" No effects found — trying LLM inference...")
elif sub == "link":
# Format: /causal link <cause> > <effect>
full_text = " ".join(args[1:])
if ">" in full_text:
parts = full_text.split(">", 1)
cause, effect = parts[0].strip(), parts[1].strip()
else:
cause = input("Cause: ").strip()
effect = input("Effect: ").strip()
strength_str = input("Strength (0.0-1.0, Enter=0.8): ").strip()
strength = float(strength_str) if strength_str else 0.8
mechanism = input("Mechanism (optional): ").strip()
result = causal.add_causal_link(cause, effect, strength, mechanism)
print(f"✅ Causal link {result['status']}: {cause} → {effect} (strength={strength})")
elif sub == "extract":
text = " ".join(args[1:])
if not text:
print("Paste text (empty line to finish):")
lines = []
try:
while True:
line = input()
if not line:
break
lines.append(line)
except EOFError:
pass
text = "\n".join(lines)
found = causal.extract_from_text(text)
print(f"\n Discovered {len(found)} causal relationships:")
for link in found:
print(f" ⚡ {link['cause']} → {link['effect']} (strength={link['strength']:.2f})")
elif sub == "counterfactual":
cause = " ".join(args[1:])
if not cause:
cause = input("Counterfactual cause (what if this hadn't happened): ").strip()
question = input("Your question (optional): ").strip()
result = causal.counterfactual(cause, question)
prevented = result.get("effects_prevented", [])
still_happen = result.get("effects_still_occurring", [])
print(f"\n If '{cause}' had NOT happened:")
if prevented:
print(f"\n Effects that would NOT occur ({len(prevented)}):")
for e in prevented:
print(f" ✗ {e['effect']}")
if still_happen:
print(f"\n Effects that would STILL occur ({len(still_happen)}):")
for e in still_happen:
print(f" → {e['effect']} (via: {', '.join(e.get('alternative_causes', [])[:2])})")
if result.get("llm_analysis"):
print(f"\n Analysis:\n{result['llm_analysis']}")
else:
print("Usage: /causal <stats|infer|predict|link|extract|counterfactual>")
def _cmd_transfer(self, args):
"""
/transfer learn <domain> — Learn a new domain from examples
/transfer solve <domain> — Solve a problem in a learned domain
/transfer analogy <A> <B> — Apply domain-A knowledge to domain-B problem
/transfer bootstrap <new> <src> — Bootstrap new domain from existing one
/transfer list — List all learned domains
"""
agent = self.agent
transfer = getattr(agent, "transfer", None)
if not transfer:
print("❌ TransferEngine not loaded.")
return
sub = args[0].lower() if args else "list"
if sub == "list":
domains = transfer.list_domains()
if not domains:
print(" No domains learned yet. Use /transfer learn <domain_name>")
return
print(f"\n Learned Domains ({len(domains)}):")
for d in domains:
bar = "█" * int(d["confidence"] * 10)
print(f" [{bar:<10}] {d['domain']:25s} "
f"({d['examples']} examples, conf={d['confidence']:.2f})")
if d.get("concepts"):
print(f" Concepts: {', '.join(d['concepts'])}")
elif sub == "learn":
domain_name = args[1] if len(args) > 1 else input("Domain name: ").strip()
description = input("Domain description (optional): ").strip()
print(f"Enter examples. Format: INPUT | OUTPUT (empty line to finish):")
examples = []
try:
while True:
line = input().strip()
if not line:
break
if "|" in line:
parts = line.split("|", 1)
examples.append({"input": parts[0].strip(), "output": parts[1].strip()})
else:
print(" (Format: input | output)")
except EOFError:
pass
if not examples:
print("No examples provided.")
return
print(f"\n⚡ Learning domain '{domain_name}' from {len(examples)} examples...")
result = transfer.learn_domain(domain_name, examples, description)
print(f"✅ Domain learned!")
print(f" Examples: {result['examples_added']}, Confidence: {result['confidence']:.2f}")
if result.get("core_concepts"):
print(f" Concepts: {', '.join(result['core_concepts'])}")
elif sub == "solve":
domain_name = args[1] if len(args) > 1 else input("Domain: ").strip()
problem = " ".join(args[2:]) if len(args) > 2 else input("Problem: ").strip()
print(f"\n⚡ Solving in domain '{domain_name}'...")
result = transfer.solve_in_domain(domain_name, problem)
if "error" in result:
print(f"❌ {result['error']}")
return
print(f"\n Solution (confidence={result['confidence']:.2f}, "
f"using {result['examples_used']} examples):")
print(f"\n{result['solution']}")
elif sub == "analogy":
src = args[1] if len(args) > 1 else input("Source domain: ").strip()
tgt = args[2] if len(args) > 2 else input("Target domain: ").strip()
problem = " ".join(args[3:]) if len(args) > 3 else input("Problem to solve: ").strip()
print(f"\n⚡ Analogical transfer: {src} → {tgt}...")
result = transfer.transfer_to(src, tgt, problem)
if "error" in result:
print(f"❌ {result['error']}")
return
print(f"\n{result['analogical_solution']}")
elif sub == "bootstrap":
new_dom = args[1] if len(args) > 1 else input("New domain name: ").strip()
src_dom = args[2] if len(args) > 2 else input("Source domain to inherit from: ").strip()
result = transfer.bootstrap_from(new_dom, src_dom)
if "error" in result:
print(f"❌ {result['error']}")
return
print(f"✅ '{new_dom}' bootstrapped from '{src_dom}'")
print(f" Inherited {result['inherited_concepts']} concept seeds")
print(f" {result['note']}")
else:
print("Usage: /transfer <list|learn|solve|analogy|bootstrap>")
def _cmd_world(self, args):
"""
/world observe <event> — Observe an event and update world model
/world simulate <action> — Mental simulation of consequences
/world query <entity> — Query what agent knows about an entity
/world link <A> <rel> <B> — Assert a world relationship
/world rule <description> — Add a world axiom
/world summary — Show world model overview
"""
agent = self.agent
world = getattr(agent, "world", None)
if not world:
print("❌ WorldModelEngine not loaded.")
return
sub = args[0].lower() if args else "summary"
if sub == "summary":
summary = world.get_world_summary()
print("\n╔══════════════════════════════════════╗")
print("║ WORLD MODEL STATE ║")
print("╠══════════════════════════════════════╣")
print(f"║ Entities tracked : {summary['total_entities']:<19}║")
print(f"║ World rules : {summary['total_rules']:<19}║")
print(f"║ Events observed : {summary['total_events_observed']:<19}║")
print("╚══════════════════════════════════════╝")
if summary.get("entity_types"):
print(f"\n Entity types: { {k:v for k,v in summary['entity_types'].items()} }")
if summary.get("recent_events"):
print(f"\n Recent events:")
for ev in summary["recent_events"]:
print(f" • {ev[:80]}")
if summary.get("world_context_preview"):
print(f"\n World context:\n{summary['world_context_preview']}")
elif sub == "observe":
event = " ".join(args[1:])
if not event:
event = input("Describe the event: ").strip()
print(f"\n⚡ Observing: '{event[:80]}'...")
result = world.observe(event)
print(f"✅ World model updated: {result['entities_updated']} entities, "
f"{result['state_changes']} state changes")
print(f" Total tracked: {result['total_entities']} entities")
elif sub == "simulate":
action = " ".join(args[1:])
if not action:
action = input("Action to simulate: ").strip()
steps_str = input("Simulation steps (Enter=3): ").strip()
steps = int(steps_str) if steps_str.isdigit() else 3
print(f"\n⚡ Running mental simulation of: '{action}' ({steps} steps)...")
result = world.simulate(action, steps)
print(f"\n{result['simulation_result']}")
elif sub == "query":
entity = " ".join(args[1:])
if not entity:
entity = input("Entity name: ").strip()
result = world.query_state(entity)
if not result.get("known"):
print(f" '{entity}' is not in the world model yet. Use /world observe to add it.")
return
print(f"\n Entity: {result['entity']} ({result['type']})")
if result.get("properties"):
print(f" Properties:")
for k, v in result["properties"].items():
print(f" {k}: {v}")
if result.get("relations"):
print(f" Relations:")
for r in result["relations"][:5]:
print(f" --[{r['predicate']}]--> {r['target_id']}")
print(f" Last updated: {result['last_updated'][:16]}")
elif sub == "link":
entity_a = input("Entity A: ").strip()
predicate = input("Relation (e.g. 'owns', 'is_part_of'): ").strip()
entity_b = input("Entity B: ").strip()
world.link_entities(entity_a, predicate, entity_b)
print(f"✅ {entity_a} --[{predicate}]--> {entity_b}")
elif sub == "rule":
desc = " ".join(args[1:])
if not desc:
desc = input("World rule description: ").strip()
cat = input("Category (physics/social/economic/logical/general): ").strip() or "general"
conf_str = input("Confidence (0.0-1.0, Enter=0.9): ").strip()
conf = float(conf_str) if conf_str else 0.9
result = world.add_rule(desc, cat, conf)
print(f"✅ Rule added: [{result['category']}] {result['description'][:60]}")
else:
print("Usage: /world <summary|observe|simulate|query|link|rule>")
def _cmd_novelty(self, args):
"""
/novelty combine <A>:<domain_a> + <B>:<domain_b> — Cross-domain concept creation
/novelty hypothesis <observation> — Generate competing hypotheses
/novelty mutate <concept> [operator] — Mutate an existing concept
/novelty score <idea> — Score how novel an idea is
/novelty brainstorm <problem> — Full ideation pipeline
/novelty list [min_score] — List generated concepts
"""
agent = self.agent
novelty = getattr(agent, "novelty", None)
if not novelty:
print("❌ NoveltyEngine not loaded.")
return
sub = args[0].lower() if args else "list"
if sub == "list":
min_score = float(args[1]) if len(args) > 1 else 0.0
concepts = novelty.list_concepts(min_novelty=min_score)
if not concepts:
print(" No concepts generated yet. Use /novelty combine or /novelty brainstorm")
return
print(f"\n Generated Concepts ({len(concepts)}):")
for c in concepts:
bar = "★" * int(c["novelty_score"] * 10)
print(f" [{bar:<10}] {c['name'][:50]} (score={c['novelty_score']:.2f})")
print(f" Domains: {' + '.join(c['domains'])} | {c['created']}")
elif sub == "combine":
# Parse: /novelty combine concept_a:domain_a + concept_b:domain_b
# Or just ask interactively
if len(args) > 1:
combined = " ".join(args[1:])
parts = combined.split("+")
if len(parts) == 2:
part_a = parts[0].strip()
part_b = parts[1].strip()
# Check for domain:concept format
if ":" in part_a:
domain_a, concept_a = part_a.split(":", 1)
else:
domain_a, concept_a = "domain_a", part_a
if ":" in part_b:
domain_b, concept_b = part_b.split(":", 1)
else:
domain_b, concept_b = "domain_b", part_b
else:
concept_a = parts[0].strip()
domain_a = "general"
concept_b = input("Second concept: ").strip()
domain_b = input("Second domain: ").strip() or "general"
else:
concept_a = input("First concept: ").strip()
domain_a = input("First domain: ").strip() or "general"
concept_b = input("Second concept: ").strip()
domain_b = input("Second domain: ").strip() or "general"
print(f"\n⚡ Synthesizing: [{domain_a}] {concept_a} + [{domain_b}] {concept_b}...")
result = novelty.combine(domain_a, concept_a, domain_b, concept_b)
print(f"\n🌟 NEW CONCEPT: {result['name']}")
print(f" Novelty Score: {result['novelty_score']:.2f}/1.0")
print(f"\n Description:\n {result['description']}")
if result.get("applications"):
print(f"\n Applications:")
for app in result["applications"]:
print(f" • {app}")
if result.get("testable_predictions"):
print(f"\n Testable Prediction:")
print(f" ⚗️ {result['testable_predictions'][0]}")
elif sub == "hypothesis":
observation = " ".join(args[1:])
if not observation:
observation = input("Observation to explain: ").strip()
domain = input("Domain (optional): ").strip() or "general"
print(f"\n⚡ Generating hypotheses for: '{observation[:60]}'...")
result = novelty.generate_hypothesis(observation, domain)
print(f"\n{result['hypotheses']}")