-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_simulation_cli.py
More file actions
2421 lines (2131 loc) · 94.9 KB
/
Copy pathrun_simulation_cli.py
File metadata and controls
2421 lines (2131 loc) · 94.9 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
"""
Headless CLI simulation demo — validates the full v0.9 agent pipeline without
any HTTP layer.
Loads a race from data/raw/2025/<gp_name>/ and iterates lap by lap through
RaceReplayEngine. For each lap it builds a RaceState, calls
run_strategy_orchestrator_from_state, and renders a live per-lap Rich table.
Usage
-----
python scripts/run_simulation_cli.py <gp_name> <driver> <team> [options]
Examples
--------
# No LLM — prints MC scores only (fast, no LM Studio required)
python scripts/run_simulation_cli.py Melbourne NOR McLaren --no-llm
# Laps 15-25 with LLM synthesis (LM Studio must be running)
python scripts/run_simulation_cli.py Bahrain NOR McLaren --laps 15-25
# Custom data paths
python scripts/run_simulation_cli.py Monaco LEC Ferrari \\
--raw-dir data/raw/2025 \\
--featured data/processed/laps_featured_2025.parquet
Output columns
--------------
Lap | Cmpd | Life | Action | Conf | STAY / PIT / UDCT / OVCT | Reasoning
"""
from __future__ import annotations
import argparse
import contextlib
import io
import json
import os
import sys
import time
import warnings
from pathlib import Path
from typing import Any, Optional
# Suppress stray SWIG DeprecationWarnings from C-extension imports.
warnings.filterwarnings("ignore", message=".*builtin type.*__module__.*")
# Suppress verbose logging from transformers / setfit / sentence-transformers.
# These libraries log LOAD REPORT tables via Python logging when loading
# state-dicts with mismatched keys (expected behaviour for fine-tuned heads).
import logging as _logging # noqa: E402
_logging.getLogger("transformers").setLevel(_logging.ERROR)
_logging.getLogger("setfit").setLevel(_logging.ERROR)
_logging.getLogger("sentence_transformers").setLevel(_logging.ERROR)
_logging.getLogger("torch").setLevel(_logging.ERROR)
# Silence the cp1252 / UTF-8 collision in subprocess._readerthread on Windows.
# Triggers: torch / triton / nvcc / ffmpeg fallbacks spawn a subprocess that
# Python decodes as utf-8 in a background reader thread; on Windows their
# stderr is cp1252 and the decoder crashes mid-byte. The traceback surfaces
# on the terminal even though the parent loop continues unaffected. Filter
# only this exact pattern (UnicodeDecodeError raised inside _readerthread)
# so legitimate threading exceptions still propagate normally.
import threading as _threading # noqa: E402
_orig_thread_excepthook = _threading.excepthook
def _silence_subprocess_decode(args: _threading.ExceptHookArgs) -> None:
if args.exc_type is UnicodeDecodeError:
tb = args.exc_traceback
while tb is not None:
if tb.tb_frame.f_code.co_name == "_readerthread":
return
tb = tb.tb_next
_orig_thread_excepthook(args)
_threading.excepthook = _silence_subprocess_decode
import pandas as pd # noqa: E402
from rich.console import Console, Group # noqa: E402
from rich.live import Live # noqa: E402
from rich.panel import Panel # noqa: E402
from rich.rule import Rule # noqa: E402
from rich.spinner import Spinner # noqa: E402
from rich.table import Table # noqa: E402
from rich.text import Text # noqa: E402
# ---------------------------------------------------------------------------
# Repo-root sys.path injection — must happen before any src.* import
# ---------------------------------------------------------------------------
_SCRIPT_DIR = Path(__file__).resolve().parent
_REPO_ROOT = next(
(p for p in [_SCRIPT_DIR, *_SCRIPT_DIR.parents] if (p / ".git").exists()),
_SCRIPT_DIR.parent,
)
if str(_REPO_ROOT) not in sys.path:
sys.path.insert(0, str(_REPO_ROOT))
# Load .env so OPENAI_API_KEY is available when --provider openai is used
try:
from dotenv import load_dotenv
_env = _REPO_ROOT / ".env"
if _env.exists():
load_dotenv(_env)
except ImportError:
pass
# ---------------------------------------------------------------------------
# Imports — NLP models load eagerly when strategy_orchestrator imports radio_agent
# (RadioAgentCFG.__post_init__ runs at module level, loading 3 NLP models).
# Suppress C-level fd 1/2 during import so terminal stays clean.
# ---------------------------------------------------------------------------
try:
from src.simulation.replay_engine import RaceReplayEngine
except ImportError as e:
sys.exit(f"[FATAL] Cannot import simulation engine: {e}")
# Inline fd suppression — cannot use _devnull_fds() here because it's defined later.
# We redirect both:
# • C-level fds 1/2 — for any C-extension that writes directly to the OS fd
# • Python-level sys.stdout/stderr — for TextIOWrapper-buffered output that
# would otherwise be flushed to the terminal after fds are restored.
_dn = os.open(os.devnull, os.O_WRONLY)
_fd1_save, _fd2_save = os.dup(1), os.dup(2)
os.dup2(_dn, 1)
os.dup2(_dn, 2) # noqa: E702
_py_out_save, _py_err_save = sys.stdout, sys.stderr
sys.stdout = sys.stderr = io.StringIO()
os.environ["TQDM_DISABLE"] = "1"
_import_err: str | None = None
try:
from src.agents.strategy_orchestrator import RaceState, run_strategy_orchestrator_from_state
except ImportError as _e:
_import_err = str(_e)
finally:
sys.stdout, sys.stderr = _py_out_save, _py_err_save
os.dup2(_fd1_save, 1)
os.dup2(_fd2_save, 2) # noqa: E702
os.close(_fd1_save)
os.close(_fd2_save)
os.close(_dn) # noqa: E702
os.environ.pop("TQDM_DISABLE", None)
if _import_err:
sys.exit(f"[FATAL] Cannot import strategy orchestrator: {_import_err}")
# ---------------------------------------------------------------------------
# Rich setup
# ---------------------------------------------------------------------------
console = Console()
ACTION_STYLE: dict[str, str] = {
"STAY_OUT": "bold green",
"PIT_NOW": "bold red",
"UNDERCUT": "bold yellow",
"OVERCUT": "bold yellow",
"ALERT": "bold cyan",
}
# Abbreviations for v2 tactical fields rendered in the Decision column
_PM_SHORT: dict[str, str] = {
"PUSH": "PUSH",
"NEUTRAL": "NTRL",
"MANAGE": "MNGR",
"LIFT_AND_COAST": "L&C",
}
_RP_SHORT: dict[str, str] = {
"AGGRESSIVE": "AGG",
"BALANCED": "BAL",
"DEFENSIVE": "DEF",
}
# Pirelli tyre-compound colours
_COMPOUND_STYLE: dict[str, str] = {
"SOFT": "bold red",
"MEDIUM": "bold yellow",
"HARD": "white",
"INTERMEDIATE": "bold green",
"WET": "bold blue",
"INT": "bold green",
}
# Loaded once in run() — maps year → gp → compound → Cx
_TIRE_ALLOC: dict = {}
# ── Driver / team colours (mirrored from src/telemetry/backend/core/driver_colors.py) ──
# No import to avoid heavy telemetry import chain at CLI startup.
_DRIVER_COLORS: dict[str, str] = {
"VER": "#0600EF",
"PER": "#3671C6", # Red Bull
"LEC": "#DC0000",
"SAI": "#FF6B6B", # Ferrari
"HAM": "#C0C0C0",
"RUS": "#E8E8E8", # Mercedes
"NOR": "#FF8700",
"PIA": "#FFB347", # McLaren
"ALO": "#00665F",
"STR": "#2BA572", # Aston Martin
"GAS": "#FF87BC",
"OCO": "#FFC0E3", # Alpine
"ALB": "#041E42",
"SAR": "#1B4F91",
"COL": "#2E6DB5", # Williams
"TSU": "#FFFFFF",
"RIC": "#F5F5F5",
"LAW": "#DCDCDC", # RB
"BOT": "#52E252",
"ZHO": "#90EE90", # Kick Sauber
"MAG": "#787878",
"HUL": "#A8A8A8",
"BEA": "#959595", # Haas
"DOO": "#FFB0D3", # Reserve
}
_DEFAULT_DRIVER_COLOR = "#A259F7"
def _drv_color(code: str) -> str:
"""Return the hex colour for *code*, or a purple fallback."""
return _DRIVER_COLORS.get(code.upper(), _DEFAULT_DRIVER_COLOR)
# ── Simulated radio message pool ──────────────────────────────────────────────
import random as _random # noqa: E402
_RADIO_POOL: dict[str, list[str]] = {
"box": [
"Box box box. Tyres are completely gone.",
"Box this lap, we're losing too much time.",
"Come in, come in. The window is open.",
],
"push": [
"Push now, push push push!",
"Go go go, gap is closing!",
"Lap time, lap time! Everything you've got.",
],
"manage": [
"Tyres, tyres. Watch the degradation.",
"Understood, just manage to the end.",
"Keep it consistent, no heroics.",
],
"info": [
"Copy that, understood.",
"What's the gap to the car behind?",
"Careful of traffic in the last sector.",
"Box? Box? Negative, stay out.",
],
"problem": [
"I've got a vibration on the rear-left.",
"Something feels wrong with the balance.",
"Flat spot, I have a flat spot!",
],
}
_RCM_POOL: list[dict] = [
{
"message": "TRACK LIMITS AT TURN 12 — NOTED",
"flag": "YELLOW",
"category": "Track Limits",
"scope": "Track",
},
{"message": "YELLOW FLAG SECTOR 2", "flag": "YELLOW", "category": "Flag", "scope": "Sector"},
{
"message": "VSC ENDING — SAFETY CAR IN THIS LAP",
"flag": "SAFETY CAR",
"category": "SafetyCar",
"scope": "Track",
},
{"message": "DRS ENABLED", "flag": "GREEN", "category": "DRS", "scope": "Track"},
{
"message": "INCIDENT UNDER INVESTIGATION",
"flag": "YELLOW",
"category": "Other",
"scope": "Driver",
},
]
def _generate_radio_event(
lap_num: int,
driver: str,
compound: str,
tyre_life: int,
position: int,
gap_ahead: float,
) -> dict:
"""Return a context-aware simulated radio message dict."""
if compound in ("SOFT", "MEDIUM") and tyre_life > 22:
intent = "box"
elif gap_ahead < 1.0 and gap_ahead > 0:
intent = "push"
elif position == 1:
intent = "manage"
elif _random.random() < 0.15:
intent = "problem"
else:
intent = _random.choice(["info", "manage"])
return {
"driver": driver,
"lap": lap_num,
"text": _random.choice(_RADIO_POOL[intent]),
"timestamp": None,
}
def _generate_rcm_event(lap_num: int) -> dict | None:
"""Return a random RCM event (30 % chance when called) or None."""
if _random.random() > 0.3:
return None
evt = dict(_random.choice(_RCM_POOL))
evt["lap"] = lap_num
evt["racing_number"] = None
return evt
def _score_float(v: Any) -> float:
"""Extract a scalar score from an MC simulation result entry.
_run_mc_simulation returns {scenario: {"E": float, "P10": float, "P90": float,
"score": float}}. When scenario_scores holds these inner dicts (full LLM path),
we extract the "score" key. When it holds plain floats (no-llm path), we cast
directly.
"""
if isinstance(v, dict):
return float(v.get("score", 0.0))
try:
return float(v)
except (TypeError, ValueError):
return 0.0
def _load_tire_alloc(repo_root: Path) -> None:
"""Populate _TIRE_ALLOC from data/tire_compounds_by_race.json."""
global _TIRE_ALLOC
path = repo_root / "data" / "tire_compounds_by_race.json"
if path.exists():
with open(path) as f:
_TIRE_ALLOC = json.load(f)
def _compound_text(compound: str, gp_name: str, year: int) -> Text:
"""Return a coloured Rich Text showing compound + Cx (e.g. 'SOF/C4')."""
cu = compound.upper()
cx = _TIRE_ALLOC.get(str(year), {}).get(gp_name, {}).get(cu)
if cx:
label = f"{cu[:3]}/{cx}" # SOF/C4, MED/C3, HAR/C2
else:
label = cu[:4] # INTE, WET (no Cx for wet compounds)
return Text(label, style=_COMPOUND_STYLE.get(cu, ""))
@contextlib.contextmanager
def _devnull_fds():
"""Redirect C-level stdout (fd 1) and stderr (fd 2) to os.devnull.
contextlib.redirect_stdout/stderr only intercept Python-level sys.stdout/err.
MLX weight-loading and tqdm write to the underlying C file descriptors
directly (bypassing the Python layer), so os.dup2 is required for full
suppression on all platforms including Windows.
"""
import warnings
devnull_fd = os.open(os.devnull, os.O_WRONLY)
saved = {1: os.dup(1), 2: os.dup(2)}
try:
os.dup2(devnull_fd, 1)
os.dup2(devnull_fd, 2)
with (
contextlib.redirect_stdout(io.StringIO()),
contextlib.redirect_stderr(io.StringIO()),
warnings.catch_warnings(),
):
warnings.simplefilter("ignore")
yield
finally:
for fd, saved_fd in saved.items():
os.dup2(saved_fd, fd)
os.close(saved_fd)
os.close(devnull_fd)
# ---------------------------------------------------------------------------
# LLM-unavailable detection — shared by _probe_core_agents and _run_no_llm
# ---------------------------------------------------------------------------
# Exception type-name fragments that indicate the LLM backend is unreachable
# or misconfigured. Matched via substring on type(exc).__name__. Covers both
# openai-python errors (BadRequestError, APIConnectionError, NotFoundError,
# AuthenticationError, APIStatusError, InternalServerError, RateLimitError,
# ServiceUnavailableError) and raw httpx/urllib failures (ConnectTimeout,
# RemoteDisconnected, etc.).
_LLM_ERR_TYPES = (
"Connection",
"APIConnection",
"OpenAI",
"HTTP",
"Timeout",
"RemoteDisconnected",
"BadRequest",
"NotFound",
"Authentication",
"APIError",
"APIStatusError",
"RateLimit",
"InternalServerError",
"ServiceUnavailable",
"PermissionDenied",
)
# Substrings that reliably indicate "LLM backend alive but unusable" — used
# as a fallback when type name alone is ambiguous (e.g. generic OSError).
# "No models loaded" is the exact LM Studio message when the developer forgot
# to `lms load` a model; "model_not_found" covers OpenAI 404s.
_LLM_ERR_MSGS = (
"Connection error",
"connect ECONNREFUSED",
"No models loaded",
"model_not_found",
"invalid_api_key",
"Could not connect",
"ENOTFOUND",
"getaddrinfo failed",
)
def _is_llm_unavailable(exc: Exception) -> bool:
"""Return True when the exception indicates the LLM backend is unusable.
Used by --no-llm mode and the LLM-mode probe layer to decide whether to
swap an agent output for a stub. Errors unrelated to LLM connectivity
(ML model bugs, bad lap_state, missing features) must NOT match — those
should propagate up to the main try/except so they land in the error row
and alert the user to a real problem.
Matches on both the exception type name (substring) and the first ~300
chars of the exception message. Intentionally broad to handle LM Studio
"No models loaded" (BadRequestError), OpenAI rate limits, and plain
socket failures uniformly.
"""
tn = type(exc).__name__
msg = str(exc)[:300]
return any(k in tn for k in _LLM_ERR_TYPES) or any(k in msg for k in _LLM_ERR_MSGS)
def _prewarm_agents(no_llm: bool) -> None:
"""Initialise all agent singletons before the Live loop with all output suppressed.
Each agent module holds a lazy module-level singleton (_default_*_agent).
Pre-initialising them here:
1. Moves model-loading latency out of the first lap — every lap runs at
the same speed from lap 1 onwards.
2. Eliminates the ThreadPoolExecutor race condition on first call (two
threads trying to initialise the same singleton simultaneously).
3. Suppresses tqdm progress bars and NLP weight LOAD REPORTs at C level.
LangGraph ReAct agents are NOT pre-warmed — they need a live LLM connection.
"""
_old_tqdm = os.environ.get("TQDM_DISABLE")
os.environ["TQDM_DISABLE"] = "1"
try:
with _devnull_fds():
from src.agents.pace_agent import _get_default_pace_agent
from src.agents.pit_strategy_agent import _get_default_pit_agent
from src.agents.race_situation_agent import _get_default_situation_agent
from src.agents.radio_agent import CFG as _r # noqa: F401
from src.agents.tire_agent import _get_default_tire_agent
_get_default_pace_agent()
_get_default_situation_agent()
_get_default_pit_agent()
_get_default_tire_agent()
except Exception:
pass # best-effort; actual errors surface during the run loop
finally:
if _old_tqdm is None:
os.environ.pop("TQDM_DISABLE", None)
else:
os.environ["TQDM_DISABLE"] = _old_tqdm
def _probe_core_agents(
race_state: "RaceState",
lap_state: dict,
laps_df: "pd.DataFrame",
):
"""Run pace + tire + situation + radio agents and return their outputs.
Used in LLM mode to populate the detail panel without waiting for the
full orchestrator. All four always-on agents are probed (pit and RAG
stay unprobed: both are LLM-backed internally, so they would just hit
the LLM twice per lap). Returns a 4-tuple (pace, tire, sit, radio) —
any element may be a stub on error.
"""
from src.agents.pace_agent import PaceOutput, run_pace_agent_from_state
from src.agents.race_situation_agent import (
RaceSituationOutput,
run_race_situation_agent_from_state,
)
from src.agents.radio_agent import RadioOutput, run_radio_agent_from_state
from src.agents.tire_agent import TireOutput, run_tire_agent_from_state
def _safe(fn, *args, stub):
try:
return fn(*args)
except Exception as exc:
if _is_llm_unavailable(exc):
return stub
raise
pace_stub = PaceOutput(
lap_time_pred=90.0,
delta_vs_prev=0.0,
delta_vs_median=0.0,
ci_p10=88.0,
ci_p90=92.0,
reasoning="[probe]",
)
tire_stub = TireOutput(
compound=race_state.compound,
current_tyre_life=race_state.tyre_life,
deg_rate=0.05,
laps_to_cliff_p10=20.0,
laps_to_cliff_p50=25.0,
laps_to_cliff_p90=30.0,
gp_name="",
reasoning="[probe]",
)
sit_stub = RaceSituationOutput(
overtake_prob=0.1,
sc_prob_3lap=0.05,
reasoning="[probe]",
)
radio_stub = RadioOutput(
radio_events=[],
rcm_events=[],
alerts=[],
reasoning="[probe]",
corrections=[],
)
pace_out = _safe(run_pace_agent_from_state, lap_state, stub=pace_stub)
tire_out = _safe(run_tire_agent_from_state, lap_state, laps_df, stub=tire_stub)
sit_out = _safe(run_race_situation_agent_from_state, lap_state, laps_df, stub=sit_stub)
# Radio probe — build a lap_state shim with the current race_state
# radio/RCM buffers so the NLP pipeline sees whatever the wizard-level
# --radio-every generator pushed in this lap. Without the shim it would
# always see an empty buffer and render idle.
radio_ls = {
**lap_state,
"lap": race_state.lap,
"radio_msgs": list(race_state.radio_msgs),
"rcm_events": list(race_state.rcm_events),
}
radio_out = _safe(run_radio_agent_from_state, radio_ls, laps_df, stub=radio_stub)
return pace_out, tire_out, sit_out, radio_out
def _make_table(has_rival: bool = False, show_header: bool = True) -> Table:
"""Build a borderless Rich Table skeleton matching the history layout.
Used in two modes:
• show_header=True — printed ONCE before the Live region as a header row.
• show_header=False — built per-lap as a 1-row sibling table and emitted
via ``live.console.print`` so it scrolls above the Live region.
box is ``None`` so successive per-lap row tables flow as one continuous
stream; column widths are pinned explicitly so alignment is preserved
without any border characters.
Why the split: embedding a growing Table inside the Live renderable caused
Rich to repaint the whole region from the top once total content exceeded
terminal height (cursor cannot rewind above the terminal top line). Moving
history out of Live and keeping only the fixed-height inference panel
inside Live is the standard Rich recipe for growing logs.
When *has_rival* is True an extra "Rival" column is inserted after
"Gap Fwd" showing the tracked driver's position / compound / interval.
"""
table = Table(
box=None,
show_lines=False,
show_header=show_header,
header_style="bold white",
expand=False,
padding=(0, 1),
)
table.add_column("Lap", justify="right", style="dim", width=4)
table.add_column("Tyre", justify="left", width=8)
table.add_column("Age", justify="right", style="dim", width=4)
table.add_column("Pos", justify="right", style="dim", width=4)
table.add_column("Lap (s)", justify="right", width=8)
table.add_column("Gap Fwd", justify="right", style="dim", width=7)
if has_rival:
table.add_column("Rival", justify="left", width=15)
table.add_column("Decision", justify="left", width=20)
table.add_column("Plan", justify="left", style="#60a5fa", width=18)
table.add_column("Conf", justify="right", width=5)
table.add_column("Stay", justify="right", style="green", width=6)
table.add_column("Pit", justify="right", style="red", width=6)
table.add_column("Ucut", justify="right", style="yellow", width=6)
table.add_column("Ocut", justify="right", style="yellow", width=6)
table.add_column("Reasoning", min_width=40, max_width=70)
return table
# ── Sub-agent inference panel ──────────────────────────────────────────────────
#
# Replaces the v1 single-line detail Text with a stacked two-section Panel:
# • Inference section — one row per sub-agent (N25..N29) showing the raw
# numeric outputs of each ML model. Always rendered when any sub-agent
# output is available.
# • Execution plan section — the StrategyRecommendation v2 fields filled by
# the LLM (pit plan, pace mode, risk posture, contingencies, key risks).
# Only rendered in LLM mode where those fields exist.
# The panel is returned as a Rich Panel so the main Live Group can stack it
# under the history table without any manual spacing logic.
# ── Design tokens — F1 pit-wall palette + TUI glyph convention ───────────────
# Research distilled from btop / k9s / lazygit (solid rendering on dark
# terminals) combined with F1 canonical colour semantics:
# purple = fastest, green = personal best / OK, yellow = watch, red = alert.
# Purple is reserved for the live table (fastest-lap highlight), the panel
# uses green/yellow/red + neutral greys so status is readable at a glance
# without competing with the table colouring.
COL_OK = "green3"
COL_WATCH = "gold1"
COL_ALERT = "red3"
COL_LABEL = "grey70"
COL_DIM = "grey50"
COL_HEADLINE = "bright_white"
# Dot-style glyphs — one column wide, render identically on Windows Terminal,
# iTerm2, and kitty. ● for filled states, ◐ for the "watch" half-state, ○ for
# idle/no-op. Putting the glyph in its own column lets the eye scan the status
# column first and only drill into labels/headlines when something is hot.
GLYPH_OK = "●"
GLYPH_WATCH = "◐"
GLYPH_ALERT = "●"
GLYPH_IDLE = "○"
# Friendly short names for conditional sub-agents — used in the panel subtitle
# (and nowhere else now that the Routing row is gone).
_AGENT_DISPLAY: dict[str, str] = {
"N25": "pace",
"N26": "tire",
"N27": "situation",
"N28": "pit",
"N29": "radio",
"N30": "rag",
}
def _mini_grid() -> Table:
"""Return a borderless 4-column grid for one inference or plan row.
Columns (fixed widths so every row lines up perfectly):
* ``glyph`` — single-char status dot (●/◐/○), coloured green/amber/red.
* ``label`` — short agent or section name ("Pace", "Tire", "Pit plan").
* ``headline`` — the single most important number for that row, rendered
in bright white so the eye lands on it first.
* ``context`` — secondary details in dim grey. Free-form; may contain
multi-span ``Text`` so individual tokens keep their own colouring.
The 4-column layout is the key UX change from the v1 two-column label/value
table: the dedicated glyph column turns each row into a visual leader that
can be scanned top-to-bottom without reading any text.
"""
t = Table.grid(padding=(0, 1), expand=False)
t.add_column("glyph", width=1, justify="center")
t.add_column("label", width=10, justify="left", no_wrap=True)
t.add_column("headline", width=24, justify="left", no_wrap=True)
t.add_column("context", justify="left", no_wrap=False)
return t
def _glyph_for(status: str) -> tuple[str, str]:
"""Return a (char, colour) tuple for a status leader column.
Collapses the various per-agent status vocabularies (TireOutput
warning_level, RaceSituationOutput threat_level, plus free-form strings
like ``"ok"``/``"watch"``/``"alert"``) onto four shared states so every
row uses identical glyphs. Unknown strings fall through to the idle
(empty-circle) state so mis-typed callers render harmlessly instead of
masquerading as OK.
"""
s = (status or "").upper()
if s in ("PIT_SOON", "HIGH", "ALERT"):
return GLYPH_ALERT, COL_ALERT
if s in ("MONITOR", "MEDIUM", "WATCH"):
return GLYPH_WATCH, COL_WATCH
if s in ("OK", "LOW", "GOOD"):
return GLYPH_OK, COL_OK
return GLYPH_IDLE, COL_DIM
# ── Row helpers ──────────────────────────────────────────────────────────────
#
# Each helper appends ONE row to the 4-column inference grid. All six agents
# (pace / tire / situation / pit / radio / rag) are rendered every lap —
# conditional agents that the MoE layer did not activate still appear as a
# dimmed "idle" row so the viewer can see the full roster at a glance and
# notice the transition the moment an agent lights up.
#
# Idle rows share a common visual language: empty-circle glyph (○) in
# COL_DIM, label + headline + context all rendered in COL_DIM, and the
# context explains what *triggers* the agent so the viewer learns the
# activation rules by watching the panel.
def _pace_status(delta_vs_prev: float) -> str:
"""Bucket a Δprev lap-time delta onto the shared ok/watch/alert vocab.
Green when the predicted lap is at or faster than the previous actual,
amber for small losses (0 – 0.25 s — normal degradation within a stint),
red for anything bigger (flat-spot, lift-and-coast, traffic). Loose by
design — the headline already carries the precise delta, the glyph just
surfaces the trend for a top-to-bottom scan of the panel.
"""
if delta_vs_prev <= 0.0:
return "OK"
if delta_vs_prev <= 0.25:
return "MONITOR"
return "PIT_SOON" # reuse the alert bucket (red glyph)
def _idle_row(tbl: Table, label: str, hint: str) -> None:
"""Append a dimmed 'idle' row for an agent that did not activate this lap.
Used for conditional agents (Pit, RAG) when the MoE routing layer chose
not to run them. The hint explains the activation rule so the viewer
understands *why* the agent is dark — e.g. "triggers on cliff pressure
or radio problem". Rendered 100 % in COL_DIM to visually recede behind
the active rows above/below it.
"""
tbl.add_row(
Text(GLYPH_IDLE, style=COL_DIM),
Text(label, style=COL_DIM),
Text("idle", style=COL_DIM),
Text(hint, style=COL_DIM),
)
# ── Reasoning syntax highlighter ─────────────────────────────────────────────
#
# A strategist scanning a ReAct narrative at glance-speed wants numbers,
# percentages and quantile names to POP out of the prose. We don't try to
# parse the reasoning semantically — we use a small set of regex patterns to
# paint known token shapes with their semantic colour. Everything else stays
# in the dim italic base style so the numeric tokens visually lead the eye.
#
# Patterns are applied in order via a single Text object, using Text.highlight_regex
# which is idempotent per match span (later patterns do not re-override earlier
# ones). The base style is set at construction time.
_REASONING_PATTERNS: list[tuple[str, str]] = [
# Action tokens — bold coloured so the recommended call jumps out
(r"\bSTAY_OUT\b", "bold green"),
(r"\bPIT_NOW\b", "bold red"),
(r"\bUNDERCUT\b", "bold yellow"),
(r"\bOVERCUT\b", "bold yellow"),
(r"\bALERT\b", "bold cyan"),
# Quantile tokens from MC-Dropout tire model and HistGBT pit model
(r"\bP(?:05|10|50|90|95)\b", "bold #60a5fa"), # blue
# Regulation article references ("Article 30.5", "Art. 32.4(b)")
(r"\bArt(?:icle|\.)\s*\d+(?:\.\d+)?(?:\([a-z]\))?", "bold #fbbf24"), # amber
# Lap references ("lap 22", "laps 15-20")
(r"\blap[s]?\s+\d+(?:\s*[-–]\s*\d+)?", "#f472b6"), # pink
# Percentages — always interesting (probabilities, deltas)
(r"[-+]?\d+(?:\.\d+)?\s*%", "bold #a78bfa"), # violet
# Signed time deltas ("+0.42s", "-1.28s")
(r"[-+]\d+(?:\.\d+)?\s*s(?:/lap)?\b", "bold #fb923c"), # orange
# Plain positive durations / lap-time numbers (only 2+ digit integers or
# decimals with a trailing 's' to avoid matching every number in prose)
(r"\b\d+(?:\.\d+)?\s*s(?:/lap)?\b", "#f97316"), # orange-dim
]
def _style_reasoning(text: str, base_style: str = "") -> Text:
"""Return a Rich Text with semantic colours applied to notable tokens.
Strategy-focused highlighter — it does NOT parse the sentence structure,
it just paints known token shapes with a colour that matches their role
in the decision chain. The goal is "at a glance, which lap? which action?
which probability?" without reading the whole paragraph.
Highlighted token families:
* actions (STAY_OUT / PIT_NOW / UNDERCUT / OVERCUT / ALERT) — bold coloured
* quantiles (P05/P10/P50/P90/P95) — bold blue
* regulation articles (Article 30.5, Art. 32.4(b)) — bold amber
* lap references (lap 22, laps 15-20) — pink
* percentages — bold violet
* signed time deltas (+0.42s, -1.28s/lap) — bold orange
* plain durations with trailing s (3.25s, 24.8s/lap) — orange-dim
``base_style`` lets the caller pick the style for un-highlighted prose.
The inference-panel continuation rows use ``"italic #6b7280"`` so the
reasoning looks visually quieter than the headline row above it; the
history-table Reasoning column uses ``""`` so it blends with the rest
of the columns (no forced italic).
"""
out = Text(text, style=base_style)
for pattern, style in _REASONING_PATTERNS:
try:
out.highlight_regex(pattern, style)
except Exception:
# Defensive — a broken regex must never crash the whole panel.
pass
return out
def _add_reasoning_continuation(tbl: Table, reasoning: str | None) -> None:
"""Append a dimmed continuation row with the agent's own reasoning text.
Sub-agents expose their narrative via the ``reasoning`` field on their
output dataclass — PaceAgent fills it from a string template every lap
(always populated), TireAgent/RaceSituationAgent/RadioAgent/PitStrategyAgent
fill it from the last LLM message in the ReAct loop (populated only in
LLM mode; in no-llm mode these fall back to the stub wrapper). We show
it as a second row under each agent so the viewer can see *why* the
numbers came out that way, not just the numbers themselves.
The continuation text is passed through ``_style_reasoning`` so action
tokens, P-quantiles, lap references, percentages and signed time deltas
are highlighted — that is the difference between staring at a wall of
text and spotting "PIT_NOW on lap 22 ... cliff P50 lap 24 ... +0.42s/lap"
at a glance.
Skips empty strings and the ``[stub — LLM unreachable]`` marker used
by no-llm mode so the panel stays clean when the ReAct chain could
not run. Everything else — including compound-not-available notes
from TireAgent — is rendered. Newlines are collapsed onto a single
line and the text is clipped to 180 chars so a verbose LLM reasoning
cannot blow up the panel height.
"""
if not reasoning:
return
s = " ".join(str(reasoning).split())
if not s or s.startswith("[stub"):
return
if len(s) > 180:
s = s[:177] + "..."
tbl.add_row(
Text(""),
Text(""),
Text("↳", style=COL_DIM),
_style_reasoning(s, base_style=f"italic {COL_DIM}"),
)
def _add_pace_row(tbl: Table, pace_out) -> None:
"""Append the Pace row to an inference grid.
Headline shifts to the *expected delta vs previous lap* — that is the
number a strategist reads first ("am I getting faster or slower?"). The
absolute predicted lap time moves into the context column alongside the
delta vs session median and a compact ±CI half-range. Falls through to
an idle row when lap_time_pred is missing (partial stub from a failed
connection) so the row is still visible.
"""
pred = getattr(pace_out, "lap_time_pred", None)
if pred is None:
_idle_row(tbl, "Pace", "no prediction — stub")
return
dv = getattr(pace_out, "delta_vs_prev", 0.0)
dm = getattr(pace_out, "delta_vs_median", 0.0)
p10 = getattr(pace_out, "ci_p10", 0.0)
p90 = getattr(pace_out, "ci_p90", 0.0)
ci_half = (p90 - p10) / 2.0
glyph, g_col = _glyph_for(_pace_status(dv))
# Headline — delta vs previous lap, coloured green (faster) / red (slower)
headline = Text()
headline.append(
f"Δnext {'+' if dv >= 0 else ''}{dv:.3f}s",
style=f"bold {COL_OK if dv <= 0 else COL_ALERT}",
)
# Context — absolute prediction + vs-median + ±CI half-range
ctx = Text()
ctx.append(f"pred {pred:.2f}s", style=COL_DIM)
ctx.append(f" vs median {'+' if dm >= 0 else ''}{dm:.2f}s", style=COL_DIM)
ctx.append(f" ±{ci_half:.2f}s", style=COL_DIM)
tbl.add_row(
Text(glyph, style=g_col),
Text("Pace", style=COL_LABEL),
headline,
ctx,
)
def _add_tire_row(tbl: Table, tire_out) -> None:
"""Append the Tire row to an inference grid.
Headline is now phrased as "cliff in ~N laps" where N is the MC-Dropout
P50 — remaining laps is the natural frame (not an absolute lap number).
Context carries the P10/P90 uncertainty band as "range A–B laps", the
degradation rate, and the warning-level badge colour-coded via the
shared glyph palette.
"""
deg = getattr(tire_out, "deg_rate", None)
p10 = getattr(tire_out, "laps_to_cliff_p10", None)
p50 = getattr(tire_out, "laps_to_cliff_p50", None)
p90 = getattr(tire_out, "laps_to_cliff_p90", None)
wl = getattr(tire_out, "warning_level", "OK")
if p50 is None:
_idle_row(tbl, "Tire", "no prediction — stub")
return
glyph, g_col = _glyph_for(wl)
headline = Text(f"cliff in ~{int(p50)} laps", style=f"bold {COL_HEADLINE}")
ctx = Text()
if p10 is not None and p90 is not None:
ctx.append(f"range {int(p10)}–{int(p90)} laps", style=COL_DIM)
if deg is not None:
ctx.append(f" deg {deg:.3f}s/lap", style=COL_DIM)
ctx.append(f" {wl}", style=g_col)
tbl.add_row(
Text(glyph, style=g_col),
Text("Tire", style=COL_LABEL),
headline,
ctx,
)
def _add_situation_row(tbl: Table, sit_out) -> None:
"""Append the Situation row to an inference grid.
Headline is the derived threat level (LOW/MEDIUM/HIGH) coloured via the
shared palette — that single word summarises everything. Context spells
out the two raw probabilities with their full English names ("overtake"
and "safety car") to kill the OT/SC jargon that made the v1 row
unreadable at first glance.
"""
ot = float(getattr(sit_out, "overtake_prob", 0.0)) * 100
sc = float(getattr(sit_out, "sc_prob_3lap", 0.0)) * 100
th = getattr(sit_out, "threat_level", "LOW")
glyph, g_col = _glyph_for(th)
headline = Text(f"threat {th}", style=f"bold {g_col}")
ctx = Text()
ctx.append(f"overtake {ot:.0f}%", style=COL_DIM)
ctx.append(
f" safety car {sc:.0f}%",
style=COL_WATCH if sc > 15 else COL_DIM,
)
tbl.add_row(
Text(glyph, style=g_col),
Text("Situation", style=COL_LABEL),
headline,
ctx,
)
def _add_pit_row(tbl: Table, pit_out) -> None:
"""Append the Pit row to an inference grid (conditional agent N28).
When the MoE routing layer did not activate N28 the row is rendered as
a dimmed idle leader so the viewer can still see the agent exists —
previously the entire row was skipped and the pipeline felt smaller
than it really is. When active, headline is "pit P50s → COMPOUND" and
the context carries the P05/P95 duration range plus undercut.
"""
if pit_out is None:
_idle_row(
tbl,
"Pit",
"triggers on cliff pressure, compound change, or problem radio",
)
return
p05 = getattr(pit_out, "stop_duration_p05", None)
p50 = getattr(pit_out, "stop_duration_p50", None)
p95 = getattr(pit_out, "stop_duration_p95", None)
rec = getattr(pit_out, "compound_recommendation", None)
up = getattr(pit_out, "undercut_prob", None)
ut = getattr(pit_out, "undercut_target", None)
glyph, g_col = _glyph_for("WATCH")
headline = Text()
if p50 is not None:
headline.append(f"pit {p50:.2f}s", style=f"bold {COL_HEADLINE}")
if rec:
if p50 is not None:
headline.append(" ", style=COL_DIM)
headline.append(f"→ {rec}", style=f"bold {COL_WATCH}")