-
Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathconsole.py
More file actions
2211 lines (1882 loc) · 77.7 KB
/
Copy pathconsole.py
File metadata and controls
2211 lines (1882 loc) · 77.7 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
# Copyright(C) 2025-2026 Advanced Micro Devices, Inc. All rights reserved.
# SPDX-License-Identifier: MIT
import json
import logging
import subprocess
import threading
import time
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional
from gaia.agents.base.tools import get_tool_display_name
logger = logging.getLogger(__name__)
# Import Rich library for pretty printing and syntax highlighting
try:
from rich import print as rprint
from rich.console import Console
from rich.live import Live
from rich.panel import Panel
from rich.spinner import Spinner
from rich.syntax import Syntax
from rich.table import Table
RICH_AVAILABLE = True
except ImportError:
RICH_AVAILABLE = False
rprint = print
Panel = None
Console = None
Live = None
Spinner = None
Syntax = None
Table = None
print(
"Rich library not found. Install with 'uv pip install rich' for syntax highlighting."
)
# Display configuration constants
MAX_DISPLAY_LINE_LENGTH = 120
# ANSI Color Codes for fallback when Rich is not available
ANSI_RESET = "\033[0m"
ANSI_BOLD = "\033[1m"
ANSI_DIM = "\033[90m" # Dark Gray
ANSI_RED = "\033[91m"
ANSI_GREEN = "\033[92m"
ANSI_YELLOW = "\033[93m"
ANSI_BLUE = "\033[94m"
ANSI_MAGENTA = "\033[95m"
ANSI_CYAN = "\033[96m"
class OutputHandler(ABC):
"""
Abstract base class for handling agent output.
Defines the minimal interface that agents use to report their progress.
Each implementation handles the output differently:
- AgentConsole: Rich console output for CLI
- SilentConsole: Suppressed output for testing
- SSEOutputHandler: Server-Sent Events for API streaming
This interface focuses on WHAT agents need to report, not HOW
each handler chooses to display it.
"""
# === Core Progress/State Methods (Required) ===
@abstractmethod
def print_processing_start(self, query: str, max_steps: int, model_id: str = None):
"""Print processing start message."""
...
@abstractmethod
def print_step_header(self, step_num: int, step_limit: int):
"""Print step header."""
...
@abstractmethod
def print_state_info(self, state_message: str):
"""Print current execution state."""
...
@abstractmethod
def print_thought(self, thought: str):
"""Print agent's reasoning/thought."""
...
@abstractmethod
def print_goal(self, goal: str):
"""Print agent's current goal."""
...
@abstractmethod
def print_plan(self, plan: List[Any], current_step: int = None):
"""Print agent's plan with optional current step highlight."""
...
# === Tool Execution Methods (Required) ===
@abstractmethod
def print_tool_usage(self, tool_name: str):
"""Print tool being called."""
...
@abstractmethod
def print_tool_complete(self):
"""Print tool completion."""
...
@abstractmethod
def pretty_print_json(self, data: Dict[str, Any], title: str = None):
"""Print JSON data (tool args/results)."""
...
# === Status Messages (Required) ===
@abstractmethod
def print_error(self, error_message: str):
"""Print error message."""
...
@abstractmethod
def print_warning(self, warning_message: str):
"""Print warning message."""
...
@abstractmethod
def print_info(self, message: str):
"""Print informational message."""
...
# === Progress Indicators (Required) ===
@abstractmethod
def start_progress(self, message: str):
"""Start progress indicator."""
...
@abstractmethod
def stop_progress(self):
"""Stop progress indicator."""
...
# === Completion Methods (Required) ===
@abstractmethod
def print_final_answer(self, answer: str):
"""Print final answer/result."""
...
@abstractmethod
def print_repeated_tool_warning(self):
"""Print warning about repeated tool calls (loop detection)."""
...
@abstractmethod
def print_completion(self, steps_taken: int, steps_limit: int):
"""Print completion summary."""
...
@abstractmethod
def print_step_paused(self, description: str):
"""Print step paused message."""
...
@abstractmethod
def print_command_executing(self, command: str):
"""Print command executing message."""
...
@abstractmethod
def print_agent_selected(self, agent_name: str, language: str, project_type: str):
"""Print agent selected message."""
...
# === Optional Methods (with default no-op implementations) ===
def print_prompt(
self, prompt: str, title: str = "Prompt"
): # pylint: disable=unused-argument
"""Print prompt (for debugging). Optional - default no-op."""
...
def print_response(
self, response: str, title: str = "Response"
): # pylint: disable=unused-argument
"""Print response (for debugging). Optional - default no-op."""
...
def print_streaming_text(
self, text_chunk: str, end_of_stream: bool = False
): # pylint: disable=unused-argument
"""Print streaming text. Optional - default no-op."""
...
def display_stats(self, stats: Dict[str, Any]): # pylint: disable=unused-argument
"""Display performance statistics. Optional - default no-op."""
...
def print_header(self, text: str): # pylint: disable=unused-argument
"""Print header. Optional - default no-op."""
...
def confirm_tool_execution(
self,
tool_name: str, # pylint: disable=unused-argument
tool_args: Dict[str, Any], # pylint: disable=unused-argument
) -> bool:
"""Request user confirmation before executing a tool. Returns True to proceed."""
return True
def print_separator(self, length: int = 50): # pylint: disable=unused-argument
"""Print separator. Optional - default no-op."""
...
def print_tool_info(
self, name: str, params_str: str, description: str
): # pylint: disable=unused-argument
"""Print tool info. Optional - default no-op."""
...
class ProgressIndicator:
"""A simple progress indicator that shows a spinner or dots animation with elapsed time."""
def __init__(self, message="Processing", show_timer=False):
"""Initialize the progress indicator.
Args:
message: The message to display before the animation
show_timer: If True, show elapsed time
"""
self.message = message
self.is_running = False
self.thread = None
self.spinner_chars = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
self.dot_chars = [".", "..", "..."]
self.spinner_idx = 0
self.dot_idx = 0
self.rich_spinner = None
self.show_timer = show_timer
self.start_time = None
self._update_timer_thread = None # Timer update thread
if RICH_AVAILABLE:
self.rich_spinner = Spinner("dots", text=message)
self.live = None
def _animate(self):
"""Animation loop that runs in a separate thread."""
while self.is_running:
if RICH_AVAILABLE:
# Rich handles the animation internally
time.sleep(0.1)
else:
# Simple terminal-based animation
self.dot_idx = (self.dot_idx + 1) % len(self.dot_chars)
self.spinner_idx = (self.spinner_idx + 1) % len(self.spinner_chars)
# Determine if we should use Unicode spinner or simple dots
try:
# Try to print a Unicode character to see if the terminal supports it
print(self.spinner_chars[0], end="", flush=True)
print(
"\b", end="", flush=True
) # Backspace to remove the test character
# If we got here, Unicode is supported
print(
f"\r{self.message} {self.spinner_chars[self.spinner_idx]}",
end="",
flush=True,
)
except (UnicodeError, OSError):
# Fallback to simple dots
print(
f"\r{self.message}{self.dot_chars[self.dot_idx]}",
end="",
flush=True,
)
time.sleep(0.1)
def start(self, message=None, show_timer=None):
"""Start the progress indicator.
Args:
message: Optional new message to display
show_timer: Optional override for showing timer
"""
if message:
self.message = message
if show_timer is not None:
self.show_timer = show_timer
if self.is_running:
return
self.is_running = True
self.start_time = time.time()
if RICH_AVAILABLE:
if self.rich_spinner:
self.rich_spinner.text = self.message
# Use transient=True to auto-clear when done
self.live = Live(
self.rich_spinner, refresh_per_second=10, transient=True
)
self.live.start()
# Update with timer if enabled
if self.show_timer:
self._update_timer_thread = threading.Thread(
target=self._update_timer
)
self._update_timer_thread.daemon = True
self._update_timer_thread.start()
else:
self.thread = threading.Thread(target=self._animate)
self.thread.daemon = True
self.thread.start()
def _update_timer(self):
"""Update spinner text with elapsed time."""
while self.is_running and self.live:
elapsed = time.time() - self.start_time
timer_text = f"{self.message} ({int(elapsed)}s)"
try:
self.rich_spinner.text = timer_text
self.live.update(self.rich_spinner)
time.sleep(1.0) # Update every 1 second
except Exception:
break
def stop(self):
"""Stop the progress indicator."""
if not self.is_running:
return
self.is_running = False
# Stop timer thread if running
if RICH_AVAILABLE and hasattr(self, "_update_timer_thread"):
try:
self._update_timer_thread.join(timeout=0.5)
except Exception:
pass
if RICH_AVAILABLE and self.live:
self.live.stop()
elif self.thread:
self.thread.join(timeout=0.2)
# Clear the animation line
print("\r" + " " * (len(self.message) + 5) + "\r", end="", flush=True)
class AgentConsole(OutputHandler):
"""
A class to handle all display-related functionality for the agent.
Provides rich text formatting and progress indicators when available.
Implements OutputHandler for CLI-based output.
"""
def __init__(self):
"""Initialize the AgentConsole with appropriate display capabilities."""
self.rich_available = RICH_AVAILABLE
self.console = Console() if self.rich_available else None
self.progress = ProgressIndicator()
self.rprint = rprint
self.Panel = Panel
self.streaming_buffer = "" # Buffer for accumulating streaming text
self.file_preview_live: Optional[Live] = None
self.file_preview_content = ""
self.file_preview_filename = ""
self.file_preview_max_lines = 15
self._paused_preview = False # Track if preview was paused for progress
self._last_preview_update_time = 0 # Throttle preview updates
self._preview_update_interval = 0.25 # Minimum seconds between updates
def print(self, *args, **kwargs):
"""
Print method that delegates to Rich Console or standard print.
This allows code to call console.print() directly on AgentConsole instances.
Args:
*args: Arguments to print
**kwargs: Keyword arguments (style, etc.) for Rich Console
"""
if self.rich_available and self.console:
self.console.print(*args, **kwargs)
else:
# Fallback to standard print
print(*args, **kwargs)
# Implementation of OutputHandler abstract methods
def pretty_print_json(self, data: Dict[str, Any], title: str = None) -> None:
"""
Pretty print JSON data with syntax highlighting if Rich is available.
If data contains a "command" field, shows it prominently.
Args:
data: Dictionary data to print
title: Optional title for the panel
"""
def _safe_default(obj: Any) -> Any:
"""
JSON serializer fallback that handles common non-serializable types like numpy scalars/arrays.
"""
try:
import numpy as np # Local import to avoid hard dependency at module import time
if isinstance(obj, np.generic):
return obj.item()
if isinstance(obj, np.ndarray):
return obj.tolist()
except Exception:
pass
for caster in (float, int, str):
try:
return caster(obj)
except Exception:
continue
return "<non-serializable>"
if self.rich_available:
# Check if this is a command execution result
if "command" in data and "stdout" in data:
# Show command execution in a special format
command = data.get("command", "")
stdout = data.get("stdout", "")
stderr = data.get("stderr", "")
return_code = data.get("return_code", 0)
# Build preview text
preview = f"$ {command}\n\n"
if stdout:
preview += stdout[:500] # First 500 chars
if len(stdout) > 500:
preview += "\n... (output truncated)"
if stderr:
preview += f"\n\nSTDERR:\n{stderr[:200]}"
if return_code != 0:
preview += f"\n\n[Return code: {return_code}]"
self.console.print(
Panel(
preview,
title=title or "Command Output",
border_style="blue",
expand=False,
)
)
else:
# Regular JSON output
# Convert to formatted JSON string with safe fallback for non-serializable types (e.g., numpy.float32)
try:
json_str = json.dumps(data, indent=2)
except TypeError:
json_str = json.dumps(data, indent=2, default=_safe_default)
# Create a syntax object with JSON highlighting
syntax = Syntax(json_str, "json", theme="monokai", line_numbers=False)
# Create a panel with a title if provided
if title:
self.console.print(Panel(syntax, title=title, border_style="blue"))
else:
self.console.print(syntax)
else:
# Fallback to standard pretty printing without highlighting
if title:
print(f"\n--- {title} ---")
# Check if this is a command execution
if "command" in data and "stdout" in data:
print(f"\n$ {data.get('command', '')}")
stdout = data.get("stdout", "")
if stdout:
print(stdout[:500])
if len(stdout) > 500:
print("... (output truncated)")
else:
try:
print(json.dumps(data, indent=2))
except TypeError:
print(json.dumps(data, indent=2, default=_safe_default))
def print_header(self, text: str) -> None:
"""
Print a header with appropriate styling.
Args:
text: The header text to display
"""
if self.rich_available:
self.console.print(f"\n[bold blue]{text}[/bold blue]")
else:
print(f"\n{text}")
def print_step_paused(self, description: str) -> None:
"""
Print step paused message.
Args:
description: Description of the step being paused after
"""
if self.rich_available:
self.console.print(
f"\n[bold yellow]⏸️ Paused after step:[/bold yellow] {description}"
)
self.console.print("Press Enter to continue, or 'n'/'q' to stop...")
else:
print(f"\n⏸️ Paused after step: {description}")
print("Press Enter to continue, or 'n'/'q' to stop...")
def print_processing_start(
self, query: str, max_steps: int, model_id: str = None
) -> None:
"""
Print the initial processing message.
Args:
query: The user query being processed
max_steps: Maximum number of steps allowed (kept for API compatibility)
model_id: Optional model ID to display
"""
if self.rich_available:
self.console.print(f"\n[bold blue]🤖 Processing:[/bold blue] '{query}'")
self.console.print("=" * 50)
if model_id:
self.console.print(f"[dim]Model: {model_id}[/dim]")
self.console.print()
else:
print(f"\n🤖 Processing: '{query}'")
print("=" * 50)
if model_id:
print(f"Model: {model_id}")
print()
def print_separator(self, length: int = 50) -> None:
"""
Print a separator line.
Args:
length: Length of the separator line
"""
if self.rich_available:
self.console.print("=" * length, style="dim")
else:
print("=" * length)
def print_step_header(self, step_num: int, step_limit: int) -> None:
"""
Print a step header.
Args:
step_num: Current step number
step_limit: Maximum number of steps (unused, kept for compatibility)
"""
_ = step_limit # Mark as intentionally unused
if self.rich_available:
self.console.print(
f"\n[bold cyan]📝 Step {step_num}:[/bold cyan] Thinking...",
highlight=False,
)
else:
print(f"\n📝 Step {step_num}: Thinking...")
def print_thought(self, thought: str) -> None:
"""
Print the agent's thought with appropriate styling.
Args:
thought: The thought to display
"""
if self.rich_available:
self.console.print(f"[bold green]🧠 Thought:[/bold green] {thought}")
else:
print(f"🧠 Thought: {thought}")
def print_goal(self, goal: str) -> None:
"""
Print the agent's goal with appropriate styling.
Args:
goal: The goal to display
"""
if self.rich_available:
self.console.print(f"[bold yellow]🎯 Goal:[/bold yellow] {goal}")
else:
print(f"🎯 Goal: {goal}")
def print_plan(self, plan: List[Any], current_step: int = None) -> None:
"""
Print the agent's plan with appropriate styling.
Args:
plan: List of plan steps
current_step: Optional index of the current step being executed (0-based)
"""
if self.rich_available:
self.console.print("\n[bold magenta]📋 Plan:[/bold magenta]")
for i, step in enumerate(plan):
step_text = step
# Convert dict steps to string representation if needed
if isinstance(step, dict):
if "tool" in step and "tool_args" in step:
args_str = json.dumps(step["tool_args"], sort_keys=True)
step_text = f"Use tool '{step['tool']}' with args: {args_str}"
else:
step_text = json.dumps(step)
# Highlight the current step being executed
if current_step is not None and i == current_step:
self.console.print(
f" [dim]{i+1}.[/dim] [bold green]►[/bold green] [bold yellow]{step_text}[/bold yellow] [bold green]◄[/bold green] [cyan](current step)[/cyan]"
)
else:
self.console.print(f" [dim]{i+1}.[/dim] {step_text}")
# Add an extra newline for better readability
self.console.print("")
else:
print("\n📋 Plan:")
for i, step in enumerate(plan):
step_text = step
# Convert dict steps to string representation if needed
if isinstance(step, dict):
if "tool" in step and "tool_args" in step:
args_str = json.dumps(step["tool_args"], sort_keys=True)
step_text = f"Use tool '{step['tool']}' with args: {args_str}"
else:
step_text = json.dumps(step)
# Highlight the current step being executed
if current_step is not None and i == current_step:
print(f" {i+1}. ► {step_text} ◄ (current step)")
else:
print(f" {i+1}. {step_text}")
def print_plan_progress(
self, current_step: int, total_steps: int, completed_steps: int = None
):
"""
Print progress in plan execution
Args:
current_step: Current step being executed (1-based)
total_steps: Total number of steps in the plan
completed_steps: Optional number of already completed steps
"""
if completed_steps is None:
completed_steps = current_step - 1
progress_str = f"[Step {current_step}/{total_steps}]"
progress_bar = ""
# Create a simple progress bar
if total_steps > 0:
bar_width = 20
completed_chars = int((completed_steps / total_steps) * bar_width)
current_char = 1 if current_step <= total_steps else 0
remaining_chars = bar_width - completed_chars - current_char
progress_bar = (
"█" * completed_chars + "▶" * current_char + "░" * remaining_chars
)
if self.rich_available:
self.rprint(f"[cyan]{progress_str}[/cyan] {progress_bar}")
else:
print(f"{progress_str} {progress_bar}")
def print_checklist(self, items: List[Any], current_idx: int) -> None:
"""Print the checklist with current item highlighted.
Args:
items: List of checklist items (must have .description attribute)
current_idx: Index of the item currently being executed (0-based)
"""
if self.rich_available:
self.console.print("\n[bold magenta]📋 EXECUTION PLAN[/bold magenta]")
self.console.print("=" * 60, style="dim")
for i, item in enumerate(items):
desc = getattr(item, "description", str(item))
if i < current_idx:
# Completed
self.console.print(f" [green]✓ {desc}[/green]")
elif i == current_idx:
# Current
self.console.print(f" [bold blue]➜ {desc}[/bold blue]")
else:
# Pending
self.console.print(f" [dim]○ {desc}[/dim]")
self.console.print("=" * 60, style="dim")
self.console.print("")
else:
print("\n" + "=" * 60)
print(f"{ANSI_BOLD}📋 EXECUTION PLAN{ANSI_RESET}")
print("=" * 60)
for i, item in enumerate(items):
desc = getattr(item, "description", str(item))
if i < current_idx:
print(f" {ANSI_GREEN}✓ {desc}{ANSI_RESET}")
elif i == current_idx:
print(f" {ANSI_BLUE}{ANSI_BOLD}➜ {desc}{ANSI_RESET}")
else:
print(f" {ANSI_DIM}○ {desc}{ANSI_RESET}")
print("=" * 60 + "\n")
def print_checklist_reasoning(self, reasoning: str) -> None:
"""
Print checklist reasoning.
Args:
reasoning: The reasoning text to display
"""
if self.rich_available:
self.console.print("\n[bold]📝 CHECKLIST REASONING[/bold]")
self.console.print("=" * 60, style="dim")
self.console.print(f"{reasoning}")
self.console.print("=" * 60, style="dim")
self.console.print("")
else:
print("\n" + "=" * 60)
print(f"{ANSI_BOLD}📝 CHECKLIST REASONING{ANSI_RESET}")
print("=" * 60)
print(f"{reasoning}")
print("=" * 60 + "\n")
def print_command_executing(self, command: str) -> None:
"""
Print command executing message.
Args:
command: The command being executed
"""
if self.rich_available:
self.console.print(f"\n[bold]Executing Command:[/bold] {command}")
else:
print(f"\nExecuting Command: {command}")
def print_agent_selected(
self, agent_name: str, language: str, project_type: str
) -> None:
"""
Print agent selected message.
Args:
agent_name: The name of the selected agent
language: The detected programming language
project_type: The detected project type
"""
if self.rich_available:
self.console.print(
f"[bold]🤖 Agent Selected:[/bold] [blue]{agent_name}[/blue] (language={language}, project_type={project_type})\n"
)
else:
print(
f"{ANSI_BOLD}🤖 Agent Selected:{ANSI_RESET} {ANSI_BLUE}{agent_name}{ANSI_RESET} (language={language}, project_type={project_type})\n"
)
def print_tool_usage(self, tool_name: str) -> None:
"""
Print tool usage information with user-friendly descriptions.
Args:
tool_name: Name of the tool being used
"""
# Map tool names to user-friendly action descriptions
tool_descriptions = {
# RAG Tools
"list_indexed_documents": "📚 Checking which documents are currently indexed",
"query_documents": "🔍 Searching through indexed documents for relevant information",
"query_specific_file": "📄 Searching within a specific document",
"search_indexed_chunks": "🔎 Performing exact text search in indexed content",
"index_document": "📥 Adding document to the knowledge base",
"index_directory": "📁 Indexing all documents in a directory",
"dump_document": "📝 Exporting document content for analysis",
"summarize_document": "📋 Creating a summary of the document",
"rag_status": "ℹ️ Retrieving RAG system status",
# File System Tools
"search_file": "🔍 Searching for files on your system",
"search_directory": "📂 Looking for directories on your system",
"search_file_content": "📝 Searching for content within files",
"read_file": "📖 Reading file contents",
"write_file": "✏️ Writing content to a file",
"add_watch_directory": "👁️ Starting to monitor a directory for changes",
# Shell Tools
"run_shell_command": "💻 Executing shell command",
# Default for unknown tools
"default": "🔧 Executing operation",
}
# Get the description or use the tool name if not found
action_desc = tool_descriptions.get(tool_name, tool_descriptions["default"])
display_name = get_tool_display_name(tool_name)
if self.rich_available:
self.console.print(f"\n[bold blue]{action_desc}[/bold blue]")
if action_desc == tool_descriptions["default"]:
# If using default, also show the tool display name
self.console.print(f" [dim]Tool: {display_name}[/dim]")
else:
print(f"\n{action_desc}")
if action_desc == tool_descriptions["default"]:
print(f" Tool: {display_name}")
def print_tool_complete(self) -> None:
"""Print that tool execution is complete."""
if self.rich_available:
self.console.print("[green]✅ Tool execution complete[/green]")
else:
print("✅ Tool execution complete")
def print_error(self, error_message: str) -> None:
"""
Print an error message with appropriate styling.
Args:
error_message: The error message to display
"""
# Handle None error messages
if error_message is None:
error_message = "Unknown error occurred (received None)"
if self.rich_available:
self.console.print(
Panel(str(error_message), title="⚠️ Error", border_style="red")
)
else:
print(f"\n⚠️ ERROR: {error_message}\n")
def print_info(self, message: str) -> None:
"""
Print an information message.
Args:
message: The information message to display
"""
if self.rich_available:
self.console.print() # Add newline before
self.console.print(Panel(message, title="ℹ️ Info", border_style="blue"))
else:
print(f"\nℹ️ INFO: {message}\n")
def print_success(self, message: str) -> None:
"""
Print a success message.
Args:
message: The success message to display
"""
if self.rich_available:
self.console.print() # Add newline before
self.console.print(Panel(message, title="✅ Success", border_style="green"))
else:
print(f"\n✅ SUCCESS: {message}\n")
def _render_image_halfblock(self, image_path: str, max_width: int = 60) -> str:
"""
Render an image as Unicode half-block characters with 24-bit ANSI colors.
Uses U+2580 (upper half block) with foreground = top pixel color and
background = bottom pixel color, so each character row encodes two image rows.
Works in any terminal that supports 24-bit ANSI colors (Windows Terminal,
gnome-terminal, etc.) with no extra dependencies beyond PIL.
Args:
image_path: Path to the image file
max_width: Maximum width in terminal columns
Returns:
Rendered ANSI string, or empty string on failure
"""
try:
import shutil
from pathlib import Path
from PIL import Image
path_obj = Path(image_path)
if not path_obj.exists():
return ""
img = Image.open(path_obj).convert("RGB")
term_w = shutil.get_terminal_size((80, 24)).columns
width = min(max_width, term_w - 4)
# Each terminal char covers 2 image rows, so height = rows * 2
aspect = img.height / img.width
height = max(2, int(width * aspect * 0.5) * 2) # ensure even
img = img.resize((width, height), Image.LANCZOS)
pixels = list(img.getdata())
lines = []
for row in range(0, height, 2):
line_parts = []
for col in range(width):
top = pixels[row * width + col]
bottom_row = row + 1
bottom = (
pixels[bottom_row * width + col]
if bottom_row < height
else (0, 0, 0)
)
fg = f"\x1b[38;2;{top[0]};{top[1]};{top[2]}m"
bg = f"\x1b[48;2;{bottom[0]};{bottom[1]};{bottom[2]}m"
line_parts.append(f"{fg}{bg}\u2580")
lines.append("".join(line_parts) + "\x1b[0m")
return "\n".join(lines)
except Exception:
return ""
def print_image(
self, image_path: str, caption: str = None, prompt_to_open: bool = False
) -> None:
"""
Display an image in terminal and optionally prompt to open in viewer.
Args:
image_path: Path to the image file
caption: Optional caption to display
prompt_to_open: If True, prompt user to open in default viewer after display
"""
import os
import sys
from pathlib import Path
path = Path(image_path)
if not path.exists():
return
if self.rich_available:
# Tier 1: term-image (Sixel/Kitty — only if installed)
term_image_ok = False
try:
from term_image.image import from_file
img = from_file(str(path))
img.set_size(width=60)
# Use plain print — Rich Panel corrupts graphics protocol escape sequences
if caption:
self.console.print(
f"[bold cyan]🖼️ {caption}[/bold cyan]", justify="center"
)
print(str(img))
self.console.print()
term_image_ok = True
except ImportError:
logger.debug(
"term-image not installed; falling back to half-block renderer"
)
except Exception as exc:
logger.debug(
"term-image failed (%s); falling back to half-block renderer", exc
)
if not term_image_ok:
# Tier 2: PIL half-block renderer (always available when PIL is installed)
rendered = self._render_image_halfblock(str(path))
if rendered:
# Use plain print — Rich Panel processing is very slow on large ANSI strings
if caption:
self.console.print(
f"[bold cyan]🖼️ {caption}[/bold cyan]", justify="center"
)
print(rendered)
print()
else:
# Tier 3: PIL metadata fallback
try:
from PIL import Image
img = Image.open(path)
info = f"[cyan]{path.name}[/cyan]\n"
info += f"[dim]Size: {img.width}x{img.height} | Format: {img.format} | File: {path.stat().st_size:,} bytes[/dim]"
if caption:
self.console.print(
Panel(
info, title=f"🖼️ {caption}", border_style="cyan"
),
justify="center",
)
else:
self.console.print(
Panel(info, border_style="cyan"), justify="center"
)
except Exception: