-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Expand file tree
/
Copy path_legacy.py
More file actions
5031 lines (4355 loc) · 189 KB
/
Copy path_legacy.py
File metadata and controls
5031 lines (4355 loc) · 189 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
"""Vibe-Trading CLI for natural-language finance research and backtesting.
Usage:
vibe-trading Interactive mode (default)
vibe-trading -p "Backtest AAPL MACD" Single run
vibe-trading serve --port 8899 Start API server
vibe-trading chat Interactive mode
vibe-trading list List runs
vibe-trading show <run_id> Show run details
"""
from __future__ import annotations
# ruff: noqa: E402
import argparse
import csv
import json
import os
import re
import shutil
import signal
import subprocess
import sys
import threading
import time
import uuid
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, List, Optional
import warnings
warnings.filterwarnings("ignore", message=".*Importing verbose from langchain.*")
warnings.filterwarnings("ignore", category=DeprecationWarning, module="langchain")
for _s in ("stdout", "stderr"):
_r = getattr(getattr(sys, _s, None), "reconfigure", None)
if callable(_r):
_r(encoding="utf-8", errors="replace")
from rich import box
from rich.columns import Columns
from rich.live import Live
from rich.markup import escape as rich_escape
from rich.panel import Panel
from rich.prompt import Confirm, IntPrompt, Prompt
from rich.syntax import Syntax
from rich.table import Table
from rich.text import Text
from cli.theme import get_console
console = get_console()
AGENT_DIR = Path(__file__).resolve().parents[1]
RUNS_DIR = AGENT_DIR / "runs"
SWARM_DIR = AGENT_DIR / ".swarm" / "runs"
SESSIONS_DIR = AGENT_DIR / "sessions"
UPLOADS_DIR = AGENT_DIR / "uploads"
EXIT_SUCCESS = 0
EXIT_RUN_FAILED = 1
EXIT_USAGE_ERROR = 2
RICH_TAG_PATTERN = re.compile(r"\[/?[^\]]+\]")
from cli._version import __version__ as _VERSION # noqa: E402 — single source of truth
if TYPE_CHECKING:
from src.agent.loop import AgentLoop
# Agent color assignments for swarm display
_AGENT_STYLES = ["cyan", "magenta", "green", "yellow", "blue", "bright_red", "bright_cyan", "bright_magenta"]
_agent_color_map: dict[str, str] = {}
_HAS_PROMPT_TOOLKIT = False
try:
from prompt_toolkit import PromptSession
from prompt_toolkit.formatted_text import FormattedText
from prompt_toolkit.history import InMemoryHistory
_HAS_PROMPT_TOOLKIT = True
except ImportError:
pass
class _SessionStats:
"""Mutable container for interactive session statistics.
Shared between the status bar renderer and the agent loop so that
tool callbacks can update counters in-place.
"""
__slots__ = ("session_start", "last_elapsed", "total_tool_ms", "tool_count")
def __init__(self, session_start: float) -> None:
self.session_start = session_start
self.last_elapsed: Optional[float] = None
self.total_tool_ms = 0
self.tool_count = 0
def _build_status_parts(stats: _SessionStats) -> list[str]:
"""Build plain-text status bar segments.
Args:
stats: Session statistics.
Returns:
List of status text segments.
"""
provider = os.getenv("LANGCHAIN_PROVIDER", "")
model = os.getenv("LANGCHAIN_MODEL_NAME", "")
model_short = model.split("/")[-1] if "/" in model else model
label = f"{provider}/{model_short}" if provider else model_short or "unknown"
session_s = int(time.monotonic() - stats.session_start)
mins, secs = divmod(session_s, 60)
session_str = f"{mins}m{secs:02d}s" if mins else f"{secs}s"
parts = [label, session_str]
if stats.last_elapsed is not None:
parts.append(f"last {stats.last_elapsed:.1f}s")
if stats.tool_count > 0:
total_s = stats.total_tool_ms / 1000
parts.append(f"{stats.tool_count} tools ({total_s:.1f}s)")
return parts
def _ptk_toolbar(stats: _SessionStats) -> FormattedText:
"""prompt_toolkit bottom_toolbar callback — called on every render.
Args:
stats: Session statistics.
Returns:
FormattedText for the toolbar.
"""
segments = _build_status_parts(stats)
text = " │ ".join(segments)
return FormattedText([("class:bottom-toolbar.text", f" {text} ")])
def _print_status_bar(stats: _SessionStats) -> None:
"""Print a static status bar using Rich (fallback without prompt_toolkit).
Args:
stats: Session statistics.
"""
parts = _build_status_parts(stats)
bar = "[dim] │ [/dim]".join(
f"[bold]{parts[0]}[/bold]" if i == 0 else p for i, p in enumerate(parts)
)
console.print(bar)
def _create_prompt_session(stats: _SessionStats) -> Any:
"""Create a prompt_toolkit PromptSession with history and live toolbar.
Args:
stats: Session statistics for the live bottom toolbar.
Returns:
A PromptSession instance, or None if prompt_toolkit is not available.
"""
if not _HAS_PROMPT_TOOLKIT:
return None
return PromptSession(
history=InMemoryHistory(),
bottom_toolbar=lambda: _ptk_toolbar(stats),
refresh_interval=1.0,
)
def _read_input(prompt_session: Any, prompt_str: str = "> ") -> str:
"""Read user input with arrow key support if prompt_toolkit is available.
Falls back to Rich Prompt.ask() when prompt_toolkit is not installed or
when stdin is not a tty.
Args:
prompt_session: A prompt_toolkit PromptSession, or None.
prompt_str: Prompt text to display.
Returns:
User input string (not stripped).
Raises:
EOFError: When the user presses Ctrl-D.
KeyboardInterrupt: When the user presses Ctrl-C.
"""
if prompt_session is not None and sys.stdin.isatty():
return prompt_session.prompt(prompt_str)
return Prompt.ask(f"[bold]{prompt_str}[/bold]")
def serve_main(argv: list[str] | None = None) -> int:
"""Delegate server startup to api_server."""
from api_server import serve_main as api_serve_main
return api_serve_main(argv)
def _strip_rich_tags(text: str) -> str:
"""Remove Rich markup from plain-text output."""
return RICH_TAG_PATTERN.sub("", text)
def _print_json_result(result: dict) -> None:
"""Print a machine-readable run summary."""
payload = {
"status": result.get("status", "unknown"),
"run_id": result.get("run_id"),
"run_dir": result.get("run_dir"),
"reason": result.get("reason"),
}
print(json.dumps(payload, ensure_ascii=False))
def _result_exit_code(result: dict) -> int:
"""Map run results to stable exit codes."""
return EXIT_SUCCESS if result.get("status") == "success" else EXIT_RUN_FAILED
def _coerce_exit_code(value: Optional[int]) -> int:
"""Normalize command return values to an integer exit code."""
return EXIT_SUCCESS if value is None else int(value)
def _read_prompt_source(
prompt: Optional[str],
prompt_file: Optional[Path],
*,
no_rich: bool,
allow_interactive: bool = True,
) -> tuple[Optional[str], Optional[str]]:
"""Resolve prompt text from CLI args, file, stdin, or interactive input."""
if prompt is not None:
return prompt.strip(), None
if prompt_file is not None:
try:
return prompt_file.read_text(encoding="utf-8").strip(), None
except OSError as exc:
return None, f"Failed to read prompt file: {exc}"
if not sys.stdin.isatty():
return sys.stdin.read().strip(), None
if not allow_interactive:
return None, "A prompt is required."
try:
if no_rich:
return input("Enter strategy request: ").strip(), None
return Prompt.ask("Enter strategy request").strip(), None
except (EOFError, KeyboardInterrupt):
return None, "Prompt input cancelled."
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _read_json(path: Path) -> dict:
"""Safely read JSON."""
if not path.exists():
return {}
try:
return json.loads(path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
return {}
def _read_metrics(path: Path) -> dict:
"""Read metrics from metrics.csv, return formatted string dict."""
if not path.exists():
return {}
try:
with path.open(encoding="utf-8") as f:
rows = list(csv.DictReader(f))
if not rows:
return {}
out = {}
for k, v in rows[0].items():
if not v:
continue
try:
fv = float(v)
out[k] = f"{fv:.4f}" if abs(fv) < 100 else f"{fv:.0f}"
except ValueError:
out[k] = v
return out
except Exception:
return {}
def _status_style(status: str) -> str:
"""Return a consistent Rich color for status labels."""
return {
"success": "green",
"completed": "green",
"ready": "green",
"running": "cyan",
"failed": "red",
"error": "red",
"cancelled": "yellow",
"warning": "yellow",
}.get((status or "").lower(), "dim")
def _format_seconds(seconds: float) -> str:
"""Format elapsed seconds for compact terminal display."""
total = max(0, int(seconds))
mins, secs = divmod(total, 60)
if mins >= 60:
hours, mins = divmod(mins, 60)
return f"{hours:d}h {mins:02d}m"
if mins:
return f"{mins:d}m {secs:02d}s"
return f"{secs:d}s"
def _configured_label(value: str | None) -> str:
"""Render a masked configuration state."""
return "[green]configured[/green]" if value else "[yellow]not set[/yellow]"
def _state_badge(value: str | None, *, ready_label: str = "READY") -> str:
"""Render a compact terminal status badge."""
return f"[black on green] {ready_label} [/]" if value else "[black on yellow] MISSING [/]"
def _terminal_width() -> int:
"""Return the active console width with a conservative fallback."""
try:
return max(40, int(console.size.width))
except Exception:
return 80
def _ensure_cli_env() -> None:
"""Load dotenv values before rendering CLI-only settings."""
try:
from src.providers.llm import _ensure_dotenv
_ensure_dotenv()
except Exception:
pass
def _provider_key_env(provider: str | None) -> str | None:
"""Return the credential environment variable for a provider."""
return {
"openrouter": "OPENROUTER_API_KEY",
"openai": "OPENAI_API_KEY",
"deepseek": "DEEPSEEK_API_KEY",
"gemini": "GEMINI_API_KEY",
"groq": "GROQ_API_KEY",
"dashscope": "DASHSCOPE_API_KEY",
"qwen": "DASHSCOPE_API_KEY",
"zhipu": "ZHIPU_API_KEY",
"moonshot": "MOONSHOT_API_KEY",
"minimax": "MINIMAX_API_KEY",
"mimo": "MIMO_API_KEY",
"zai": "ZAI_API_KEY",
}.get((provider or "").lower())
def _provider_base_env(provider: str | None) -> str | None:
"""Return the base URL environment variable for a provider."""
return {
"openrouter": "OPENROUTER_BASE_URL",
"openai": "OPENAI_BASE_URL",
"openai-codex": "OPENAI_CODEX_BASE_URL",
"deepseek": "DEEPSEEK_BASE_URL",
"gemini": "GEMINI_BASE_URL",
"groq": "GROQ_BASE_URL",
"dashscope": "DASHSCOPE_BASE_URL",
"qwen": "DASHSCOPE_BASE_URL",
"zhipu": "ZHIPU_BASE_URL",
"moonshot": "MOONSHOT_BASE_URL",
"minimax": "MINIMAX_BASE_URL",
"mimo": "MIMO_BASE_URL",
"zai": "ZAI_BASE_URL",
"ollama": "OLLAMA_BASE_URL",
}.get((provider or "").lower())
def _clip_inline(text: str, limit: int) -> str:
"""Collapse whitespace and clip text for single-line terminal cells."""
clipped = " ".join(str(text or "").split())
if len(clipped) <= limit:
return clipped
return clipped[: max(0, limit - 3)] + "..."
def _fit_cell(text: str, width: int) -> str:
"""Clip and pad text to an exact display cell width."""
width = max(1, width)
return _clip_inline(text, width).ljust(width)
def _styled_line(parts: list[tuple[str, int | None, str]]) -> Text:
"""Build one fixed-width line with per-cell styling."""
line = Text()
for value, width, style in parts:
rendered = value if width is None else _fit_cell(value, width)
line.append(rendered, style=style)
return line
def _stack_text(lines: list[Text]) -> Text:
"""Join Text lines while preserving segment styles."""
out = Text()
for idx, line in enumerate(lines):
if idx:
out.append("\n")
out.append_text(line)
return out
def _welcome_widths(term_width: int) -> dict[str, int]:
"""Calculate welcome-screen column widths from the terminal width."""
content_width = max(34, term_width - 8)
label = 10
right_label = 10
right_value = 8
gap = 2 if term_width < 86 else 4
left_value = max(10, content_width - label - gap - right_label - right_value)
command_gap = 2 if term_width < 86 else 6
pair_width = max(20, (content_width - command_gap) // 2)
action = min(16, max(12, pair_width // 2))
use = max(7, pair_width - action - 1)
return {
"content": content_width,
"label": label,
"left_value": left_value,
"gap": gap,
"right_label": right_label,
"right_value": right_value,
"action": action,
"use": use,
"command_gap": command_gap,
}
def _metric_value_style(key: str, value: str) -> str:
"""Return a compact color style for numeric metric values."""
if key in {"total_return", "sharpe", "excess_return", "information_ratio"}:
try:
return "green" if float(value) >= 0 else "red"
except (TypeError, ValueError):
return "white"
if key == "max_drawdown":
return "yellow"
return "white"
_SPINNER_GLYPHS = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
class _RunDashboard:
"""Render a compact live view for a single agent run."""
def __init__(self, prompt: str, max_iter: int) -> None:
self.prompt = prompt
self.max_iter = max_iter
self.start_time = time.monotonic()
self.iterations = 0
self.current_tool = "thinking"
self.current_args = ""
self.latest_text = ""
self.timeline: list[tuple[str, str, str, float, str]] = []
self.status = "running"
self.live: Optional[Live] = None
# Per-tool live feedback keyed by tool name. Supports parallel
# readonly batches (loop._execute_parallel runs up to 8 tools in
# ThreadPoolExecutor and each gets its own HeartbeatTimer). Each
# entry: {start_ts, elapsed_s, stage, current, total, message,
# prev_stage, stage_started_at}.
self.tool_active: dict[str, dict[str, Any]] = {}
self._spinner_idx = 0
self._last_progress_render: float = 0.0
def refresh(self) -> None:
"""Refresh the live display when attached to a Rich Live context."""
if self.live is not None:
self.live.update(self.render())
def _ensure_entry(self, tool: str) -> dict[str, Any]:
"""Return the active per-tool entry, creating it on first use."""
entry = self.tool_active.get(tool)
if entry is None:
entry = {
"start_ts": time.monotonic(),
"elapsed_s": 0.0,
"stage": "",
"current": None,
"total": None,
"message": "",
"prev_stage": None,
"stage_started_at": time.monotonic(),
}
self.tool_active[tool] = entry
return entry
def handle_event(self, event_type: str, data: Dict[str, Any]) -> None:
"""Update the dashboard from AgentLoop UI events."""
if event_type == "text_delta":
delta = data.get("delta", "")
if delta:
self.latest_text = (self.latest_text + delta).strip()[-260:]
self.refresh()
return
if event_type == "thinking_done":
self.current_tool = "thinking"
self.current_args = ""
self.refresh()
return
if event_type == "tool_call":
tool = data.get("tool", "")
args = data.get("arguments", {})
self.iterations += 1
self.current_tool = tool or "tool"
self.current_args = _strip_rich_tags(_format_tool_call_args(tool, args)).strip()
# If the prior timeline row is still "running" with no active
# entry in self.tool_active (i.e. its HeartbeatTimer is gone but
# no tool_result arrived), downgrade it to a warning (H2). Skip
# this when a parallel batch is still in flight — sibling tools
# legitimately remain "running" while a new call lands.
if self.timeline and self.timeline[-1][0] == "running":
prev_status, prev_tool, prev_args, _prev_el, _prev_pre = self.timeline[-1]
if prev_tool not in self.tool_active:
self.timeline[-1] = (
"warning",
prev_tool,
prev_args,
0.0,
"no result event",
)
# Reset per-tool state on each call (handles repeat invocations).
now = time.monotonic()
self.tool_active[self.current_tool] = {
"start_ts": now,
"elapsed_s": 0.0,
"stage": "",
"current": None,
"total": None,
"message": "",
"prev_stage": None,
"stage_started_at": now,
}
self.timeline.append(("running", self.current_tool, self.current_args, 0.0, ""))
self.timeline = self.timeline[-8:]
self.refresh()
return
if event_type == "tool_heartbeat":
# Keepalive while a long tool runs. Updates elapsed in-place.
tool = data.get("tool") or self.current_tool
entry = self._ensure_entry(tool)
entry["elapsed_s"] = float(data.get("elapsed_s", 0) or 0)
self.refresh()
return
if event_type == "tool_progress":
# Structured stage/current/total emitted from the tool.
tool = data.get("tool") or self.current_tool
entry = self._ensure_entry(tool)
stage = str(data.get("stage", "") or "")
if stage and stage != entry.get("stage"):
entry["prev_stage"] = entry.get("stage") or None
entry["stage_started_at"] = time.monotonic()
entry["stage"] = stage
entry["current"] = data.get("current")
entry["total"] = data.get("total")
entry["message"] = str(data.get("message", "") or "")
elapsed = data.get("elapsed_s")
if elapsed is not None:
entry["elapsed_s"] = float(elapsed)
# Throttle redraws so a chatty tool can't peg the renderer (M1).
now = time.monotonic()
if now - self._last_progress_render >= 0.25:
self._last_progress_render = now
self.refresh()
return
if event_type == "tool_result":
tool = data.get("tool", self.current_tool)
status = data.get("status", "ok")
elapsed_s = float(data.get("elapsed_ms", 0) or 0) / 1000
preview = _strip_rich_tags(_format_tool_result_preview(tool, status, data.get("preview", "")))
row_status = "success" if status == "ok" else "failed"
# Find the matching running row for this tool (may not be the last
# row when tools run in parallel).
matched = False
for idx in range(len(self.timeline) - 1, -1, -1):
row = self.timeline[idx]
if row[0] == "running" and row[1] == tool:
self.timeline[idx] = (row_status, tool, row[2], elapsed_s, preview)
matched = True
break
if not matched:
self.timeline.append((row_status, tool, "", elapsed_s, preview))
self.timeline = self.timeline[-8:]
# Drop the per-tool entry so it disappears from the active list.
self.tool_active.pop(tool, None)
if not self.tool_active:
self.current_tool = "thinking"
self.current_args = ""
self.refresh()
return
if event_type == "compact":
tokens = data.get("tokens_before", "?")
self.timeline.append(("warning", "context", "", 0.0, f"compressed after {tokens} tokens"))
self.timeline = self.timeline[-8:]
self.refresh()
def _render_progress_row(
self,
tool: str,
entry: Dict[str, Any],
spinner: str,
bar_width: int,
compact: bool,
detail_width: int,
) -> str:
"""Render a single active-tool progress row for the Current grid."""
stage = str(entry.get("stage") or "")
current_val = entry.get("current")
total_val = entry.get("total")
message = str(entry.get("message") or "")
elapsed_s = float(entry.get("elapsed_s") or 0.0)
has_count = (
isinstance(current_val, int)
and isinstance(total_val, int)
and total_val > 0
)
has_structured = bool(stage or has_count or message)
if not has_structured and elapsed_s <= 0:
return ""
if not has_structured:
# Heartbeat-only fallback. No bar, no decimal precision (L4).
plain = f"{spinner} {tool} · still running… {elapsed_s:.0f}s elapsed"
return f"[dim]{_clip_inline(plain, detail_width)}[/dim]"
# Build a plain prefix + dim suffix so markup survives clipping.
prefix_plain_parts: list[str] = [spinner]
prefix_styled_parts: list[str] = [f"[cyan]{spinner}[/cyan]"]
if stage:
prefix_plain_parts.append(stage)
prefix_styled_parts.append(f"[bold cyan]{stage}[/bold cyan]")
if has_count:
filled = max(0, min(bar_width, int(bar_width * current_val / total_val)))
bar = "#" * filled + "-" * (bar_width - filled)
prefix_plain_parts.append(f"[{bar}]")
prefix_styled_parts.append(f"[cyan]\\[{bar}][/cyan]")
count_str = f"{current_val}/{total_val}"
prefix_plain_parts.append(count_str)
prefix_styled_parts.append(f"[cyan]{count_str}[/cyan]")
else:
prefix_plain_parts.append(f"{elapsed_s:.1f}s")
prefix_styled_parts.append(f"[cyan]{elapsed_s:.1f}s[/cyan]")
prefix_plain = " ".join(prefix_plain_parts)
prefix_styled = " ".join(prefix_styled_parts)
suffix_plain_parts: list[str] = []
if message:
suffix_plain_parts.append(f"· {message}")
# ETA: only when count is known, we're past ~10% and at least 3 units,
# and the stage hasn't just changed (L1). Suppressed in compact mode.
if has_count and not compact and current_val >= 3 and current_val >= total_val * 0.1:
stage_started_at = entry.get("stage_started_at")
prev_stage = entry.get("prev_stage")
stable_stage = (
prev_stage is None
or (
stage_started_at is not None
and (time.monotonic() - float(stage_started_at)) >= 1.0
)
)
if stable_stage and elapsed_s > 0:
try:
eta = (elapsed_s / current_val) * (total_val - current_val)
except ZeroDivisionError:
eta = 0.0
if eta > 0 and eta == eta: # NaN check
suffix_plain_parts.append(f"· ~{eta:.0f}s left")
suffix_plain = " ".join(suffix_plain_parts)
# Clip the dim suffix to whatever space is left after the prefix.
remaining = max(0, detail_width - len(prefix_plain) - 1)
if suffix_plain and remaining > 4:
clipped_suffix = _clip_inline(suffix_plain, remaining)
return f"{prefix_styled} [dim]{clipped_suffix}[/dim]"
return prefix_styled
def render(self) -> Panel:
"""Build the Rich renderable shown while the run is active."""
term_width = _terminal_width()
compact = term_width < 86
content_width = max(32, term_width - (6 if compact else 10))
elapsed = _format_seconds(time.monotonic() - self.start_time)
prompt_preview = _clip_inline(self.prompt, min(96, max(22, content_width - 12)))
meta = Table.grid(expand=True)
meta.add_column(ratio=1)
progress = min(1.0, self.iterations / max(1, self.max_iter))
bar_width = 12 if compact else 20
filled = max(1, int(progress * bar_width)) if self.iterations else 0
bar = "#" * filled + "-" * (bar_width - filled)
progress_text = f"[cyan]{elapsed}[/cyan] [dim]{bar} {self.iterations}/{self.max_iter}[/dim]"
if compact:
meta.add_row("[bold cyan]Running agent[/bold cyan]")
meta.add_row(progress_text)
meta.add_row(f"[dim]Request: {prompt_preview}[/dim]")
else:
meta.add_column(justify="right")
meta.add_row("[bold cyan]Running agent[/bold cyan]", progress_text)
meta.add_row(f"[dim]Request: {prompt_preview}[/dim]", "")
current = Table.grid(expand=True)
current.add_column(width=8 if compact else 9, style="dim")
current.add_column(ratio=1)
tool_label = self.current_tool
if self.current_args:
tool_label = f"{tool_label} [dim]{_clip_inline(self.current_args, max(20, content_width - 18))}[/dim]"
current.add_row("Current", f"[cyan]{tool_label}[/cyan]")
# One row per active tool (caps at 3 to keep dashboard height bounded).
# Snapshot via list(...) first: Rich's refresh thread calls render()
# concurrently with heartbeat/worker threads mutating self.tool_active,
# so a bare ``.items()`` would race and may raise "dictionary changed
# size during iteration". list() materialization is GIL-atomic.
active_entries = sorted(
list(self.tool_active.items()), key=lambda kv: kv[1].get("start_ts", 0.0)
)
if len(active_entries) > 3:
active_entries = active_entries[:3]
# Advance the spinner once per render so all active rows step together.
self._spinner_idx = (self._spinner_idx + 1) % len(_SPINNER_GLYPHS)
spinner = _SPINNER_GLYPHS[self._spinner_idx]
bar_width = 6 if compact else 8
detail_width = max(20, content_width - 18)
for tool, entry in active_entries:
row_text = self._render_progress_row(
tool, entry, spinner, bar_width, compact, detail_width
)
if row_text:
current.add_row("Progress", row_text)
timeline = Table(
box=box.SIMPLE,
show_header=True,
header_style="dim",
padding=(0, 1),
expand=True,
)
timeline.add_column("State", width=7 if compact else 8, no_wrap=True)
timeline.add_column("Tool", width=12 if compact else 20, no_wrap=True)
timeline.add_column("Time", width=6 if compact else 8, justify="right")
timeline.add_column("Detail", ratio=1, overflow="fold")
rows = self.timeline[-6:] or [("running", "waiting", "", 0.0, "starting")]
for status, tool, args, elapsed_s, preview in rows:
style = _status_style(status)
label = "running" if status == "running" else ("ok" if status == "success" else "check")
detail = _clip_inline(preview or args, max(18, content_width - (35 if compact else 48)))
timeline.add_row(
f"[{style}]{label}[/{style}]",
_clip_inline(tool, 12 if compact else 20),
f"{elapsed_s:.1f}s" if elapsed_s else "",
detail,
)
latest = self.latest_text.replace("\n", " ").strip()
latest = _clip_inline(latest[-220:], max(24, content_width - 4))
body = Table.grid(expand=True)
body.add_row(meta)
body.add_row("")
body.add_row(current)
body.add_row("")
body.add_row(timeline)
if latest:
body.add_row("")
body.add_row(Panel(Text(latest, style="dim"), title="Latest answer", border_style="dim", padding=(0, 1)))
return Panel(body, title="Vibe-Trading", border_style="cyan", padding=(1, 1 if compact else 2))
from cli.ui.rail import RailRunDashboard as _RunDashboard # noqa: E402,F811
# ---------------------------------------------------------------------------
# Agent execution core
# ---------------------------------------------------------------------------
def _format_tool_call_args(tool: str, args: Dict[str, str]) -> str:
"""Smart-format tool argument summary."""
if tool == "load_skill":
return f'("{args.get("name", "")}")'
if tool in ("write_file", "read_file", "edit_file"):
return f' {args.get("path", args.get("file_path", ""))}'
if tool in ("bash", "background_run"):
cmd = args.get("command", "")[:80]
return f' [yellow]{cmd}[/yellow]'
if tool == "check_background":
tid = args.get("task_id", "")
return f' {tid}' if tid else ""
if tool in ("backtest", "compact"):
return ""
for v in args.values():
if v and v != "None":
return f" {v[:60]}"
return ""
def _format_tool_result_preview(tool: str, status: str, preview: str) -> str:
"""Smart-format tool result preview."""
if status != "ok":
return f"[red]{preview[:80]}[/red]"
if tool == "backtest":
sharpe = re.search(r'"sharpe":\s*([\d.eE+-]+)', preview)
ret = re.search(r'"total_return":\s*([\d.eE+-]+)', preview)
parts = []
if sharpe:
parts.append(f"sharpe={sharpe.group(1)}")
if ret:
parts.append(f"return={float(ret.group(1))*100:.1f}%")
return ", ".join(parts) if parts else ""
if tool == "render_shadow_report":
url = re.search(r'"report_url":\s*"([^"]+)"', preview)
if url:
return f"[bold cyan]report:[/bold cyan] [link]{url.group(1)}[/link]"
return ""
if tool in ("extract_shadow_strategy", "run_shadow_backtest"):
sid = re.search(r'"shadow_id":\s*"([^"]+)"', preview)
return f"shadow_id={sid.group(1)}" if sid else ""
if tool in ("bash", "background_run"):
if "OK" in preview[:50]:
return "OK"
return preview[:60].replace("\n", " ")
if tool in ("read_file", "load_skill", "compact"):
return ""
return ""
# ---------------------------------------------------------------------------
# In-process mandate.proposal relay (CLI mirror of api_server's
# _mandate_proposal_frame_from_tool_result, SPEC.md Consent §1/§2)
# ---------------------------------------------------------------------------
#
# The agent loop emits the propose tool's output only as a generic
# ``tool_result`` event (``loop.py`` ``_finalize_tool_result`` → preview =
# result[:200]); it NEVER emits a top-level ``mandate.proposal`` event. So in
# the in-process REPL path nothing ever arms ``ctx.pending_proposal`` and the
# user's numeric pick falls through to the model as chat. The frontend solved
# the same gap server-side by relaying the propose-tool ``tool_result`` into a
# top-level ``mandate.proposal`` SSE frame (api_server
# ``_mandate_proposal_frame_from_tool_result``). The CLI needs the identical
# relay in its own ``on_event`` handler — done below, WITHOUT touching the
# protected ``loop.py``.
_PROPOSAL_TOOL_NAME = "propose_mandate_profiles"
_PROPOSAL_ID_RE = re.compile(r'"proposal_id"\s*:\s*"(mp_[0-9a-f]{32})"')
def _load_full_proposal(proposal_id: str) -> Optional[Dict[str, Any]]:
"""Reload a persisted ``mandate.proposal`` payload by id, broker-agnostic.
The propose tool persists the full proposal under
``<runtime_root>/live/<broker>/proposals/<proposal_id>.json`` before
returning. The ``tool_result`` preview is only the first 200 chars of the
JSON body, far too short to carry the full proposal, so the relay reloads it
from disk. The broker segment is unknown from the preview alone, so every
broker's proposals directory is searched (mirrors api_server).
Args:
proposal_id: The ``mp_...`` id parsed from the tool_result preview.
Returns:
The full proposal dict, or ``None`` when not found / unreadable.
"""
try:
from src.live.paths import live_root
for proposal_path in live_root().glob(f"*/proposals/{proposal_id}.json"):
try:
data = json.loads(proposal_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
continue
if isinstance(data, dict) and data.get("type") == "mandate.proposal":
return data
except Exception: # noqa: BLE001 — relay must never break the turn
pass
return None
def _mandate_proposal_from_tool_result(data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""Recover a full ``mandate.proposal`` payload from a propose-tool result.
Detection mirrors api_server's ``_mandate_proposal_frame_from_tool_result``:
the event must be a successful ``tool_result`` for ``propose_mandate_profiles``
whose preview carries a ``proposal_id``. The full proposal is then reloaded
from disk (the preview is truncated).
Args:
data: The ``tool_result`` event payload (``tool`` / ``status`` /
``preview``).
Returns:
The full proposal dict ready to feed ``proposal_sink`` (arming
``ctx.pending_proposal``), or ``None`` when this is not a recoverable
propose-tool result.
"""
if data.get("tool") != _PROPOSAL_TOOL_NAME or data.get("status") != "ok":
return None
match = _PROPOSAL_ID_RE.search(str(data.get("preview") or ""))
if not match:
return None
return _load_full_proposal(match.group(1))
def _run_agent(
prompt: str,
history: Optional[List[Dict]] = None,
run_dir_override: Optional[str] = None,
max_iter: int = 50,
*,
no_rich: bool = False,
stream_output: bool = True,
dashboard: Optional[_RunDashboard] = None,
session_id: str = "",
proposal_sink: Optional[Any] = None,
) -> dict:
"""Build AgentLoop and execute, return result dict.
Args:
proposal_sink: Optional callable invoked with the payload of every
``mandate.proposal`` event the agent emits. The interactive REPL
uses this to capture an outstanding live-trading mandate proposal so
it can intercept the user's numeric pick *before* the model — a pick
is a privileged surface action (commit), never a tool the model can
call (SPEC.md Consent §2).
"""
from src.tools import build_registry
from src.providers.chat import ChatLLM
from src.agent.loop import AgentLoop
# Closure-level state for the no-rich path so dots and progress lines
# don't shoulder-bump each other (M3) and progress prints are throttled
# to ≤1/0.5s per tool (M1).
no_rich_state: dict[str, Any] = {
"dot_pending": False,
"last_progress_ts": {}, # type: ignore[var-annotated]
}
def on_event(event_type: str, data: Dict[str, Any]) -> None:
# Live mandate proposals are surfaced to the REPL out-of-band so the
# user's pick is intercepted before the model (SPEC.md Consent §2).
# This fires regardless of stream_output / rich state — capturing the
# proposal must not depend on rendering.
if event_type == "mandate.proposal" and proposal_sink is not None:
try:
proposal_sink(data)
except Exception: # noqa: BLE001 — capture must never kill the turn
pass
return
# The agent loop never emits a top-level ``mandate.proposal`` — it only
# emits the propose tool's output as a generic ``tool_result``. Relay it
# here (CLI mirror of api_server's SSE relay) so the REPL arms
# ``ctx.pending_proposal`` and intercepts the pick before the model
# (SPEC.md Consent §1/§2). Fires regardless of stream_output / rich
# state — arming must not depend on rendering — and does NOT return:
# the tool_result still flows on to the dashboard / no-rich printers.
if event_type == "tool_result" and proposal_sink is not None:
proposal = _mandate_proposal_from_tool_result(data)
if proposal is not None:
try:
proposal_sink(proposal)
except Exception: # noqa: BLE001 — relay must never kill the turn
pass
if not stream_output:
return
if dashboard is not None and not no_rich:
dashboard.handle_event(event_type, data)
return
if no_rich and event_type == "thinking_done":
print()
return
if no_rich and event_type == "tool_call":
tool = data.get("tool", "")
args = data.get("arguments", {})
args_preview = _format_tool_call_args(tool, args)
print(f" - {tool}{_strip_rich_tags(args_preview)}", end="")
no_rich_state["dot_pending"] = False
return