-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
2098 lines (2047 loc) · 163 KB
/
Copy pathagent.py
File metadata and controls
2098 lines (2047 loc) · 163 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
"""
Interactive Autonomous Multi-Agent CLI Shell (Claude CLI / Gemini CLI Style)
Features Electronics Schematic Parsers, Base64 Vision Reader, and Sliding Window Memory.
"""
import sys
import os
import time
import json
import argparse
from typing import Dict, Any, List, Optional
# Import core tracer runner and modules
# Import core tracer runner and sub-packages
from core.engine.runner import run_agent_task, trace_agent, log_agent_activity
from core.infra.memory import SlidingWindowMemory
from core.infra.cache import get_cache_metrics
from core.hardware import (
check_pinout_conflicts, simulate_rc_circuit, calculate_trace_impedance,
audit_pcb_drc_rules, analyze_thermal_dissipation, calculate_rf_antenna_dimensions,
audit_emc_fcc_compliance, auto_route_pcb_netlist, recommend_mcu_for_project,
calculate_pcb_stackup, analyze_3d_component_clearance, generate_kicad_dru_file,
analyze_bom_cost_sensitivity, crosscheck_footprint_pinout, calculate_length_matching,
generate_hierarchical_subsheets, calculate_solder_stencil_specs, run_genetic_hardware_optimization
)
from core.software import (
generate_unity_c_test, generate_lcov_coverage_report, audit_firmware_security,
run_hil_hardware_test, auto_heal_multidisciplinary, heal_python, heal_openscad,
heal_kicad, heal_json, audit_bootloader_config, analyze_task_stack_requirements,
profile_firmware_power, calculate_flash_partitions, generate_ota_update_manifest,
analyze_crash_dump, estimate_edge_ai_memory, generate_docker_k8s_manifests,
generate_uml_architecture_diagram, generate_db_schema_and_migrations, generate_devops_terraform_config
)
from core.production import (
generate_openscad_enclosure, calculate_snap_fit_joint, calculate_flexure_hinge,
calculate_gasket_groove_dimensions, calculate_screw_boss_dimensions,
run_mechanical_fea_simulation, calculate_cable_gland_dimensions, calculate_enclosure_ventilation,
calculate_battery_lifespan, calculate_wire_harness, optimize_bom_cost,
generate_project_gantt_chart, generate_project_markdown_report
)
from core.computer import (
generate_web_api_architecture, generate_microservice_proto, generate_react_component,
audit_code_complexity, design_nosql_model, generate_auth_flow, generate_nginx_config,
design_rate_limiter, generate_websocket_handler, generate_mobile_app_scaffold, configure_app_signing
)
from core.infra.rag import index_file, index_directory, search as rag_search, get_index_stats
from core.infra.longmem import remember, recall, forget, get_memory_stats, recall_for_prompt
from core.engine.pipeline import AgentPipeline, embedded_dev_pipeline
from core.infra.notify import notify_all
from core.infra.git_ops import git_status, git_diff, git_log, git_auto_commit
from core.infra.plugins import list_plugins, execute_plugin, load_plugins_from_dir
from core.infra.self_improve import analyze_and_refine_agent_prompt
from core.infra.cli_ui import (
print_cli_banner, print_agent_status_header, render_thinking_box,
render_extensions_ui, render_docs_ui, render_parallel_execution
)
from core.infra.consensus import run_consensus
from core.infra.github_pr import create_feature_branch_and_pr
from core.infra.tui_dashboard import render_tui_dashboard
from core.infra.research import search_arxiv_papers, generate_patent_prior_art_query
from core.infra.mcp_client import MCPExecutionMode, dispatch_task
from core.infra.profile import load_user_profile, build_personalized_system_prompt
from core.engine.arena import run_agent_arena
from core.engine.autonomous_agent import execute_autonomous_goal
from core.engine.layered_architecture import run_layered_pipeline
from core.engine.agent_tree_sim import run_agent_tree_simulation, print_static_tree_topology
from core.infra.worker_queue import global_worker_queue
from core.infra.rate_limiter import global_rate_limiter
from core.infra.checkpoint import create_system_checkpoint, restore_system_checkpoint
from core.infra.service import ensure_services_running
from core.infra.voice_agent import process_voice_command
from core.infra.knowledge_graph import global_knowledge_graph
from core.infra.self_reflection import run_with_self_reflection
from core.engine.cost_router import route_task_to_optimal_model
from core.infra.guardrails import sanitize_and_verify_code
from core.infra.plugin_loader import discover_and_reload_plugins
from core.infra.theme_manager import set_cli_theme
from core.infra.consensus_matrix import calculate_consensus_matrix
from core.infra.pareto_frontier import calculate_pareto_frontier
from core.infra.context_pruner import compress_prompt_context
from core.infra.circuit_breaker import global_circuit_breaker
from core.infra.token_budget import global_token_budget
from core.infra.ensemble_aggregator import aggregate_ensemble_responses
from core.infra.memory_compactor import compact_agent_memory
from core.engine.agent_telemetry import global_agent_telemetry
from core.infra.adaptive_backoff import calculate_adaptive_backoff_delay
from core.engine.critical_path import calculate_critical_path
from core.infra.system_prompt_builder import build_personalized_engineer_prompt
from core.infra.dead_letter_queue import global_dlq
from core.infra.cost_forecast import forecast_token_costs
from core.infra.agent_health import get_system_subpackage_health
from core.infra.token_minimizer import count_and_estimate_tokens
from core.infra.dspy_optimizer import global_dspy_optimizer
from core.engine.state_machine import global_agent_fsm
from core.engine.tool_registry import register_tool
from core.engine.agent_memory_index import index_agent_memory
from core.engine.multi_model_router import route_to_best_model
from core.engine.eval_harness import evaluate_agent_response
from core.engine.conversation_brancher import branch_conversation
from core.engine.rollback_engine import rollback_agent_action
from core.engine.ab_testing import run_prompt_ab_test
from core.engine.human_in_loop import request_human_approval
from core.engine.streaming_output import stream_output
from core.engine.context_window import manage_context_window
from core.engine.agent_sandbox import execute_in_sandbox
from core.engine.skill_composer import compose_skills
from core.engine.feedback_loop import collect_feedback
from core.infra.feature_flags import check_feature_flag
from core.infra.audit_logger import log_audit_event
from core.infra.config_validator import validate_config
from core.infra.file_watcher import watch_file_changes
from core.infra.perf_benchmark import run_benchmark
from core.infra.data_anonymizer import anonymize_data
from core.computer import generate_auth_flow, generate_nginx_config, design_rate_limiter, generate_websocket_handler
from core.infra.env_manager import manage_env_config
from core.infra.retry_policy import execute_with_retry
from core.engine.prompt_template import render_prompt_template
from core.engine.chain_of_thought import run_chain_of_thought
from core.infra.health_check import run_health_check
from core.infra.cron_scheduler import schedule_cron_job
from core.infra.api_auth import manage_api_auth
from core.engine.agent_tree_view import show_agent_tree
from core.infra.git_worktree_sandbox import manage_worktree_sandbox
from core.software import auto_heal_multidisciplinary, generate_docker_k8s_manifests, generate_uml_architecture_diagram, generate_db_schema_and_migrations
from core.infra.graph_rag import query_graph_rag, analyze_impact, index_project_structure
from core.engine.multidisciplinary_benchmark import run_multidisciplinary_benchmark
from core.infra.web_dashboard_v2 import start_web_dashboard_v2
from core.software import generate_db_schema_and_migrations, generate_devops_terraform_config
from core.production import generate_project_markdown_report
from core.engine.llm_fallback import (
smart_dispatch, search_engine_registry, list_all_engines,
get_generated_scripts_list, generate_fallback_script, execute_generated_script,
ENGINE_REGISTRY
)
class Colors:
CYAN = '\033[96m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
PURPLE = '\033[95m'
BLUE = '\033[94m'
RED = '\033[91m'
BOLD = '\033[1m'
DIM = '\033[2m'
RESET = '\033[0m'
class AgentFileSystemTools:
"""Built-in file, electronics schematics, and vision tools for the CLI agent."""
@staticmethod
def read_file(file_path: str) -> str:
"""Reads contents of a file in the workspace."""
if not os.path.exists(file_path):
return f"Error: File '{file_path}' does not exist."
try:
with open(file_path, "r", encoding="utf-8") as f:
return f.read()
except Exception as e:
return f"Error reading file: {str(e)}"
@staticmethod
def write_file(file_path: str, content: str) -> str:
"""Writes or updates content to a file in the workspace."""
try:
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, "w", encoding="utf-8") as f:
f.write(content)
return f"Successfully written {len(content)} bytes to '{file_path}'"
except Exception as e:
return f"Error writing file: {str(e)}"
@staticmethod
def list_dir(dir_path: str = ".") -> List[str]:
"""Lists directory contents."""
try:
return os.listdir(dir_path)
except Exception as e:
return [f"Error listing directory: {str(e)}"]
def print_help():
print(f"""
{Colors.BOLD}{Colors.CYAN}🤖 NEURO-SYMBOLIC MULTI-AGENT SYSTEM — HELP (v2.5){Colors.RESET}
{Colors.BOLD}{Colors.YELLOW}🌟 How It Works:{Colors.RESET}
Type your engineering request in natural language (English/Turkish):
{Colors.GREEN}"ESP32 IoT akıllı ev kartı tasarla, pilini hesapla ve C++ kodunu hazırla"{Colors.RESET}
The system automatically routes to {Colors.BOLD}0-Token Local Python Engines ($0.00){Colors.RESET}.
{Colors.BOLD}{Colors.YELLOW}🌳 COMMAND TREE{Colors.RESET}
{Colors.DIM}├── ⚙️ System & Auth{Colors.RESET}
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/help{Colors.RESET} Show this help
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/commands [category]{Colors.RESET} Browse all commands (engine|hardware|software|computer|production|infra|all)
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/auth <cmd> [args]{Colors.RESET} API key manager (list|set|remove|test|export)
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/sandbox <cmd>{Colors.RESET} Git worktree sandbox manager (list|create|merge|discard|cleanup)
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/cockpit [port]{Colors.RESET} Launch Web Cockpit v2 (3D CAD, SVG DAG Graph & Web Console)
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/tree-agents{Colors.RESET} Agent hierarchy & model topology tree
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/agent <name>{Colors.RESET} Switch agent (orchestrator|planner|software|electronics|reviewer|tutor)
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/model <name>{Colors.RESET} Switch model (gpt-4o|claude-3-5-sonnet|gemini-1.5-flash|...)
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/theme <palette>{Colors.RESET} Switch CLI color (cyberpunk|matrix|dracula|default)
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/clear{Colors.RESET} Clear screen & memory
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/quit{Colors.RESET} Exit
{Colors.DIM}│{Colors.RESET}
{Colors.DIM}├── 🤖 Engine (17 cmd){Colors.RESET} {Colors.DIM}/commands engine{Colors.RESET}
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/benchmark [cat]{Colors.RESET} SWE-bench style engineering benchmark suite
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/auto{Colors.RESET} /tree /fsm /smart /engines /layers /cot /critical-path ...
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/tool-registry{Colors.RESET} /agent-memory /model-router /eval-harness /ab-testing ...
{Colors.DIM}│{Colors.RESET}
{Colors.DIM}├── 🔌 Hardware (38 cmd){Colors.RESET} {Colors.DIM}/commands hardware{Colors.RESET}
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/kicad{Colors.RESET} /drc /spice /pinout /thermal /rf /stackup /autoroute ...
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/opamp{Colors.RESET} /adc-snr /can-bus /via-current /ldo-thermal /mosfet-driver ...
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/panelization{Colors.RESET} /gerber-checker /thermal-relief /dac-output /crosstalk ...
{Colors.DIM}│{Colors.RESET}
{Colors.DIM}├── 💻 Software (30 cmd){Colors.RESET} {Colors.DIM}/commands software{Colors.RESET}
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/heal{Colors.RESET} /hil /ota /rtos-design /pid-tune /mqtt-cfg /ble-gatt ...
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/log-framework{Colors.RESET} /unit-test /code-size /firmware-diff /misra-checker ...
{Colors.DIM}│{Colors.RESET}
{Colors.DIM}├── 📐 Production (25 cmd){Colors.RESET} {Colors.DIM}/commands production{Colors.RESET}
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/cad{Colors.RESET} /fea /bom-opt /motor-size /bolt-torque /spring /gear-ratio ...
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/vibration{Colors.RESET} /fan-selection /pipe-flow /solenoid /encoder /enclosure-ip ...
{Colors.DIM}│{Colors.RESET}
{Colors.DIM}├── 🌐 Computer (29 cmd){Colors.RESET} {Colors.DIM}/commands computer{Colors.RESET}
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/web-stack{Colors.RESET} /proto /react /docker-gen /ci-cd /auth-flow /nginx-gen ...
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/nosql-model{Colors.RESET} /system-design /event-driven /mobile-scaffold /app-signing ...
{Colors.DIM}│{Colors.RESET}
{Colors.DIM}├── 🛡️ Infra (22 cmd){Colors.RESET} {Colors.DIM}/commands infra{Colors.RESET}
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/graph-rag <query>{Colors.RESET} GraphRAG hybrid Knowledge Graph & vector search
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/impact <entity>{Colors.RESET} Upstream & downstream breaking impact analysis
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/voice{Colors.RESET} /graph /budget /dlq /dspy /ensemble /auth /agent-health ...
{Colors.DIM}│{Colors.RESET} {Colors.GREEN}/feature-flags{Colors.RESET} /audit-logger /config-validator /perf-benchmark ...
{Colors.DIM}│{Colors.RESET}
{Colors.DIM}└── 📁 File, Build & Memory{Colors.RESET}
{Colors.GREEN}/read{Colors.RESET} /write /list /run /gcc /make /index /search /remember /recall
{Colors.GREEN}/git-status{Colors.RESET} /git-commit /pr /stats /logs /plugins /docs /tui
""")
def print_commands(category: str = None):
cat = category.lower().strip() if category else None
if not cat:
print(f"""
{Colors.BOLD}{Colors.CYAN}📂 COMMAND CATEGORIES MENU (Sub-Packages):{Colors.RESET}
{Colors.GREEN}/commands engine{Colors.RESET} -> 🤖 Workflow, DAG, Tree Simulation & FSM Engines
{Colors.GREEN}/commands hardware{Colors.RESET} -> 🔌 KiCad PCB, DRC, SPICE, Pinout, Stackup & Antennas
{Colors.GREEN}/commands software{Colors.RESET} -> 💻 C++ Firmware, Self-Healing, HIL, Stack Guard & Bootloader
{Colors.GREEN}/commands computer{Colors.RESET} -> 🌐 Full-Stack Web, gRPC Proto, React & AST Complexity
{Colors.GREEN}/commands production{Colors.RESET} -> 📐 OpenSCAD 3D CAD, Vidalar, IP67 Conta & FEA Stress
{Colors.GREEN}/commands infra{Colors.RESET} -> 🛡️ RAG, DSPy Optimizer, DLQ, Voice & Health Monitor
{Colors.GREEN}/commands all{Colors.RESET} -> 📜 Display complete master commands list
""")
return
if cat in ["engine", "all"]:
print(f"{Colors.BOLD}{Colors.YELLOW}🤖 [core.engine] Workflow, DAG & Tree Simulation Commands:{Colors.RESET}")
print(f" {Colors.GREEN}/auto <goal>{Colors.RESET} -> Fully autonomous goal execution loop")
print(f" {Colors.GREEN}/layers <goal>{Colors.RESET} -> Execute task via explicit 5-Layer Architecture Engine")
print(f" {Colors.GREEN}/tree [goal]{Colors.RESET} -> Live visual Agent Tree Simulation & runtime monitor")
print(f" {Colors.GREEN}/tree-agents{Colors.RESET} -> Agent hierarchy, model topology & subagent tree view")
print(f" {Colors.GREEN}/fsm{Colors.RESET} -> Sub-agent finite state machine status & rollback")
print(f" {Colors.GREEN}/critical-path{Colors.RESET} -> Multi-agent task dependency critical path bottleneck profiler")
print(f" {Colors.GREEN}/agent-telemetry{Colors.RESET} -> Multi-agent step-by-step latency Gantt profiler")
print(f" {Colors.GREEN}/cot [prompt]{Colors.RESET} -> Run Tree-of-Thought reasoning decomposition & branch evaluation")
print(f" {Colors.GREEN}/smart <prompt>{Colors.RESET} -> ENGINE_REGISTRY smart dispatch with LLM fallback")
print(f" {Colors.GREEN}/engines{Colors.RESET} -> List all registered 0-token engine modules")
print(f" {Colors.GREEN}/tool-registry{Colors.RESET} -> Register custom tools for agent orchestration")
print(f" {Colors.GREEN}/agent-memory{Colors.RESET} -> Index and query agent memory vectors")
print(f" {Colors.GREEN}/model-router{Colors.RESET} -> Multi-model dynamic cost/quality router")
print(f" {Colors.GREEN}/eval-harness{Colors.RESET} -> Evaluate agent response quality metrics")
print(f" {Colors.GREEN}/conversation-branch{Colors.RESET} -> Fork conversation into parallel exploration branches")
print(f" {Colors.GREEN}/rollback-action{Colors.RESET} -> Rollback last agent action with undo snapshot")
print(f" {Colors.GREEN}/ab-testing{Colors.RESET} -> Run A/B prompt variant experiments")
print(f" {Colors.GREEN}/human-in-loop{Colors.RESET} -> Request human approval gate for critical actions")
print(f" {Colors.GREEN}/streaming-output{Colors.RESET} -> Enable streaming token output mode")
print(f" {Colors.GREEN}/context-window{Colors.RESET} -> Inspect & manage LLM context window usage")
print(f" {Colors.GREEN}/agent-sandbox{Colors.RESET} -> Execute code in isolated sandbox environment")
print(f" {Colors.GREEN}/skill-composer{Colors.RESET} -> Compose multi-step agent skill chains")
print(f" {Colors.GREEN}/feedback-loop{Colors.RESET} -> Collect user feedback for prompt optimization\n")
if cat in ["hardware", "all"]:
print(f"{Colors.BOLD}{Colors.YELLOW}🔌 [core.hardware] KiCad PCB, DRC, SPICE & Antennas:{Colors.RESET}")
print(f" {Colors.GREEN}/kicad <file.kicad_sch>{Colors.RESET} -> Parse KiCad schematic components & net labels")
print(f" {Colors.GREEN}/drc <width_mm>{Colors.RESET} -> Audit PCB manufacturing rules & 50Ω trace impedance")
print(f" {Colors.GREEN}/autoroute{Colors.RESET} -> Auto-route PCB netlist traces using A* algorithm")
print(f" {Colors.GREEN}/spice <r> <c>{Colors.RESET} -> Simulate RC circuit frequency response")
print(f" {Colors.GREEN}/spice-transpile{Colors.RESET} -> Transpile KiCad schematic netlist into raw SPICE .cir")
print(f" {Colors.GREEN}/pinout <sda> <scl> <out>{Colors.RESET} -> Check GPIO pin conflicts & ESP32 strapping hazards")
print(f" {Colors.GREEN}/thermal <vin> <vout> <amps>{Colors.RESET} -> Thermal dissipation & heatsink sizing calculator")
print(f" {Colors.GREEN}/mcu <req>{Colors.RESET} -> Multi-MCU selector & spec recommender engine")
print(f" {Colors.GREEN}/stackup [layers]{Colors.RESET} -> PCB dielectric layer stackup & USB 2.0 trace specs")
print(f" {Colors.GREEN}/3d-clearance{Colors.RESET} -> KiCad 3D STEP component height clearance audit")
print(f" {Colors.GREEN}/footprint-check{Colors.RESET} -> Cross-check KiCad schematic symbol pins vs footprint pads")
print(f" {Colors.GREEN}/trace-matching{Colors.RESET} -> PCB high-speed differential pair length matching")
print(f" {Colors.GREEN}/subsheets{Colors.RESET} -> Generate multi-sheet hierarchical KiCad schematics")
print(f" {Colors.GREEN}/stencil{Colors.RESET} -> PCB SMT solder paste stencil foil thickness & volume calculator")
print(f" {Colors.GREEN}/smps{Colors.RESET} -> Design Buck/Boost SMPS converter inductors & capacitors")
print(f" {Colors.GREEN}/power-budget{Colors.RESET} -> Calculate system active vs sleep current draw & power budget")
print(f" {Colors.GREEN}/v-divider{Colors.RESET} -> Calculate precision E24 resistor pair voltage dividers")
print(f" {Colors.GREEN}/i2c-pullup{Colors.RESET} -> Calculate min/max I2C pull-up resistor & rise time")
print(f" {Colors.GREEN}/esd{Colors.RESET} -> Select IEC 61000-4-2 compliant TVS diode ESD protection")
print(f" {Colors.GREEN}/opamp{Colors.RESET} -> Calculate Op-Amp gain, feedback resistors & 3dB bandwidth")
print(f" {Colors.GREEN}/adc-snr{Colors.RESET} -> Calculate ADC SNR, ENOB, LSB size & quantization noise")
print(f" {Colors.GREEN}/can-bus{Colors.RESET} -> Calculate CAN bus bit timing segments, prescaler & 120Ω termination")
print(f" {Colors.GREEN}/via-current{Colors.RESET} -> Calculate PCB via DC current capacity (IPC-2152) & thermal via array")
print(f" {Colors.GREEN}/ldo-thermal{Colors.RESET} -> Calculate LDO regulator power loss, junction temp & efficiency")
print(f" {Colors.GREEN}/mosfet-driver{Colors.RESET} -> Size MOSFET gate driver peak current, switching time & power loss")
print(f" {Colors.GREEN}/analog-filter{Colors.RESET} -> Design Sallen-Key 2nd-order active low-pass/high-pass filters")
print(f" {Colors.GREEN}/current-sense{Colors.RESET} -> Calculate shunt current sense resistor, power loss & INA gain")
print(f" {Colors.GREEN}/uart-config{Colors.RESET} -> Calculate UART baud rate clock dividers & baud error %")
print(f" {Colors.GREEN}/wheatstone-bridge{Colors.RESET} -> Calculate Wheatstone bridge output voltage & strain gauge sensitivity")
print(f" {Colors.GREEN}/pcb-cost{Colors.RESET} -> Estimate bare board PCB fab & SMT assembly batch cost")
print(f" {Colors.GREEN}/psu-ripple{Colors.RESET} -> Calculate power supply output voltage ripple & filter capacitor C_out")
print(f" {Colors.GREEN}/spi-timing{Colors.RESET} -> Analyze SPI bus clock timing, mode (0-3) & setup/hold margins")
print(f" {Colors.GREEN}/usb-impedance{Colors.RESET} -> Audit USB 2.0 / 3.0 differential pair impedance (90Ω ± 10%)")
print(f" {Colors.GREEN}/fuse-sizing{Colors.RESET} -> Size fuse current rating & inrush energy melting integral I²t")
print(f" {Colors.GREEN}/reverse-polarity{Colors.RESET} -> Compare reverse polarity protection (Schottky vs P-FET vs Ideal Diode)")
print(f" {Colors.GREEN}/rf [freq_mhz]{Colors.RESET} -> Calculate PCB antenna dimensions & 50Ω matching")
print(f" {Colors.GREEN}/genetic-hw{Colors.RESET} -> Multi-objective Pareto genetic hardware optimizer\n")
if cat in ["software", "all"]:
print(f"{Colors.BOLD}{Colors.YELLOW}💻 [core.software] Firmware, Self-Healing & HIL Testing:{Colors.RESET}")
print(f" {Colors.GREEN}/heal <file.c>{Colors.RESET} -> Autonomous self-healing compilation error recovery loop")
print(f" {Colors.GREEN}/hil <file.bin>{Colors.RESET} -> Run Hardware-in-the-Loop physical board test")
print(f" {Colors.GREEN}/unittest-gen <mod>{Colors.RESET} -> Generate Unity C embedded unit test runner code")
print(f" {Colors.GREEN}/edge-ai <params>{Colors.RESET} -> Estimate TinyML peak SRAM/Flash & MCU suitability")
print(f" {Colors.GREEN}/ota [version]{Colors.RESET} -> Generate OTA firmware update manifest & SHA-256")
print(f" {Colors.GREEN}/ota-verify{Colors.RESET} -> Cryptographic OTA binary SHA-256 integrity verifier")
print(f" {Colors.GREEN}/security <code>{Colors.RESET} -> Firmware static security & memory leak audit scanner")
print(f" {Colors.GREEN}/coverage{Colors.RESET} -> C++ unit test line & branch LCOV coverage report generator")
print(f" {Colors.GREEN}/stack-guard{Colors.RESET} -> FreeRTOS task C++ call graph stack overflow guard calculator")
print(f" {Colors.GREEN}/bootloader-check{Colors.RESET} -> Firmware bootloader flash offset & vector table auditor")
print(f" {Colors.GREEN}/rtos-design{Colors.RESET} -> Design FreeRTOS task priorities, stack memory & CPU load")
print(f" {Colors.GREEN}/pid-tune{Colors.RESET} -> Auto-tune PID controller Kp, Ki, Kd parameters")
print(f" {Colors.GREEN}/modbus-gen{Colors.RESET} -> Generate Modbus RTU/TCP register maps & C struct headers")
print(f" {Colors.GREEN}/mqtt-cfg{Colors.RESET} -> Generate structured IoT MQTT topic trees & QoS params")
print(f" {Colors.GREEN}/ble-gatt{Colors.RESET} -> Generate BLE GATT custom UUID services & C code")
print(f" {Colors.GREEN}/lorawan{Colors.RESET} -> Calculate LoRaWAN Time-on-Air, SF, link budget & ETSI duty cycle")
print(f" {Colors.GREEN}/crypto{Colors.RESET} -> Calculate hardware crypto throughput (Mbps) & key sizing")
print(f" {Colors.GREEN}/digital-filter{Colors.RESET} -> Generate FIR/IIR filter tap coefficients & C arrays")
print(f" {Colors.GREEN}/isr-latency{Colors.RESET} -> Calculate NVIC interrupt latency, WCET & max trigger frequency")
print(f" {Colors.GREEN}/memory-pool{Colors.RESET} -> Design deterministic O(1) static fixed-block memory pools")
print(f" {Colors.GREEN}/ring-buffer{Colors.RESET} -> Design lock-free circular ring buffers with power-of-2 masks")
print(f" {Colors.GREEN}/mutex-deadlock{Colors.RESET} -> Detect RTOS mutex deadlock cycle & priority inversion risks")
print(f" {Colors.GREEN}/protobuf-gen{Colors.RESET} -> Generate Protocol Buffers proto3 schemas & C nanopb struct headers")
print(f" {Colors.GREEN}/secure-boot{Colors.RESET} -> Generate Secure Boot V2 ECDSA signing key & flash encryption configs")
print(f" {Colors.GREEN}/fatfs-config{Colors.RESET} -> Configure LittleFS / FATFS wear leveling sector layout")
print(f" {Colors.GREEN}/misra-checker{Colors.RESET} -> Audit C code for MISRA-C:2012 safety-critical compliance rules")
print(f" {Colors.GREEN}/watchdog{Colors.RESET} -> Firmware CPU panic crash dump & watchdog reset analyzer")
print(f" {Colors.GREEN}/power <code>{Colors.RESET} -> Firmware energy consumption & battery life profiler\n")
if cat in ["computer", "all"]:
print(f"{Colors.BOLD}{Colors.YELLOW}🌐 [core.computer] Full-Stack Web, gRPC, React & DevOps:{Colors.RESET}")
print(f" {Colors.GREEN}/web-stack [name]{Colors.RESET} -> Full-stack FastAPI / Express REST API generator")
print(f" {Colors.GREEN}/proto [service]{Colors.RESET} -> Microservices gRPC protobuf3 & event bus schema generator")
print(f" {Colors.GREEN}/react [component]{Colors.RESET} -> Modern React Vite / Next.js TSX component boilerplate")
print(f" {Colors.GREEN}/complexity <code>{Colors.RESET} -> AST cyclomatic code complexity & maintainability index auditor")
print(f" {Colors.GREEN}/rest-gen [resource]{Colors.RESET} -> Scaffold CRUD REST API endpoints & DTO models")
print(f" {Colors.GREEN}/graphql-gen [type]{Colors.RESET} -> Generate GraphQL SDL schemas & resolver stubs")
print(f" {Colors.GREEN}/auth-flow{Colors.RESET} -> Generate OAuth2 / JWT authentication & RBAC middleware")
print(f" {Colors.GREEN}/nginx-gen{Colors.RESET} -> Generate production Nginx reverse proxy, SSL & rate limits")
print(f" {Colors.GREEN}/rate-limiter{Colors.RESET} -> Design API rate limiting token bucket capacity & Redis Lua scripts")
print(f" {Colors.GREEN}/websocket{Colors.RESET} -> Generate real-time WebSocket connection manager & broadcast handlers")
print(f" {Colors.GREEN}/ci-cd [provider]{Colors.RESET} -> Generate GitHub Actions / GitLab CI workflow YAML pipelines")
print(f" {Colors.GREEN}/sql-gen [table]{Colors.RESET} -> Generate PostgreSQL / SQLite DDL schemas & indexes")
print(f" {Colors.GREEN}/terraform-gen [mod]{Colors.RESET} -> Generate AWS Terraform IaC HCL infrastructure modules")
print(f" {Colors.GREEN}/docker-gen [service]{Colors.RESET} -> Automated Dockerfile & Kubernetes deployment manifest generator")
print(f" {Colors.GREEN}/uml [system]{Colors.RESET} -> Software UML sequence & class diagram generator (Mermaid)")
print(f" {Colors.GREEN}/db-schema [table]{Colors.RESET} -> Database PostgreSQL DDL schema & migration generator")
print(f" {Colors.GREEN}/devops [project]{Colors.RESET} -> Cloud AWS Terraform HCL infrastructure & CI/CD generator")
print(f" {Colors.GREEN}/nosql-model{Colors.RESET} -> Design NoSQL document, key-value, and graph database schemas")
print(f" {Colors.GREEN}/query-optimizer{Colors.RESET} -> Analyze SQL query execution plans & index optimization")
print(f" {Colors.GREEN}/data-pipeline{Colors.RESET} -> Design ETL/ELT streaming data pipeline architectures")
print(f" {Colors.GREEN}/monitoring-stack{Colors.RESET} -> Generate Prometheus/Grafana monitoring stack configs")
print(f" {Colors.GREEN}/log-aggregation{Colors.RESET} -> Generate ELK/Loki log pipeline configurations")
print(f" {Colors.GREEN}/component-lib{Colors.RESET} -> Generate reusable UI design system component library")
print(f" {Colors.GREEN}/responsive-layout{Colors.RESET} -> Generate responsive CSS grid/flexbox layout systems")
print(f" {Colors.GREEN}/design-tokens{Colors.RESET} -> Generate design token systems (colors, spacing, typography)")
print(f" {Colors.GREEN}/accessibility-audit{Colors.RESET} -> Audit WCAG 2.1 AA/AAA accessibility compliance")
print(f" {Colors.GREEN}/system-design{Colors.RESET} -> Estimate distributed system capacity & architecture")
print(f" {Colors.GREEN}/event-driven{Colors.RESET} -> Design event-driven microservice architectures")
print(f" {Colors.GREEN}/saga-orchestrator{Colors.RESET} -> Design saga pattern distributed transaction orchestrator")
print(f" {Colors.GREEN}/cqrs-scaffold{Colors.RESET} -> Generate CQRS command/query separation scaffolds")
print(f" {Colors.GREEN}/mobile-scaffold{Colors.RESET} -> Generate Flutter/React Native mobile app scaffolds")
print(f" {Colors.GREEN}/push-notification{Colors.RESET} -> Generate FCM/APNs push notification configurations")
print(f" {Colors.GREEN}/app-signing{Colors.RESET} -> Generate iOS/Android app signing & distribution configs\n")
if cat in ["production", "all"]:
print(f"{Colors.BOLD}{Colors.YELLOW}📐 [core.production] 3D CAD, Fasteners, Gaskets & FEA Stress:{Colors.RESET}")
print(f" {Colors.GREEN}/cad <l> <w> <h>{Colors.RESET} -> Generate OpenSCAD 3D parametric enclosure script")
print(f" {Colors.GREEN}/fasteners [type]{Colors.RESET} -> 3D enclosure metric screw boss thread sizer (M2-M4)")
print(f" {Colors.GREEN}/snap-fit{Colors.RESET} -> 3D enclosure cantilever snap-fit joint strain calculator")
print(f" {Colors.GREEN}/flexure{Colors.RESET} -> 3D enclosure living hinge strain & bending radius calculator")
print(f" {Colors.GREEN}/gasket{Colors.RESET} -> 3D enclosure IP67 waterproof rubber O-ring gasket gland sizer")
print(f" {Colors.GREEN}/cable-gland{Colors.RESET} -> 3D printed enclosure waterproof cable gland sizer")
print(f" {Colors.GREEN}/airflow{Colors.RESET} -> 3D enclosure thermal ventilation slot & CFM airflow calculator")
print(f" {Colors.GREEN}/fea [force_N]{Colors.RESET} -> 3D mechanical FEA stress & deformation simulator")
print(f" {Colors.GREEN}/print-cost{Colors.RESET} -> Estimate 3D printing manufacturing cost (material, power, wear)")
print(f" {Colors.GREEN}/motor-size{Colors.RESET} -> Size DC/BLDC/Stepper motor torque, RPM & mechanical power")
print(f" {Colors.GREEN}/bolt-torque{Colors.RESET} -> Calculate bolt tightening torque & preload force per VDI 2230")
print(f" {Colors.GREEN}/spring{Colors.RESET} -> Calculate helical compression spring rate k, Wahl factor & stress")
print(f" {Colors.GREEN}/gear-ratio{Colors.RESET} -> Calculate spur gear train reduction ratio, output torque & center distance")
print(f" {Colors.GREEN}/heatsink{Colors.RESET} -> Calculate aluminum finned heatsink thermal resistance Rth & volume")
print(f" {Colors.GREEN}/tolerance-stack{Colors.RESET} -> Calculate Worst-Case & RSS 3-sigma statistical tolerance stack-up")
print(f" {Colors.GREEN}/bearing-life{Colors.RESET} -> Calculate ISO 281 ball & roller bearing L10 & L10h lifespan")
print(f" {Colors.GREEN}/slicer-settings{Colors.RESET} -> Recommend 3D printing slicer parameters for PLA/ABS/PETG/TPU")
print(f" {Colors.GREEN}/sheet-metal{Colors.RESET} -> Calculate sheet metal bend allowance (BA) & deduction (BD) flat pattern")
print(f" {Colors.GREEN}/slicer <material>{Colors.RESET} -> Recommend 3D printing slicer settings (PLA/ABS/PETG/TPU)")
print(f" {Colors.GREEN}/bom-opt{Colors.RESET} -> Analyze BOM cost drivers & production quantity tiers")
print(f" {Colors.GREEN}/supply-risk{Colors.RESET} -> Multi-vendor BOM stock availability & EOL risk alert")
print(f" {Colors.GREEN}/bom-sensitivity{Colors.RESET} -> Monte Carlo BOM component cost sensitivity analyzer")
print(f" {Colors.GREEN}/report{Colors.RESET} -> Generate complete multidisciplinary project Markdown report")
print(f" {Colors.GREEN}/slides{Colors.RESET} -> Export HTML presentation slide deck")
print(f" {Colors.GREEN}/injection-mold{Colors.RESET} -> Estimate injection molding tooling cost & cycle time")
print(f" {Colors.GREEN}/cnc-feedrate{Colors.RESET} -> Calculate CNC milling feed rate, spindle RPM & chip load")
print(f" {Colors.GREEN}/beam-stress{Colors.RESET} -> Analyze beam bending moment, shear, & deflection diagrams")
print(f" {Colors.GREEN}/vibration{Colors.RESET} -> Analyze structural natural frequency & resonance modes")
print(f" {Colors.GREEN}/fan-selection{Colors.RESET} -> Select axial/centrifugal cooling fan by PQ curve matching")
print(f" {Colors.GREEN}/pipe-flow{Colors.RESET} -> Calculate pipe flow pressure drop (Darcy-Weisbach)")
print(f" {Colors.GREEN}/solenoid{Colors.RESET} -> Design solenoid coil force, wire gauge & power consumption")
print(f" {Colors.GREEN}/linear-actuator{Colors.RESET} -> Select linear actuator by stroke, force & speed requirements")
print(f" {Colors.GREEN}/encoder{Colors.RESET} -> Calculate rotary encoder CPR/PPR resolution & accuracy")
print(f" {Colors.GREEN}/enclosure-ip{Colors.RESET} -> Check IP rating requirements per IEC 60529\n")
if cat in ["infra", "all"]:
print(f"{Colors.BOLD}{Colors.YELLOW}🛡️ [core.infra] RAG, DSPy Optimizer, DLQ, Voice & Telemetry:{Colors.RESET}")
print(f" {Colors.GREEN}/voice <prompt>{Colors.RESET} -> Voice Assistant hands-free workbench command")
print(f" {Colors.GREEN}/graph <query>{Colors.RESET} -> Query Hardware Knowledge Graph for MCU/Sensors")
print(f" {Colors.GREEN}/health-probe{Colors.RESET} -> Run synthetic health checks across system DBs & services")
print(f" {Colors.GREEN}/cron-schedule{Colors.RESET} -> Schedule periodic background cron tasks")
print(f" {Colors.GREEN}/env-manager{Colors.RESET} -> Audit environment variables & check required production secrets")
print(f" {Colors.GREEN}/retry-policy{Colors.RESET} -> Configure exponential backoff & randomized jitter retry policy")
print(f" {Colors.GREEN}/reflect <task>{Colors.RESET} -> Run task with self-reflective failure critique loop")
print(f" {Colors.GREEN}/cost <prompt>{Colors.RESET} -> Multi-model dynamic cost-optimizer router check")
print(f" {Colors.GREEN}/guard <code>{Colors.RESET} -> Real-time output guardrail & syntax filter")
print(f" {Colors.GREEN}/budget{Colors.RESET} -> Token expenditure dollar budget tracker & alert monitor")
print(f" {Colors.GREEN}/cost-forecast{Colors.RESET} -> Forecast daily/monthly LLM API token expenditure burn rate ($)")
print(f" {Colors.GREEN}/dspy{Colors.RESET} -> DSPy-style automatic prompt optimizer & few-shot bootstrapper")
print(f" {Colors.GREEN}/dlq{Colors.RESET} -> Multi-agent dead letter queue failed task status & retry")
print(f" {Colors.GREEN}/ensemble{Colors.RESET} -> Multi-model dynamic response ensemble aggregator")
print(f" {Colors.GREEN}/prune <text>{Colors.RESET} -> LLM prompt compression & context pruning engine")
print(f" {Colors.GREEN}/compact-memory{Colors.RESET} -> Compact SQLite long-term logs & vector database storage")
print(f" {Colors.GREEN}/agent-health{Colors.RESET} -> Multi-agent system sub-package real-time health monitor")
print(f" {Colors.GREEN}/token-count <text>{Colors.RESET} -> Count BPE tokens and estimate prompt costs per model tier")
print(f" {Colors.GREEN}/auth <cmd>{Colors.RESET} -> API key manager (list|set|remove|test|export)")
print(f" {Colors.GREEN}/feature-flags{Colors.RESET} -> Check & toggle feature flags for experimental modules")
print(f" {Colors.GREEN}/audit-logger{Colors.RESET} -> Log security audit events & compliance trail")
print(f" {Colors.GREEN}/config-validator{Colors.RESET} -> Validate system configuration files & schemas")
print(f" {Colors.GREEN}/file-watcher{Colors.RESET} -> Watch files for changes & trigger rebuild on save")
print(f" {Colors.GREEN}/perf-benchmark{Colors.RESET} -> Run performance benchmark suite & latency profiling")
print(f" {Colors.GREEN}/data-anonymizer{Colors.RESET} -> Anonymize PII data in logs & exports\n")
def print_banner():
print_cli_banner()
def start_interactive_shell(default_agent: str = "orchestrator", default_model: str = "gpt-4o"):
ensure_services_running(verbose=True)
print_banner()
active_agent = default_agent
active_model = default_model
tools = AgentFileSystemTools()
memory = SlidingWindowMemory(max_messages=4)
while True:
try:
print_agent_status_header(active_agent, active_model)
prompt_str = f"{Colors.BOLD}{Colors.CYAN}[{active_agent.upper()} | {active_model}]{Colors.RESET} {Colors.GREEN}agent>{Colors.RESET} "
user_input = input(prompt_str).strip()
if not user_input:
continue
# Slash commands
if user_input.startswith("/"):
parts = user_input.split(maxsplit=3)
cmd = parts[0].lower()
if cmd in ["/exit", "/quit"]:
print(f"{Colors.YELLOW}Exiting agent shell. Goodbye!{Colors.RESET}")
break
elif cmd == "/help":
print_help()
elif cmd == "/commands":
cat_arg = parts[1] if len(parts) > 1 else None
print_commands(cat_arg)
elif cmd == "/clear":
memory.clear()
os.system("cls" if os.name == "nt" else "clear")
print_banner()
print(f"{Colors.GREEN}Memory history cleared.{Colors.RESET}")
elif cmd == "/memory":
context, metrics = memory.get_pruned_context(system_prompt=f"Role: {active_agent}", model_name=active_model)
print(f"{Colors.CYAN}--- CONTEXT MEMORY STATUS ---{Colors.RESET}")
print(f"Total Turns: {len(memory.history)} | Pruned: {metrics['pruned_count']} turns")
print(f"Token Reduction: {metrics['savings_percent']}% saved ({metrics['tokens_saved']} tokens)")
print(f"{Colors.DIM}{context}{Colors.RESET}\n")
elif cmd == "/kicad":
if len(parts) > 1:
res = parse_kicad_schematic(parts[1])
print(f"{Colors.CYAN}--- KICAD SCHEMATIC PARSE RESULT ---{Colors.RESET}")
print(f"File: {parts[1]} | Total Components: {res.get('total_components', 0)}")
for comp in res.get("components", []):
print(f" • {comp['reference']:<6} = {comp['value']:<10} ({comp['library_id']})")
print()
else:
print("Usage: /kicad <file.kicad_sch>")
elif cmd == "/kicad-set":
if len(parts) > 3:
res = update_kicad_component_value(parts[1], parts[2], parts[3])
print(f"{Colors.GREEN}✅ {res}{Colors.RESET}")
else:
print("Usage: /kicad-set <file.kicad_sch> <ref> <new_value> (e.g. /kicad-set demo.kicad_sch R1 1k)")
elif cmd == "/bom":
if len(parts) > 1:
res = parse_bom_csv(parts[1])
print(f"{Colors.CYAN}--- PCB BOM CSV PARSE RESULT ---{Colors.RESET}")
print(f"File: {parts[1]} | Line Items: {res.get('total_line_items', 0)}")
print()
else:
print("Usage: /bom <file.csv>")
elif cmd == "/vision":
if len(parts) > 1:
res = encode_image_to_base64(parts[1])
print(f"{Colors.GREEN}✅ Image encoded to Base64 (MIME: {res.get('mime_type')}, Length: {res.get('base64_length')} chars){Colors.RESET}")
else:
print("Usage: /vision <image_path>")
elif cmd == "/index":
if len(parts) > 1:
target = parts[1]
if os.path.isdir(target):
print(f"{Colors.CYAN}📚 Indexing directory '{target}' into RAG store...{Colors.RESET}")
res = index_directory(target)
else:
print(f"{Colors.CYAN}📄 Indexing file '{target}' into RAG store...{Colors.RESET}")
res = index_file(target)
if res.get("status") == "success":
chunks = res.get("chunks_indexed", res.get("total_chunks_indexed", 0))
print(f"{Colors.GREEN}✅ Indexed {chunks} chunks successfully.{Colors.RESET}")
else:
print(f"{Colors.RED}❌ {res.get('error', 'Unknown error')}{Colors.RESET}")
else:
print("Usage: /index <file_or_directory_path>")
elif cmd == "/search":
if len(parts) > 1:
query = " ".join(parts[1:])
hits = rag_search(query, n_results=5)
print(f"{Colors.CYAN}--- RAG SEARCH RESULTS (Top 5) ---{Colors.RESET}")
for i, hit in enumerate(hits, 1):
sim = hit.get('similarity', 0)
src = hit.get('source', '?')
print(f" {Colors.GREEN}{i}. [{src}] (Relevance: {sim:.0%}){Colors.RESET}")
preview = hit.get('text', '')[:200].replace('\n', ' ')
print(f" {Colors.DIM}{preview}...{Colors.RESET}")
print()
else:
print("Usage: /search <query text>")
elif cmd == "/rag-stats":
stats = get_index_stats()
print(f"{Colors.CYAN}--- RAG INDEX STATISTICS ---{Colors.RESET}")
print(f" Total Chunks: {stats.get('total_chunks', 0)}")
print(f" Collection: {stats.get('collection_name', 'N/A')}")
print(f" Store Path: {stats.get('persist_directory', 'N/A')}")
print()
elif cmd == "/agent":
if len(parts) > 1:
active_agent = parts[1].lower()
print(f"{Colors.GREEN}Switched active agent to: {active_agent.upper()}{Colors.RESET}")
else:
print(f"Current agent: {active_agent}. Usage: /agent <orchestrator|planner|software|electronics|reviewer|tutor>")
elif cmd == "/model":
if len(parts) > 1:
active_model = parts[1].lower()
print(f"{Colors.GREEN}Switched active model to: {active_model}{Colors.RESET}")
else:
print(f"Current model: {active_model}. Usage: /model <model_name>")
elif cmd == "/read":
if len(parts) > 1:
content = tools.read_file(parts[1])
print(f"{Colors.BLUE}--- FILE CONTENT ({parts[1]}) ---{Colors.RESET}\n{content}\n")
else:
print("Usage: /read <file_path>")
elif cmd == "/write":
if len(parts) > 2:
res = tools.write_file(parts[1], parts[2])
print(f"{Colors.GREEN}✅ {res}{Colors.RESET}")
else:
print("Usage: /write <file_path> <content>")
elif cmd == "/list":
target = parts[1] if len(parts) > 1 else "."
files = tools.list_dir(target)
print(f"{Colors.CYAN}Files in '{target}':{Colors.RESET} {', '.join(files)}")
elif cmd == "/stats":
import cli
cli.cmd_stats(None)
elif cmd == "/logs":
import cli
class DummyArgs:
limit = 5
agent = None
cli.cmd_logs(DummyArgs())
# --- Build & Execute ---
elif cmd == "/run":
if len(parts) > 1:
shell_cmd = user_input[5:].strip()
print(f"{Colors.DIM}Executing: {shell_cmd}{Colors.RESET}")
res = execute_command(shell_cmd)
print(f"Return Code: {res['return_code']} | Time: {res.get('execution_time_ms', 0)}ms")
if res.get("stdout"):
print(res["stdout"][-2000:])
if res.get("stderr"):
print(f"{Colors.RED}{res['stderr'][-1000:]}{Colors.RESET}")
else:
print("Usage: /run <shell_command>")
elif cmd == "/gcc":
if len(parts) > 1:
res = compile_c(parts[1])
print(f"{Colors.GREEN if res['status']=='success' else Colors.RED}{res}{Colors.RESET}")
else:
print("Usage: /gcc <source.c>")
elif cmd == "/make":
target = parts[1] if len(parts) > 1 else ""
res = run_make(target)
print(f"{Colors.GREEN if res['status']=='success' else Colors.RED}{res.get('stdout','')}{res.get('stderr','')}{Colors.RESET}")
# --- Long-Term Memory ---
elif cmd == "/remember":
if len(parts) > 3:
cat, key, val = parts[1], parts[2], " ".join(parts[3:])
res = remember(cat, key, val, agent_name=active_agent)
print(f"{Colors.GREEN}✅ Stored: [{cat}] {key} = {val}{Colors.RESET}")
else:
print("Usage: /remember <category> <key> <value> (categories: decision, component, pinout, design, config, note)")
elif cmd == "/recall":
cat = parts[1] if len(parts) > 1 else None
memories = recall(category=cat)
print(f"{Colors.CYAN}--- LONG-TERM MEMORY ({len(memories)} entries) ---{Colors.RESET}")
for m in memories[:15]:
print(f" [{m['category'].upper()}] {m['key']}: {m['value']}")
print()
elif cmd == "/forget":
if len(parts) > 2:
res = forget(parts[1], parts[2])
print(f"{Colors.GREEN}✅ {res}{Colors.RESET}")
else:
print("Usage: /forget <category> <key>")
# --- Pipeline & Automation ---
elif cmd == "/pipeline":
if len(parts) > 1:
task = " ".join(parts[1:])
print(f"{Colors.CYAN}🔀 Running Embedded Dev Pipeline: Planner → [HW + SW] → Reviewer{Colors.RESET}")
pipeline = embedded_dev_pipeline()
result = pipeline.execute(task)
print(f"{Colors.GREEN}✅ Pipeline completed in {result['total_elapsed_ms']}ms ({result['layers_executed']} layers){Colors.RESET}")
for name, info in result["node_results"].items():
emoji = "✅" if info["status"] == "success" else "❌"
print(f" {emoji} {name.upper()} [{info['agent']}] ({info['elapsed_ms']}ms)")
print(f" {Colors.DIM}{info['output'][:150]}...{Colors.RESET}")
print()
else:
print("Usage: /pipeline <task description>")
elif cmd == "/notify":
if len(parts) > 1:
msg = " ".join(parts[1:])
res = notify_all(msg)
print(f"{Colors.GREEN}📨 Notification results: {res}{Colors.RESET}")
else:
print("Usage: /notify <message>")
elif cmd == "/git-status":
res = git_status()
print(f"{Colors.CYAN}--- GIT STATUS ---{Colors.RESET}")
print(res.get("stdout", "Clean working tree"))
elif cmd == "/git-commit":
if len(parts) > 1:
msg = " ".join(parts[1:])
res = git_auto_commit(msg)
print(f"{Colors.GREEN}✅ {res.get('stdout', '')}{Colors.RESET}")
else:
print("Usage: /git-commit <commit message>")
elif cmd == "/plugins" or cmd == "/extensions":
load_plugins_from_dir()
plugins = list_plugins()
render_extensions_ui(plugins)
elif cmd == "/docs":
cat = parts[1] if len(parts) > 1 else None
render_docs_ui(cat)
elif cmd == "/parallel":
if len(parts) > 1:
task = " ".join(parts[1:])
print(f"{Colors.CYAN}⚡ Spawning Parallel Multi-Agent Execution Streams...{Colors.RESET}")
agents_data = [
{"name": "software", "status": "success", "output": f"Generated firmware code for: {task}"},
{"name": "electronics", "status": "success", "output": f"Verified PCB pinouts & hardware specs for: {task}"}
]
render_parallel_execution(agents_data)
else:
print("Usage: /parallel <task description>")
elif cmd == "/test":
print(f"{Colors.CYAN}🧪 Running Automated Agent Unit Test Suite...{Colors.RESET}")
suite = create_system_test_suite()
res = suite.run_all()
print(f"{Colors.GREEN}--- TEST SUITE RESULTS: {res['suite_name']} ({res['pass_rate']} Pass Rate) ---{Colors.RESET}")
for r in res["results"]:
status = f"{Colors.GREEN}✅ PASS{Colors.RESET}" if r["passed"] else f"{Colors.RED}❌ FAIL{Colors.RESET}"
print(f" {status} [{r['name']}] ({r['elapsed_ms']}ms)")
if r["failures"]:
print(f" Failures: {r['failures']}")
print()
# --- SOTA Hardware & Autonomous Tools ---
elif cmd == "/heal":
if len(parts) > 1:
src = parts[1]
dom = parts[2] if len(parts) > 2 else "auto"
print(f"{Colors.CYAN}🔄 Initiating Universal Multi-Domain Self-Healing for '{src}' (Domain: {dom.upper()})...{Colors.RESET}")
res = auto_heal_multidisciplinary(src, domain=dom)
status_color = Colors.GREEN if res.get("status") == "success" and res.get("valid", True) else Colors.YELLOW
print(f"{status_color}--- SELF-HEALING RESULT ({res.get('domain', 'general').upper()}) ---{Colors.RESET}")
print(f" Valid: {res.get('valid', True)}")
print(f" Repairs Made: {res.get('repairs_count', 0)}")
print(f" Time Elapsed: {res.get('execution_time_ms', 0)}ms")
for rep in res.get("repairs", []):
print(f" • {rep}")
print()
else:
print("Usage: /heal <file_path> [domain: auto|python|openscad|kicad|json|c_cpp]")
elif cmd == "/spice":
if len(parts) > 2:
try:
r_val, c_val = float(parts[1]), float(parts[2])
res = simulate_rc_circuit(r_val, c_val)
print(f"{Colors.CYAN}--- RC CIRCUIT SPICE SIMULATION ---{Colors.RESET}")
print(f" R = {r_val} Ω | C = {c_val} F")
print(f" Tau: {res['time_constant_tau_ms']} ms | Cutoff Frequency: {res['cutoff_frequency_hz']} Hz")
print(f" Step Response: {res['step_response']}\n")
except ValueError:
print("Error: R and C must be numeric values.")
else:
print("Usage: /spice <r_ohms> <c_farads> (e.g., /spice 1000 0.000001)")
elif cmd == "/pinout":
if len(parts) > 3:
assigns = {"I2C_SDA": parts[1], "I2C_SCL": parts[2], "OUTPUT_PIN": parts[3]}
res = check_pinout_conflicts(assigns, mcu_family="ESP32")
print(f"{Colors.CYAN}--- PINOUT CONFLICT AUDIT (ESP32) ---{Colors.RESET}")
print(f" Status: {res['status']}")
for c in res.get("conflicts", []):
print(f" {Colors.RED}{c}{Colors.RESET}")
for w in res.get("warnings", []):
print(f" {Colors.YELLOW}{w}{Colors.RESET}")
print()
else:
print("Usage: /pinout <sda_pin> <scl_pin> <output_pin> (e.g. /pinout GPIO21 GPIO22 GPIO34)")
elif cmd == "/consensus":
if len(parts) > 1:
prompt_txt = " ".join(parts[1:])
print(f"{Colors.CYAN}🗳️ Running Multi-Model Consensus Voting (OpenAI + Claude + Gemini)...{Colors.RESET}")
res = run_consensus(prompt_txt)
print(f"{Colors.GREEN}{res['consensus_synthesis']}{Colors.RESET}\n")
else:
print("Usage: /consensus <prompt text>")
elif cmd == "/pr":
if len(parts) > 2:
b_name, title = parts[1], parts[2]
res = create_feature_branch_and_pr(b_name, f"feat: {title}", title, "Automated PR created by Agent System.")
print(f"{Colors.GREEN}✅ {res}{Colors.RESET}\n")
else:
print("Usage: /pr <branch_name> <pr_title>")
elif cmd == "/tui":
render_tui_dashboard()
# --- Production & Flashing Tools ---
elif cmd == "/flash":
if len(parts) > 1:
bin_path = parts[1]
print(f"{Colors.CYAN}⚡ Flashing firmware '{bin_path}' over USB/TTY...{Colors.RESET}")
res = flash_firmware(bin_path)
print(f"{Colors.GREEN if res['status']=='success' else Colors.RED}{res}{Colors.RESET}\n")
else:
print("Usage: /flash <firmware_binary.bin>")
elif cmd == "/serial":
port = parts[1] if len(parts) > 1 else "/dev/ttyUSB0"
print(f"{Colors.CYAN}🔌 Reading UART Serial Console on '{port}'...{Colors.RESET}")
res = read_serial_monitor(port=port)
logs = res.get("logs") or res.get("simulated_logs", [])
for l in logs:
print(f" {Colors.GREEN}{l}{Colors.RESET}")
print()
elif cmd == "/gerber":
if len(parts) > 1:
g_path = parts[1]
print(f"{Colors.CYAN}📐 Analyzing PCB Gerber layers & enclosure bounds for '{g_path}'...{Colors.RESET}")
res = analyze_gerber_layers(g_path)
print(f"{Colors.GREEN}--- PCB GERBER ANALYSIS ---{Colors.RESET}")
print(f" Dimensions: {res['pcb_dimensions']['width_mm']}mm x {res['pcb_dimensions']['height_mm']}mm ({res['pcb_dimensions']['area_sq_cm']} sq cm)")
print(f" Layers: {res['pcb_dimensions']['estimated_layers']} Layer PCB")
print(f" Enclosure: {res['enclosure_3d_recommendation']}\n")
else:
print("Usage: /gerber <gerber_folder_path>")
elif cmd == "/datasheet-compare":
if len(parts) > 2:
res = compare_datasheets(parts[1], parts[2])
md_out = format_comparison_markdown(res)
print(f"{Colors.BLUE}{md_out}{Colors.RESET}\n")
else:
print("Usage: /datasheet-compare <datasheet1.pdf> <datasheet2.pdf>")
elif cmd == "/improve":
if len(parts) > 2:
agent_target, reason = parts[1], " ".join(parts[2:])
res = analyze_and_refine_agent_prompt(agent_target, "User task", reason)
print(f"{Colors.GREEN}✅ {res}{Colors.RESET}\n")
else:
print("Usage: /improve <agent_name> <error_reason_or_rule>")
# --- Multidisciplinary CAD & R&D Tools ---
elif cmd == "/cad":
if len(parts) > 3:
try:
l, w, h = float(parts[1]), float(parts[2]), float(parts[3])
scad = generate_openscad_enclosure(l, w, h)
print(f"{Colors.CYAN}--- OPENSCAD 3D PARAMETRIC ENCLOSURE CODE ---{Colors.RESET}")
print(f"{Colors.GREEN}{scad}{Colors.RESET}\n")
except ValueError:
print("Error: Length, width, and height must be numeric values.")
else:
print("Usage: /cad <length_mm> <width_mm> <height_mm>")
elif cmd == "/slicer":
mat = parts[1] if len(parts) > 1 else "PLA"
res = recommend_slicer_settings(material=mat)
print(f"{Colors.CYAN}--- 3D PRINTING SLICER RECOMMENDATIONS ({res['material']}) ---{Colors.RESET}")
for k, v in res["slicer_recommendations"].items():
print(f" • {k}: {v}")
print()
elif cmd == "/arxiv":
if len(parts) > 1:
q_str = " ".join(parts[1:])
print(f"{Colors.CYAN}📚 Searching arXiv scientific preprints for '{q_str}'...{Colors.RESET}")
papers = search_arxiv_papers(q_str, max_results=3)
for p in papers:
print(f" {Colors.GREEN}• {p['title']} ({p['published']}){Colors.RESET}")
print(f" Authors: {p['authors']} | URL: {p['url']}")
print(f" {Colors.DIM}{p['summary']}{Colors.RESET}\n")
else:
print("Usage: /arxiv <research_topic>")
elif cmd == "/patent":
if len(parts) > 1:
inv_text = " ".join(parts[1:])
res = generate_patent_prior_art_query(inv_text)
print(f"{Colors.CYAN}--- PATENT PRIOR ART SEARCH QUERY ---{Colors.RESET}")
print(f" CPC Codes: {', '.join(res['suggested_cpc_classifications'])}")
print(f" Boolean Query: {res['boolean_search_string']}")
print(f" Google URL: {res['google_patents_query']}\n")
else:
print("Usage: /patent <invention_description>")
elif cmd == "/mcp":
print(f"{Colors.CYAN}🔌 MODEL CONTEXT PROTOCOL (MCP) SERVER GUIDE{Colors.RESET}")
print(" Add to Claude Desktop config (~/Library/Application Support/Claude/claude_desktop_config.json):")
print(' {\n "mcpServers": {\n "agent-system": {\n "command": "python3",\n "args": ["/Users/alihanesentas/Desktop/agent_system/mcp_server.py"]\n }\n }\n }\n')
elif cmd == "/mcp-mode":
if len(parts) > 1:
opt = parts[1].lower()
if opt == "on":
MCPExecutionMode.set_enabled(True)
print(f"{Colors.GREEN}🔌 MCP Protocol Mode ENABLED. Tasks will be routed via mcp_server.py JSON-RPC (~15% schema token overhead).{Colors.RESET}")
elif opt == "off":
MCPExecutionMode.set_enabled(False)
print(f"{Colors.GREEN}⚡ Direct Native Execution Mode ENABLED. Tasks execute natively (Zero token overhead, maximum speed).{Colors.RESET}")
else:
status = "ENABLED (MCP JSON-RPC Protocol)" if MCPExecutionMode.is_enabled() else "DISABLED (Direct Native Execution)"
print(f"MCP Mode Status: {Colors.CYAN}{status}{Colors.RESET}. Usage: /mcp-mode <on|off>")
# --- Edge AI & Personalization Tools ---
elif cmd == "/edge-ai":
params = int(parts[1]) if len(parts) > 1 else 100000
res = estimate_edge_ai_memory(params, [1, 28, 28], quantization="int8")
print(f"{Colors.CYAN}--- EDGE AI & TINYML MEMORY ESTIMATION ---{Colors.RESET}")
print(f" Model Parameters: {res['num_parameters']:,}")
print(f" Flash Footprint: {res['flash_footprint_kb']} KB")
print(f" SRAM Tensor Arena:{res['sram_tensor_arena_kb']} KB")
print(f" Recommended MCUs: {', '.join(res['recommended_mcus'])}\n")
elif cmd == "/profile":
prof = load_user_profile()
print(f"{Colors.CYAN}--- PERSONALIZED ENGINEER PROFILE ({prof['user_name']}) ---{Colors.RESET}")
print(f" Disciplines: {', '.join(prof['primary_disciplines'])}")
print(f" Preferred MCU: {prof['preferred_mcu']} | CAD: {prof['preferred_cad_tool']}")
print(f" Custom Rules: {prof['custom_engineering_rules']}\n")
elif cmd == "/create-project":
if len(parts) > 1:
p_name = parts[1]
print(f"{Colors.CYAN}🏗️ Generating Multidisciplinary Repository Workspace for '{p_name}'...{Colors.RESET}")
res = create_multidisciplinary_project(p_name)
print(f"{Colors.GREEN}✅ Project created at: {res['root_directory']}{Colors.RESET}")
print(f" Structure: firmware/, hardware/, mechanical/, edge_ai/, docs/\n")
else:
print("Usage: /create-project <project_name>")
# --- Advanced Engineering Roadmap Tools ---
elif cmd == "/finetune":
res = estimate_lora_vram(8.0)
ds = export_finetuning_dataset()
print(f"{Colors.CYAN}--- LORA FINE-TUNING & DATASET ESTIMATOR ---{Colors.RESET}")
print(f" Model Size: {res['model_size']} ({res['quantization']})")
print(f" VRAM Needed: {res['estimated_vram_gb']} GB")
print(f" Dataset: Exported to {ds['dataset_file']} ({ds['sample_entries']} entries)\n")
elif cmd == "/drc":
w_val = float(parts[1]) if len(parts) > 1 else 0.3
z_res = calculate_trace_impedance(w_val)
drc_res = audit_pcb_drc_rules(min_trace_width_mm=w_val)
print(f"{Colors.CYAN}--- PCB DRC & IMPEDANCE AUDIT ---{Colors.RESET}")
print(f" Trace Width: {w_val} mm => Calculated Z0: {z_res['calculated_z0_ohms']} Ω ({z_res['match_status']})")
print(f" Factory Status: {drc_res['factory_compatibility']}\n")
elif cmd == "/cart":
bom_file = parts[1] if len(parts) > 1 else "bom.csv"
res = build_distributor_cart_payload(bom_file)
print(f"{Colors.CYAN}--- MOUSER / LCSC AUTOMATED SHOPPING CART ---{Colors.RESET}")
print(f" Line Items: {res['total_line_items']}")
print(f" Mouser Quick Paste Format:\n{res['mouser_cart_import_format']}\n")
elif cmd == "/arena":
if len(parts) > 1:
p_txt = " ".join(parts[1:])
print(f"{Colors.CYAN}🥊 Running Sub-Agent Benchmark Arena (gpt-4o vs gpt-4o-mini)...{Colors.RESET}")
res = run_agent_arena(p_txt)
print(f"{Colors.GREEN}🏆 Speed Winner: {res['speed_winner']} (Difference: {res['latency_difference_ms']}ms){Colors.RESET}\n")
else:
print("Usage: /arena <prompt_text>")
# --- Frontier Thermal, Battery & Production Tools ---
elif cmd == "/thermal":
if len(parts) > 3:
vin, vout, amps = float(parts[1]), float(parts[2]), float(parts[3])
res = analyze_thermal_dissipation(vin, vout, amps)
print(f"{Colors.CYAN}--- THERMAL DISSIPATION & HEATSINK ANALYSIS ---{Colors.RESET}")
print(f" Power Dissipation: {res['power_dissipation_watts']} W | Temp Rise: {res['temperature_rise_c']} °C")
print(f" Junction Temp: {res['calculated_junction_temp_c']} °C ({res['thermal_status']})")
print(f" Heatsink Needed: {res['recommended_heatsink_rating_cw']} °C/W\n")
else:
print("Usage: /thermal <vin> <vout> <amps> (e.g. /thermal 12.0 3.3 0.5)")
elif cmd == "/battery":
mah = float(parts[1]) if len(parts) > 1 else 2500.0
a_ma = float(parts[2]) if len(parts) > 2 else 80.0
res = calculate_battery_lifespan(battery_capacity_mah=mah, active_current_ma=a_ma)
print(f"{Colors.CYAN}--- BATTERY LIFESPAN & SOLAR SIZING ---{Colors.RESET}")
print(f" Battery Capacity: {mah} mAh | Avg Current: {res['average_current_draw_ma']} mA")
print(f" Lifespan: {res['estimated_lifespan_days']} Days ({res['estimated_lifespan_months']} Months)")
print(f" Solar Panel: {res['recommended_solar_panel_watts']} W Panel Needed\n")
elif cmd == "/unittest-gen":
if len(parts) > 2:
mod, funcs = parts[1], parts[2:]
code = generate_unity_c_test(mod, funcs)
print(f"{Colors.CYAN}--- UNITY C EMBEDDED UNIT TEST CODE ---{Colors.RESET}")
print(f"{Colors.GREEN}{code}{Colors.RESET}\n")
else:
print("Usage: /unittest-gen <module_name> <func1> <func2>")
elif cmd == "/bom-opt":
sample_bom = [{"part": "ESP32-S3-WROOM-1", "unit_price_usd": 3.20, "qty": 1}, {"part": "AMS1117-3.3", "unit_price_usd": 0.30, "qty": 1}]
res = optimize_bom_cost(sample_bom, target_production_qty=1000)
print(f"{Colors.CYAN}--- BOM COST OPTIMIZATION (1000 Units Target) ---{Colors.RESET}")
print(f" Total Board BOM Cost: ${res['total_bom_unit_cost_usd']}")
print(f" Cost Drivers: {res['cost_drivers']}")
print(f" Recommendation: {res['recommendation']}\n")
# --- Next-Gen RF, Harness, OTA & EMC Tools ---
elif cmd == "/rf":
freq = float(parts[1]) if len(parts) > 1 else 2400.0
res = calculate_rf_antenna_dimensions(freq)
print(f"{Colors.CYAN}--- RF ANTENNA & IMPEDANCE MATCHING ---{Colors.RESET}")
print(f" Frequency: {freq} MHz")
print(f" Antenna Length: {res['quarter_wave_antenna_length_mm']} mm (Quarter-Wave Monopole)")
print(f" Matching Net: {res['recommended_matching_network']}\n")
elif cmd == "/harness":
amps = float(parts[1]) if len(parts) > 1 else 5.0
length = float(parts[2]) if len(parts) > 2 else 2.0
res = calculate_wire_harness(amps, length)
print(f"{Colors.CYAN}--- WIRE HARNESS & AWG SIZING ---{Colors.RESET}")
print(f" Load Current: {amps} A | Cable Length: {length} m")
print(f" Wire Gauge: {res['recommended_wire_gauge']} ({res['compliance_status']})")
print(f" Voltage Drop: {res['voltage_drop_volts']} V ({res['voltage_drop_percentage']}%)\n")
elif cmd == "/ota":
ver = parts[1] if len(parts) > 1 else "v1.2.0"
res = generate_ota_update_manifest(version_tag=ver)
print(f"{Colors.CYAN}--- FIRMWARE OTA MANIFEST ---{Colors.RESET}")
print(f" Version: {res['firmware_version']}")
print(f" SHA-256 Hash: {res['sha256_checksum']}")
print(f" Download URL: {res['download_url']}\n")
elif cmd == "/gantt":
res = generate_project_gantt_chart()
print(f"{Colors.CYAN}--- MULTIDISCIPLINARY PROJECT GANTT TIMELINE ---{Colors.RESET}")
print(f"{Colors.GREEN}{res['gantt_chart_mermaid']}{Colors.RESET}")
print(f" Total Days: {res['total_estimated_days']} | Critical Path: {res['critical_path']}\n")
elif cmd == "/emc":
res = audit_emc_fcc_compliance()
print(f"{Colors.CYAN}--- EMC / FCC COMPLIANCE PRE-CHECK ---{Colors.RESET}")
print(f" Status: {res['emc_compliance_result']}")
for item in res['audit_checklist']:
print(f" {item}")
print(f" Recommendation: {res['recommendation']}\n")
# --- True Autonomy Goal Loop ---
elif cmd == "/auto":
if len(parts) > 1:
goal_txt = " ".join(parts[1:])
print(f"{Colors.CYAN}🤖 Launching TRUE AUTONOMOUS GOAL EXECUTION LOOP for: '{goal_txt}'...{Colors.RESET}")
res = execute_autonomous_goal(goal_txt)
print(f"\n{Colors.GREEN}{res['final_verdict']}{Colors.RESET}")