Spaces:
Running
Running
File size: 15,199 Bytes
399b80c | 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 | """
OpenSpace Terminal UI System
Provides real-time CLI visualization for OpenSpace execution flow.
Displays agent activities, grounding backends, and detailed logs.
Uses native ANSI colors and custom box drawing for a clean, lightweight interface.
"""
from typing import Optional, Dict, Any, List, Tuple
from datetime import datetime
from enum import Enum
import asyncio
import sys
import shutil
from openspace.utils.display import Box, BoxStyle, colorize
class AgentStatus(Enum):
"""Agent execution status"""
IDLE = "idle"
THINKING = "thinking"
EXECUTING = "executing"
WAITING = "waiting"
class OpenSpaceUI:
"""
OpenSpace Terminal UI
Provides real-time visualization of:
- Agent activities and status
- Grounding backend operations
- Execution logs
- System metrics
Design Philosophy:
- Lightweight and fast (no heavy dependencies)
- Clean ANSI-based rendering
- Minimal CPU overhead
- Easy to customize
"""
def __init__(self, enable_live: bool = True, compact: bool = False):
"""
Initialize UI
Args:
enable_live: Whether to enable live display updates
compact: Use compact layout (for smaller terminals)
"""
self.enable_live = enable_live
self.compact = compact
# Terminal dimensions
self.term_width, self.term_height = self._get_terminal_size()
# State tracking
self.agent_status: Dict[str, AgentStatus] = {}
self.agent_activities: Dict[str, List[str]] = {}
self.grounding_operations: List[Dict[str, Any]] = []
self.grounding_backends: List[Dict[str, Any]] = [] # Backend info (type, servers, etc.)
self.log_buffer: List[Tuple[str, str, datetime]] = [] # (message, level, timestamp)
# Metrics
self.metrics: Dict[str, Any] = {
"start_time": None,
"iterations": 0,
"completed_tasks": 0,
"llm_calls": 0,
"grounding_calls": 0,
}
# Live display state
self._live_running = False
self._live_task: Optional[asyncio.Task] = None
self._last_render: List[str] = []
def _get_terminal_size(self) -> Tuple[int, int]:
"""Get terminal size"""
try:
size = shutil.get_terminal_size((80, 24))
return size.columns, size.lines
except:
return 80, 24
def _clear_screen(self):
"""Clear screen"""
if self.enable_live:
# Clear entire screen and move cursor to top-left
sys.stdout.write('\033[2J\033[H')
sys.stdout.flush()
def _move_cursor_home(self):
"""Move cursor to home position"""
sys.stdout.write('\033[H')
sys.stdout.flush()
def _hide_cursor(self):
"""Hide cursor"""
sys.stdout.write('\033[?25l')
sys.stdout.flush()
def _show_cursor(self):
"""Show cursor"""
sys.stdout.write('\033[?25h')
sys.stdout.flush()
# Banner and Startup
def print_banner(self):
"""Print startup banner"""
box = Box(width=70, style=BoxStyle.ROUNDED, color='c')
print()
print(box.top_line(indent=4))
print(box.empty_line(indent=4))
# Title
title = colorize("OpenSpace", 'c', bold=True)
print(box.text_line(title, align='center', indent=4, text_color=''))
# Subtitle
subtitle = "Self-Evolving Skill Worker & Community"
print(box.text_line(subtitle, align='center', indent=4, text_color='gr'))
print(box.empty_line(indent=4))
print(box.bottom_line(indent=4))
print()
def print_initialization(self, steps: List[Tuple[str, str]]):
"""
Print initialization steps
Args:
steps: List of (component_name, status) tuples
"""
box = Box(width=70, style=BoxStyle.ROUNDED, color='bl')
print(box.text_line("Initializing Components", align='center', indent=4, text_color='c'))
print(box.separator_line(indent=4))
for component, status in steps:
icon = colorize("β", 'g') if status == "ok" else colorize("β", 'rd')
line = f"{icon} {component}"
print(box.text_line(line, indent=4))
print(box.bottom_line(indent=4))
print()
async def start_live_display(self):
"""Start live display"""
if not self.enable_live or self._live_running:
return
self._live_running = True
self.metrics["start_time"] = datetime.now()
self._clear_screen()
self._hide_cursor()
# Start update loop
self._live_task = asyncio.create_task(self._live_update_loop())
async def stop_live_display(self):
"""Stop live display"""
if not self._live_running:
return
self._live_running = False
if self._live_task:
self._live_task.cancel()
try:
await self._live_task
except asyncio.CancelledError:
pass
self._show_cursor()
print() # Add newline after live display
async def _live_update_loop(self):
"""Live update loop"""
while self._live_running:
try:
self.render()
await asyncio.sleep(2.0)
except asyncio.CancelledError:
break
except Exception as e:
print(f"UI render error: {e}")
def render(self):
"""Render entire UI"""
if not self.enable_live or not self._live_running:
return
# Clear and redraw
self._clear_screen()
lines = []
# Header
lines.extend(self._render_header())
lines.append("")
# Stack all panels vertically
lines.extend(self._render_agents())
lines.append("")
lines.extend(self._render_grounding())
lines.append("")
lines.extend(self._render_logs())
output = "\n".join(lines)
sys.stdout.write(output)
sys.stdout.flush()
def update_display(self):
"""Update display (alias for render())"""
self.render()
def _render_header(self) -> List[str]:
"""Render header section"""
lines = []
# Calculate elapsed time
elapsed = "0s"
if self.metrics["start_time"]:
delta = datetime.now() - self.metrics["start_time"]
minutes = delta.seconds // 60
seconds = delta.seconds % 60
if minutes > 0:
elapsed = f"{minutes}m{seconds}s"
else:
elapsed = f"{seconds}s"
status_text = (
f"βΆ {colorize('RUNNING', 'g')} | "
f"Time: {colorize(elapsed, 'c')} | "
f"Iter: {colorize(str(self.metrics['iterations']), 'y')} | "
f"Tasks: {colorize(str(self.metrics['completed_tasks']), 'g')} | "
f"LLM: {colorize(str(self.metrics['llm_calls']), 'bl')} | "
f"Grounding: {colorize(str(self.metrics['grounding_calls']), 'm')}"
)
lines.append(" " + status_text)
lines.append(" " + "β" * 60)
return lines
def _render_agents(self) -> List[str]:
"""Render agents section"""
lines = []
lines.append(" " + colorize("Β§ Agents", 'c', bold=True))
# Agent info
agents = [
("GroundingAgent", 'c', self.agent_status.get("GroundingAgent", AgentStatus.IDLE)),
]
for agent_name, color, status in agents:
# Status icon
status_icons = {
AgentStatus.IDLE: "β",
AgentStatus.THINKING: "β",
AgentStatus.EXECUTING: "β",
AgentStatus.WAITING: "β·",
}
icon = status_icons.get(status, "β")
# Recent activity
activities = self.agent_activities.get(agent_name, [])
activity = activities[-1][:40] if activities else "idle"
# Format line
line = f" {colorize(icon, 'y')} {colorize(agent_name, color):<20s} {activity}"
lines.append(line)
return lines
def _render_grounding(self) -> List[str]:
"""Render grounding operations section"""
lines = []
lines.append(" " + colorize("β Grounding Backends", 'c', bold=True))
# Show backend types and servers
if self.grounding_backends:
for backend_info in self.grounding_backends:
backend_name = backend_info.get("name", "unknown")
backend_type = backend_info.get("type", "unknown")
servers = backend_info.get("servers", [])
# Backend type icon
type_icons = {
"gui": "β ",
"shell": "$",
"mcp": "β",
"system": "β",
"web": "β",
}
icon = type_icons.get(backend_type, "β")
# Format backend line
if backend_type == "mcp" and servers:
servers_str = ", ".join([s[:15] for s in servers])
line = f" {icon} {colorize(backend_name, 'y')} ({backend_type}): {colorize(servers_str, 'gr')}"
else:
line = f" {icon} {colorize(backend_name, 'y')} ({backend_type})"
lines.append(line)
# Show last 3 operations
recent_ops = self.grounding_operations[-3:] if self.grounding_operations else []
if recent_ops:
lines.append(" " + colorize("Recent Operations:", 'gr'))
for op in recent_ops:
backend = op.get("backend", "unknown")
action = op.get("action", "unknown")[:40]
status = op.get("status", "pending")
# Status icon
if status == "success":
icon = colorize("β", 'g')
elif status == "pending":
icon = colorize("β³", 'y')
else:
icon = colorize("β", 'rd')
line = f" {icon} {colorize(backend, 'bl')}: {action}"
lines.append(line)
return lines
def _render_logs(self) -> List[str]:
"""Render logs section"""
lines = []
lines.append(" " + colorize("β Recent Events", 'c', bold=True))
# Show last 5 logs
recent_logs = self.log_buffer[-5:] if self.log_buffer else []
if recent_logs:
for message, level, timestamp in recent_logs:
time_str = timestamp.strftime("%H:%M:%S")
# Truncate long messages
msg_display = message[:55]
log_line = f" {colorize(time_str, 'gr')} | {msg_display}"
lines.append(log_line)
return lines
def update_agent_status(self, agent_name: str, status: AgentStatus):
"""Update agent status"""
self.agent_status[agent_name] = status
def add_agent_activity(self, agent_name: str, activity: str):
"""Add agent activity"""
if agent_name not in self.agent_activities:
self.agent_activities[agent_name] = []
self.agent_activities[agent_name].append(activity)
# Keep only last 10 activities
if len(self.agent_activities[agent_name]) > 10:
self.agent_activities[agent_name] = self.agent_activities[agent_name][-10:]
def update_grounding_backends(self, backends: List[Dict[str, Any]]):
"""
Update grounding backends information
Args:
backends: List of backend info dicts with keys:
- name: backend name
- type: backend type (gui, shell, mcp, system, web)
- servers: list of server names (for mcp)
"""
self.grounding_backends = backends
def add_grounding_operation(self, backend: str, action: str, status: str = "pending"):
"""Add grounding operation"""
self.grounding_operations.append({
"backend": backend,
"action": action,
"status": status,
"timestamp": datetime.now(),
})
self.metrics["grounding_calls"] += 1
def add_log(self, message: str, level: str = "info"):
"""Add log message"""
self.log_buffer.append((message, level, datetime.now()))
# Keep only last 100 logs
if len(self.log_buffer) > 100:
self.log_buffer = self.log_buffer[-100:]
def update_metrics(self, **kwargs):
"""Update metrics"""
self.metrics.update(kwargs)
def print_summary(self, result: Dict[str, Any]):
"""Print execution summary"""
box = Box(width=70, style=BoxStyle.ROUNDED, color='c')
print()
print(box.text_line(colorize("β Execution Summary", 'c', bold=True), align='center', indent=4, text_color=''))
print(box.separator_line(indent=4))
# Status
status = result.get("status", "unknown")
status_display = {
"completed": colorize("COMPLETED", 'g', bold=True),
"timeout": colorize("TIMEOUT", 'y', bold=True),
"error": colorize("ERROR", 'rd', bold=True),
}
status_text = status_display.get(status, status)
print(box.text_line(f" Status: {status_text}", indent=4, text_color=''))
print(box.text_line(f" Execution Time: {colorize(f'{result.get('execution_time', 0):.2f}s', 'c')}", indent=4, text_color=''))
print(box.text_line(f" Iterations: {colorize(str(result.get('iterations', 0)), 'y')}", indent=4, text_color=''))
print(box.text_line(f" Completed Tasks: {colorize(str(result.get('completed_tasks', 0)), 'g')}", indent=4, text_color=''))
if result.get('evaluation_results'):
print(box.text_line(f" Evaluations: {colorize(str(len(result['evaluation_results'])), 'bl')}", indent=4, text_color=''))
print(box.bottom_line(indent=4))
print()
def create_ui(enable_live: bool = True, compact: bool = False) -> OpenSpaceUI:
"""
Create OpenSpace UI instance
Args:
enable_live: Whether to enable live display updates
compact: Use compact layout for smaller terminals
"""
return OpenSpaceUI(enable_live=enable_live, compact=compact) |