Skip to content

Screens

TUI screens and components for the interactive interface.

Agent Details

Agent details screen showing methods and source code.

AgentDetailsScreen

Bases: Screen[None]

Screen showing detailed agent methods and source code.

Source code in src/opensymbolicai_cli/screens/agent_details.py
class AgentDetailsScreen(Screen[None]):
    """Screen showing detailed agent methods and source code."""

    CSS = """
    AgentDetailsScreen {
        layout: grid;
        grid-size: 2;
        grid-columns: 1fr 2fr;
    }

    MethodList {
        width: 100%;
        height: 100%;
        border: solid $primary;
        padding: 1;
    }

    SourceViewer {
        width: 100%;
        height: 100%;
        border: solid $secondary;
        padding: 1;
    }

    .panel-title {
        text-style: bold;
        color: $accent;
        margin-bottom: 1;
    }

    .legend {
        margin-bottom: 1;
    }

    #method-list {
        height: 1fr;
        margin-bottom: 1;
    }

    .method-name {
        padding: 0 1;
    }

    #method-info {
        height: auto;
        margin-top: 1;
        padding: 1;
        background: $surface;
    }

    #source-content {
        width: 100%;
    }

    .source-code {
        color: $text;
    }
    """

    BINDINGS = [
        Binding("escape", "back", "Back"),
        Binding("q", "back", "Back"),
    ]

    def __init__(
        self,
        agent: DiscoveredAgent,
        name: str | None = None,
        id: str | None = None,
        classes: str | None = None,
    ) -> None:
        super().__init__(name=name, id=id, classes=classes)
        self.agent = agent

    def compose(self) -> ComposeResult:
        yield Header()
        yield MethodList()
        yield SourceViewer()
        yield Footer()

    def on_mount(self) -> None:
        """Populate method list on mount."""
        method_list = self.query_one("#method-list", ListView)

        # Group methods by type
        primitives = [m for m in self.agent.methods if m.method_type == "primitive"]
        decompositions = [m for m in self.agent.methods if m.method_type == "decomposition"]

        # Add primitives first
        for method in primitives:
            method_list.append(MethodListItem(method))

        # Add decompositions
        for method in decompositions:
            method_list.append(MethodListItem(method))

        # Auto-select first method if available
        if self.agent.methods:
            method_list.index = 0
            first_method = primitives[0] if primitives else decompositions[0]
            self._show_method(first_method)

        # Update header
        self.title = f"Agent: {self.agent.name}"

    def on_list_view_highlighted(self, event: ListView.Highlighted) -> None:
        """Handle cursor movement in the method list."""
        if isinstance(event.item, MethodListItem):
            self._show_method(event.item.method)

    def _show_method(self, method: DiscoveredMethod) -> None:
        """Display method details in both panels."""
        # Update method info panel (left side, below list)
        self._update_method_info(method)

        # Update source viewer (right side)
        self._update_source_viewer(method)

    def _update_method_info(self, method: DiscoveredMethod) -> None:
        """Update the method info section below the method list."""
        method_info = self.query_one("#method-info", Static)

        inputs, return_type = _parse_signature_parts(method.signature)

        lines = []
        lines.append(f"[bold]{method.name}[/bold]")
        lines.append(f"Type: {method.method_type}")

        if method.method_type == "primitive":
            lines.append(f"Read-only: {'Yes' if method.read_only else 'No'}")
        elif method.intent:
            lines.append(f"Intent: {method.intent}")

        lines.append("")
        lines.append("[bold]Inputs:[/bold]")
        if inputs:
            for inp in inputs:
                lines.append(f"  • {inp}")
        else:
            lines.append("  [dim](none)[/dim]")

        lines.append("")
        lines.append(f"[bold]Returns:[/bold] {return_type}")

        method_info.update("\n".join(lines))

    def _update_source_viewer(self, method: DiscoveredMethod) -> None:
        """Update the source code viewer with syntax highlighting."""
        source_content = self.query_one("#source-content", Static)

        if not method.source:
            source_content.update(Text("Source code not available", style="dim"))
            return

        # Use rich Syntax for Python syntax highlighting
        syntax = Syntax(
            method.source,
            "python",
            theme="monokai",
            line_numbers=True,
            word_wrap=False,
        )
        source_content.update(syntax)

    def action_back(self) -> None:
        """Go back to main screen."""
        self.dismiss(None)

action_back()

Go back to main screen.

Source code in src/opensymbolicai_cli/screens/agent_details.py
def action_back(self) -> None:
    """Go back to main screen."""
    self.dismiss(None)

on_list_view_highlighted(event)

Handle cursor movement in the method list.

Source code in src/opensymbolicai_cli/screens/agent_details.py
def on_list_view_highlighted(self, event: ListView.Highlighted) -> None:
    """Handle cursor movement in the method list."""
    if isinstance(event.item, MethodListItem):
        self._show_method(event.item.method)

on_mount()

Populate method list on mount.

Source code in src/opensymbolicai_cli/screens/agent_details.py
def on_mount(self) -> None:
    """Populate method list on mount."""
    method_list = self.query_one("#method-list", ListView)

    # Group methods by type
    primitives = [m for m in self.agent.methods if m.method_type == "primitive"]
    decompositions = [m for m in self.agent.methods if m.method_type == "decomposition"]

    # Add primitives first
    for method in primitives:
        method_list.append(MethodListItem(method))

    # Add decompositions
    for method in decompositions:
        method_list.append(MethodListItem(method))

    # Auto-select first method if available
    if self.agent.methods:
        method_list.index = 0
        first_method = primitives[0] if primitives else decompositions[0]
        self._show_method(first_method)

    # Update header
    self.title = f"Agent: {self.agent.name}"

MethodList

Bases: Vertical

Left panel showing list of methods with their signatures.

Source code in src/opensymbolicai_cli/screens/agent_details.py
class MethodList(Vertical):
    """Left panel showing list of methods with their signatures."""

    def compose(self) -> ComposeResult:
        yield Static("Methods", classes="panel-title")
        yield Static("[dim]● primitive  ↳ decomposition[/dim]", classes="legend")
        yield ListView(id="method-list")
        yield Static("", id="method-info")

MethodListItem

Bases: ListItem

A list item representing a method.

Source code in src/opensymbolicai_cli/screens/agent_details.py
class MethodListItem(ListItem):
    """A list item representing a method."""

    def __init__(self, method: DiscoveredMethod) -> None:
        super().__init__()
        self.method = method

    def compose(self) -> ComposeResult:
        # ● for primitives (atomic action), ↳ for decompositions (breaks down into sub-steps)
        type_icon = "●" if self.method.method_type == "primitive" else "↳"
        ro_marker = " [dim](ro)[/dim]" if self.method.read_only else ""
        yield Static(f"{type_icon} {self.method.name}{ro_marker}", classes="method-name")

SourceViewer

Bases: VerticalScroll

Right panel showing full method source code.

Source code in src/opensymbolicai_cli/screens/agent_details.py
class SourceViewer(VerticalScroll):
    """Right panel showing full method source code."""

    def compose(self) -> ComposeResult:
        yield Static("Source Code", classes="panel-title")
        yield Static("Select a method to view source", id="source-content", classes="source-code")

Agent Execution

Agent execution screen for running queries against an agent.

AgentExecutionScreen

Bases: Screen[None]

Screen for executing queries against an agent.

Source code in src/opensymbolicai_cli/screens/agent_execution.py
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
class AgentExecutionScreen(Screen[None]):
    """Screen for executing queries against an agent."""

    CSS = """
    AgentExecutionScreen {
        layout: vertical;
    }

    #agent-header {
        height: auto;
        padding: 1;
        background: $surface;
        border-bottom: solid $primary;
    }

    #agent-info {
        color: $text-muted;
    }

    #main-container {
        height: 1fr;
    }

    #execution-area {
        height: 1fr;
        padding: 1;
    }

    .status-bar {
        height: auto;
        padding: 0 1;
        color: $text-muted;
    }
    """

    BINDINGS = [
        Binding("escape", "back", "Back"),
        Binding("ctrl+l", "clear", "Clear"),
        Binding("ctrl+t", "toggle_trace", "Trace"),
    ]

    def __init__(
        self,
        agent: DiscoveredAgent,
        settings: Settings,
        name: str | None = None,
        id: str | None = None,
        classes: str | None = None,
    ) -> None:
        super().__init__(name=name, id=id, classes=classes)
        self.agent = agent
        self.settings = settings
        self.agent_instance: Any = None
        self.show_plan = False
        self._loading = False
        self.last_result: OrchestrationResult | None = None
        # Mutation approval state
        self._mutation_event: threading.Event | None = None
        self._mutation_approved: bool = False

    def compose(self) -> ComposeResult:
        yield Header()
        yield Static(id="agent-header")
        yield Horizontal(
            Vertical(
                ConversationView(id="conversation"),
                QueryInput(),
                Static("", id="status-bar", classes="status-bar"),
                id="execution-area",
            ),
            TracePanel(id="trace-panel"),
            id="main-container",
        )
        yield Footer()

    def on_mount(self) -> None:
        """Initialize the screen."""
        self.title = f"Run: {self.agent.name}"

        # Update agent header
        header = self.query_one("#agent-header", Static)
        header_content = f"[bold]{self.agent.name}[/bold]"
        if self.agent.description:
            header_content += f"\n[dim]{self.agent.description}[/dim]"
        header.update(header_content)

        # Show welcome message
        conversation = self.query_one("#conversation", ConversationView)
        conversation.add_message(
            f"Agent [bold]{self.agent.name}[/bold] loaded. Type your query below.",
            "system",
        )

        # Update status
        self._update_status()

        # Focus the input
        self.query_one("#query-input", Input).focus()

        # Try to load the agent
        self._load_agent()

    def _update_status(self) -> None:
        """Update the status bar."""
        status = self.query_one("#status-bar", Static)
        provider = self.settings.default_provider or "not set"
        model = self.settings.default_model or "not set"
        plan_indicator = "[bold green]ON[/]" if self.show_plan else "[dim]OFF[/]"
        debug_indicator = "[bold green]ON[/]" if self.settings.debug_mode else "[dim]OFF[/]"
        trace_panel = self.query_one("#trace-panel", TracePanel)
        trace_indicator = "[bold green]ON[/]" if trace_panel.has_class("visible") else "[dim]OFF[/]"
        status.update(
            f"Provider: {provider} | Model: {model} | Plan: {plan_indicator} | Debug: {debug_indicator} | Trace: {trace_indicator}"
        )

    def _handle_mutation(self, context: MutationHookContext) -> str | None:
        """Handle mutation hook - called from execution thread.

        Shows a confirmation dialog and blocks until user responds.
        Returns None to allow mutation, or a rejection reason string.
        """
        # Create an event to wait for UI response
        self._mutation_event = threading.Event()
        self._mutation_approved = False

        # Schedule dialog on main thread
        self.app.call_from_thread(self._show_mutation_dialog, context)

        # Block until user responds
        self._mutation_event.wait()

        if self._mutation_approved:
            return None  # Allow mutation
        return "User aborted the mutation"

    def _show_mutation_dialog(self, context: MutationHookContext) -> None:
        """Show the mutation confirmation dialog (called on main thread)."""
        self.app.push_screen(MutationConfirmScreen(context), self._on_mutation_response)

    def _on_mutation_response(self, approved: bool | None) -> None:
        """Handle mutation dialog response."""
        self._mutation_approved = approved is True  # Treat None/False as rejection
        if self._mutation_event:
            self._mutation_event.set()

    def _load_agent(self) -> None:
        """Dynamically load and instantiate the agent."""
        conversation = self.query_one("#conversation", ConversationView)

        # Check if provider and model are configured
        if not self.settings.default_provider or not self.settings.default_model:
            conversation.add_message(
                "Provider or model not configured. Press 's' in main screen to configure settings.",
                "error",
            )
            return

        try:
            # Import the agent module dynamically
            file_path = self.agent.file_path
            module_name = file_path.stem

            # Add parent directory to path if needed
            parent_dir = str(file_path.parent)
            if parent_dir not in sys.path:
                sys.path.insert(0, parent_dir)

            spec = importlib.util.spec_from_file_location(module_name, file_path)
            if spec is None or spec.loader is None:
                conversation.add_message(f"Could not load module from {file_path}", "error")
                return

            module = importlib.util.module_from_spec(spec)
            sys.modules[module_name] = module
            spec.loader.exec_module(module)

            # Get the agent class
            agent_class = getattr(module, self.agent.class_name, None)
            if agent_class is None:
                conversation.add_message(
                    f"Could not find class {self.agent.class_name} in module", "error"
                )
                return

            # Create LLM config
            from opensymbolicai.llm import LLMConfig

            llm_config = LLMConfig(
                provider=self.settings.default_provider,
                model=self.settings.default_model,
            )

            # Instantiate the agent
            self.agent_instance = agent_class(llm=llm_config)

            # Set mutation hook on the agent's config
            self.agent_instance.config.on_mutation = self._handle_mutation

            conversation.add_message(
                f"Agent initialized with {self.settings.default_provider}/{self.settings.default_model}",
                "system",
            )

        except Exception as e:
            conversation.add_message(f"Failed to load agent: {e}", "error")

    def on_input_submitted(self, event: Input.Submitted) -> None:
        """Handle query submission."""
        if event.input.id != "query-input":
            return

        query = event.value.strip()
        if not query:
            return

        # Handle /plan command
        if query.lower() == "/plan":
            event.input.value = ""
            self._toggle_plan()
            return

        # Handle /debug command
        if query.lower() == "/debug":
            event.input.value = ""
            self._toggle_debug_mode()
            return

        # Handle /trace command
        if query.lower() == "/trace":
            event.input.value = ""
            self.action_toggle_trace()
            return

        conversation = self.query_one("#conversation", ConversationView)

        # Show user query immediately
        conversation.add_message(f"[bold]You:[/bold] {query}", "user")

        # Clear input after showing message
        event.input.value = ""

        # Check if agent is loaded
        if self.agent_instance is None:
            conversation.add_message("Agent not loaded. Check settings and try again.", "error")
            return

        # Prevent concurrent executions
        if self._loading:
            return
        self._loading = True

        # Run in background worker so UI updates immediately
        self.run_worker(self._execute_query(query), exclusive=True)

    def _toggle_debug_mode(self) -> None:
        """Toggle debug mode on/off."""
        self.settings.debug_mode = not self.settings.debug_mode
        self.settings.save()
        self._update_status()
        mode = "enabled" if self.settings.debug_mode else "disabled"
        self.notify(f"Debug mode {mode}")

    async def _execute_query(self, query: str) -> None:
        """Execute a query against the agent."""
        conversation = self.query_one("#conversation", ConversationView)

        # Update status to show processing
        status = self.query_one("#status-bar", Static)
        status.update("[yellow]Processing...[/]")

        try:
            # Run the agent in a thread pool to avoid blocking the UI
            result: OrchestrationResult = await self._run_in_thread(
                lambda: self.agent_instance.run(query)
            )

            # Store the result for trace panel
            self.last_result = result

            # Update trace panel if visible
            trace_panel = self.query_one("#trace-panel", TracePanel)
            if trace_panel.has_class("visible"):
                trace_panel.update_trace(result)

            # Show plan output if enabled
            if self.show_plan and result.plan_attempts:
                for i, attempt in enumerate(result.plan_attempts):
                    plan_code = (
                        attempt.plan_generation.extracted_code if attempt.plan_generation else ""
                    )
                    if plan_code:
                        conversation.add_message(f"[dim]--- Plan Attempt {i + 1} ---[/]", "system")
                        syntax = Syntax(plan_code, "python", theme="monokai", line_numbers=False)
                        conversation.add_message(syntax, "system")

            # Show debug info if enabled
            if self.settings.debug_mode:
                self._show_debug_info(conversation, result)

            # Show result
            if result.success:
                conversation.add_message(
                    f"[bold green]Result:[/bold green] {result.result}", "assistant"
                )
            else:
                error_msg = f"[bold red]Error:[/bold red] {result.error}"
                if result.plan:
                    error_msg += f"\n\n[dim]Plan attempted:[/dim]\n{result.plan}"
                conversation.add_message(error_msg, "error")

        except Exception as e:
            conversation.add_message(f"[bold red]Exception:[/bold red] {e}", "error")

        finally:
            # Restore status and reset loading flag
            self._loading = False
            self._update_status()

    def _show_debug_info(self, conversation: ConversationView, result: OrchestrationResult) -> None:
        """Display debug information about the execution."""
        debug_parts: list[str] = []

        # Time taken from metrics
        if result.metrics:
            metrics = result.metrics
            total_time = metrics.total_time_seconds
            debug_parts.append(
                f"[bold cyan]Time:[/] {total_time:.2f}s "
                f"(plan: {metrics.plan_time_seconds:.2f}s, exec: {metrics.execute_time_seconds:.2f}s)"
            )

            # Token usage
            tokens = metrics.plan_tokens
            total_tokens = tokens.total_tokens
            debug_parts.append(
                f"[bold cyan]Tokens:[/] {total_tokens} "
                f"(input: {tokens.input_tokens}, output: {tokens.output_tokens})"
            )

        # Plan
        if result.plan:
            debug_parts.append(f"[bold cyan]Plan:[/]\n{result.plan}")

        if debug_parts:
            debug_text = "[dim]--- Debug Info ---[/]\n" + "\n".join(debug_parts)
            conversation.add_message(debug_text, "system")

    async def _run_in_thread(self, func: Any) -> Any:
        """Run a blocking function in a thread pool."""
        import asyncio
        from concurrent.futures import ThreadPoolExecutor

        loop = asyncio.get_event_loop()
        with ThreadPoolExecutor() as executor:
            return await loop.run_in_executor(executor, func)

    def action_back(self) -> None:
        """Go back to main screen."""
        self.dismiss(None)

    def action_clear(self) -> None:
        """Clear the conversation."""
        conversation = self.query_one("#conversation", ConversationView)
        conversation.clear_messages()
        conversation.add_message(
            f"Agent [bold]{self.agent.name}[/bold] ready. Type your query below.",
            "system",
        )

    def _toggle_plan(self) -> None:
        """Toggle plan visibility."""
        self.show_plan = not self.show_plan
        self._update_status()
        mode = "shown" if self.show_plan else "hidden"
        self.notify(f"Plan {mode}")

    def action_toggle_trace(self) -> None:
        """Toggle trace panel visibility."""
        trace_panel = self.query_one("#trace-panel", TracePanel)
        if trace_panel.has_class("visible"):
            trace_panel.remove_class("visible")
            self.notify("Trace panel hidden")
        else:
            trace_panel.add_class("visible")
            trace_panel.update_trace(self.last_result)
            self.notify("Trace panel shown")
        self._update_status()

action_back()

Go back to main screen.

Source code in src/opensymbolicai_cli/screens/agent_execution.py
def action_back(self) -> None:
    """Go back to main screen."""
    self.dismiss(None)

action_clear()

Clear the conversation.

Source code in src/opensymbolicai_cli/screens/agent_execution.py
def action_clear(self) -> None:
    """Clear the conversation."""
    conversation = self.query_one("#conversation", ConversationView)
    conversation.clear_messages()
    conversation.add_message(
        f"Agent [bold]{self.agent.name}[/bold] ready. Type your query below.",
        "system",
    )

action_toggle_trace()

Toggle trace panel visibility.

Source code in src/opensymbolicai_cli/screens/agent_execution.py
def action_toggle_trace(self) -> None:
    """Toggle trace panel visibility."""
    trace_panel = self.query_one("#trace-panel", TracePanel)
    if trace_panel.has_class("visible"):
        trace_panel.remove_class("visible")
        self.notify("Trace panel hidden")
    else:
        trace_panel.add_class("visible")
        trace_panel.update_trace(self.last_result)
        self.notify("Trace panel shown")
    self._update_status()

on_input_submitted(event)

Handle query submission.

Source code in src/opensymbolicai_cli/screens/agent_execution.py
def on_input_submitted(self, event: Input.Submitted) -> None:
    """Handle query submission."""
    if event.input.id != "query-input":
        return

    query = event.value.strip()
    if not query:
        return

    # Handle /plan command
    if query.lower() == "/plan":
        event.input.value = ""
        self._toggle_plan()
        return

    # Handle /debug command
    if query.lower() == "/debug":
        event.input.value = ""
        self._toggle_debug_mode()
        return

    # Handle /trace command
    if query.lower() == "/trace":
        event.input.value = ""
        self.action_toggle_trace()
        return

    conversation = self.query_one("#conversation", ConversationView)

    # Show user query immediately
    conversation.add_message(f"[bold]You:[/bold] {query}", "user")

    # Clear input after showing message
    event.input.value = ""

    # Check if agent is loaded
    if self.agent_instance is None:
        conversation.add_message("Agent not loaded. Check settings and try again.", "error")
        return

    # Prevent concurrent executions
    if self._loading:
        return
    self._loading = True

    # Run in background worker so UI updates immediately
    self.run_worker(self._execute_query(query), exclusive=True)

on_mount()

Initialize the screen.

Source code in src/opensymbolicai_cli/screens/agent_execution.py
def on_mount(self) -> None:
    """Initialize the screen."""
    self.title = f"Run: {self.agent.name}"

    # Update agent header
    header = self.query_one("#agent-header", Static)
    header_content = f"[bold]{self.agent.name}[/bold]"
    if self.agent.description:
        header_content += f"\n[dim]{self.agent.description}[/dim]"
    header.update(header_content)

    # Show welcome message
    conversation = self.query_one("#conversation", ConversationView)
    conversation.add_message(
        f"Agent [bold]{self.agent.name}[/bold] loaded. Type your query below.",
        "system",
    )

    # Update status
    self._update_status()

    # Focus the input
    self.query_one("#query-input", Input).focus()

    # Try to load the agent
    self._load_agent()

ConversationView

Bases: VerticalScroll

Scrollable container for conversation messages.

Source code in src/opensymbolicai_cli/screens/agent_execution.py
class ConversationView(VerticalScroll):
    """Scrollable container for conversation messages."""

    DEFAULT_CSS = """
    ConversationView {
        height: 1fr;
        border: solid $secondary;
        padding: 1;
    }

    ConversationView > #conversation-content {
        height: auto;
    }
    """

    def compose(self) -> ComposeResult:
        yield Vertical(id="conversation-content")

    def add_message(self, content: str | Text | Syntax, message_type: str = "assistant") -> None:
        """Add a message to the conversation.

        Args:
            content: The message content (string, Rich Text, or Syntax).
            message_type: One of "user", "assistant", "error", "system".
        """
        conversation = self.query_one("#conversation-content", Vertical)
        message = MessageDisplay(content, classes=f"{message_type}-message")
        conversation.mount(message)
        self.scroll_end(animate=False)

    def clear_messages(self) -> None:
        """Clear all messages from the conversation."""
        conversation = self.query_one("#conversation-content", Vertical)
        conversation.remove_children()

add_message(content, message_type='assistant')

Add a message to the conversation.

Parameters:

Name Type Description Default
content str | Text | Syntax

The message content (string, Rich Text, or Syntax).

required
message_type str

One of "user", "assistant", "error", "system".

'assistant'
Source code in src/opensymbolicai_cli/screens/agent_execution.py
def add_message(self, content: str | Text | Syntax, message_type: str = "assistant") -> None:
    """Add a message to the conversation.

    Args:
        content: The message content (string, Rich Text, or Syntax).
        message_type: One of "user", "assistant", "error", "system".
    """
    conversation = self.query_one("#conversation-content", Vertical)
    message = MessageDisplay(content, classes=f"{message_type}-message")
    conversation.mount(message)
    self.scroll_end(animate=False)

clear_messages()

Clear all messages from the conversation.

Source code in src/opensymbolicai_cli/screens/agent_execution.py
def clear_messages(self) -> None:
    """Clear all messages from the conversation."""
    conversation = self.query_one("#conversation-content", Vertical)
    conversation.remove_children()

MessageDisplay

Bases: Static

A single message in the conversation.

Source code in src/opensymbolicai_cli/screens/agent_execution.py
class MessageDisplay(Static):
    """A single message in the conversation."""

    DEFAULT_CSS = """
    MessageDisplay {
        width: 100%;
        padding: 1;
        margin-bottom: 1;
    }

    MessageDisplay.user-message {
        background: $primary-darken-2;
        border-left: thick $primary;
    }

    MessageDisplay.assistant-message {
        background: $surface;
        border-left: thick $success;
    }

    MessageDisplay.error-message {
        background: $error 20%;
        border-left: thick $error;
    }

    MessageDisplay.system-message {
        background: $surface;
        border-left: thick $warning;
        color: $text-muted;
    }
    """

MutationConfirmScreen

Bases: ModalScreen[bool]

Modal dialog to confirm or abort a mutation operation.

Source code in src/opensymbolicai_cli/screens/agent_execution.py
class MutationConfirmScreen(ModalScreen[bool]):
    """Modal dialog to confirm or abort a mutation operation."""

    CSS = """
    MutationConfirmScreen {
        align: center middle;
    }

    #mutation-dialog {
        width: 60;
        height: auto;
        padding: 1 2;
        background: $surface;
        border: thick $warning;
    }

    #mutation-title {
        text-style: bold;
        color: $warning;
        text-align: center;
        margin-bottom: 1;
    }

    #mutation-details {
        height: auto;
        padding: 1;
        margin-bottom: 1;
        background: $surface-darken-1;
        border-left: thick $accent;
    }

    #mutation-method {
        color: $success;
        text-style: bold;
    }

    #mutation-args {
        color: $text-muted;
        margin-top: 1;
    }

    #mutation-buttons {
        height: 3;
        align: center middle;
    }

    #mutation-buttons Button {
        margin: 0 1;
    }
    """

    BINDINGS = [
        Binding("enter", "continue", "Continue"),
        Binding("escape", "abort", "Abort"),
    ]

    def __init__(
        self,
        context: MutationHookContext,
        name: str | None = None,
        id: str | None = None,
        classes: str | None = None,
    ) -> None:
        super().__init__(name=name, id=id, classes=classes)
        self.context = context

    def compose(self) -> ComposeResult:
        with Vertical(id="mutation-dialog"):
            yield Static("⚠️  Mutation Detected", id="mutation-title")
            with Vertical(id="mutation-details"):
                yield Static(f"Method: {self.context.method_name}()", id="mutation-method")
                args_str = ", ".join(f"{k}={v!r}" for k, v in self.context.args.items())
                if args_str:
                    yield Static(f"Args: {args_str}", id="mutation-args")
                else:
                    yield Static("Args: (none)", id="mutation-args")
            with Horizontal(id="mutation-buttons"):
                yield Button("Continue", variant="success", id="continue-btn")
                yield Button("Abort", variant="error", id="abort-btn")

    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Handle button presses."""
        if event.button.id == "continue-btn":
            self.action_continue()
        elif event.button.id == "abort-btn":
            self.action_abort()

    def action_continue(self) -> None:
        """Allow the mutation to proceed."""
        self.dismiss(True)

    def action_abort(self) -> None:
        """Abort the mutation."""
        self.dismiss(False)

action_abort()

Abort the mutation.

Source code in src/opensymbolicai_cli/screens/agent_execution.py
def action_abort(self) -> None:
    """Abort the mutation."""
    self.dismiss(False)

action_continue()

Allow the mutation to proceed.

Source code in src/opensymbolicai_cli/screens/agent_execution.py
def action_continue(self) -> None:
    """Allow the mutation to proceed."""
    self.dismiss(True)

on_button_pressed(event)

Handle button presses.

Source code in src/opensymbolicai_cli/screens/agent_execution.py
def on_button_pressed(self, event: Button.Pressed) -> None:
    """Handle button presses."""
    if event.button.id == "continue-btn":
        self.action_continue()
    elif event.button.id == "abort-btn":
        self.action_abort()

QueryInput

Bases: Static

Input area for queries.

Source code in src/opensymbolicai_cli/screens/agent_execution.py
class QueryInput(Static):
    """Input area for queries."""

    DEFAULT_CSS = """
    QueryInput {
        height: auto;
        padding: 1;
        border: solid $primary;
    }

    QueryInput > Static {
        margin-bottom: 1;
    }

    QueryInput > Input {
        width: 100%;
    }
    """

    def compose(self) -> ComposeResult:
        yield Static("[bold]Enter your query:[/bold]")
        yield Input(placeholder="Type your query and press Enter...", id="query-input")

TracePanel

Bases: VerticalScroll

Side panel for displaying execution trace.

Source code in src/opensymbolicai_cli/screens/agent_execution.py
class TracePanel(VerticalScroll):
    """Side panel for displaying execution trace."""

    DEFAULT_CSS = """
    TracePanel {
        width: 50;
        height: 100%;
        border-left: solid $secondary;
        background: $surface;
        padding: 1;
        display: none;
    }

    TracePanel.visible {
        display: block;
    }

    TracePanel .trace-header {
        text-style: bold;
        color: $primary;
        margin-bottom: 1;
    }

    TracePanel #trace-content {
        height: auto;
    }

    TracePanel .trace-step {
        margin-bottom: 1;
        padding: 1;
        background: $surface-darken-1;
        border-left: thick $accent;
    }

    TracePanel .trace-step.failed {
        border-left: thick $error;
        background: $error 10%;
    }

    TracePanel .step-header {
        color: $text;
        text-style: bold;
    }

    TracePanel .step-statement {
        color: $success;
        margin-top: 0;
    }

    TracePanel .step-result {
        color: $text-muted;
        margin-top: 0;
    }

    TracePanel .step-time {
        color: $text-disabled;
    }

    TracePanel .no-trace {
        color: $text-muted;
        text-style: italic;
    }
    """

    def compose(self) -> ComposeResult:
        yield Static("[bold]Execution Trace[/bold]", classes="trace-header")
        yield Vertical(id="trace-content")

    def update_trace(self, result: OrchestrationResult | None) -> None:
        """Update the trace panel with execution trace from the result."""
        content = self.query_one("#trace-content", Vertical)
        content.remove_children()

        if result is None or result.trace is None:
            content.mount(
                Static("[dim]No trace available. Run a query first.[/dim]", classes="no-trace")
            )
            return

        trace = result.trace
        for step in trace.steps:
            step_class = "trace-step" if step.success else "trace-step failed"

            # Build step content as rich text
            header_text = f"[bold]Step {step.step_number}[/bold]"
            if step.primitive_called:
                header_text += f" - {step.primitive_called}()"

            # Statement
            statement = step.statement
            if len(statement) > 60:
                statement = statement[:57] + "..."

            # Result
            if step.success:
                result_str = str(step.result_value)
                if len(result_str) > 50:
                    result_str = result_str[:47] + "..."
                result_line = f"→ {result_str}"
            else:
                result_line = f"[red]✗ {step.error}[/]"

            # Combine into single content block
            step_content = f"{header_text}\n[green]{statement}[/]\n{result_line}\n[dim]{step.time_seconds:.3f}s[/]"
            content.mount(Static(step_content, classes=step_class))

        # Total time
        content.mount(Static(f"\n[bold]Total: {trace.total_time_seconds:.3f}s[/bold]"))

update_trace(result)

Update the trace panel with execution trace from the result.

Source code in src/opensymbolicai_cli/screens/agent_execution.py
def update_trace(self, result: OrchestrationResult | None) -> None:
    """Update the trace panel with execution trace from the result."""
    content = self.query_one("#trace-content", Vertical)
    content.remove_children()

    if result is None or result.trace is None:
        content.mount(
            Static("[dim]No trace available. Run a query first.[/dim]", classes="no-trace")
        )
        return

    trace = result.trace
    for step in trace.steps:
        step_class = "trace-step" if step.success else "trace-step failed"

        # Build step content as rich text
        header_text = f"[bold]Step {step.step_number}[/bold]"
        if step.primitive_called:
            header_text += f" - {step.primitive_called}()"

        # Statement
        statement = step.statement
        if len(statement) > 60:
            statement = statement[:57] + "..."

        # Result
        if step.success:
            result_str = str(step.result_value)
            if len(result_str) > 50:
                result_str = result_str[:47] + "..."
            result_line = f"→ {result_str}"
        else:
            result_line = f"[red]✗ {step.error}[/]"

        # Combine into single content block
        step_content = f"{header_text}\n[green]{statement}[/]\n{result_line}\n[dim]{step.time_seconds:.3f}s[/]"
        content.mount(Static(step_content, classes=step_class))

    # Total time
    content.mount(Static(f"\n[bold]Total: {trace.total_time_seconds:.3f}s[/bold]"))

Settings

Settings screen for configuring the agent runner.

SettingsScreen

Bases: Screen[Settings | None]

Screen for configuring application settings.

Source code in src/opensymbolicai_cli/screens/settings.py
class SettingsScreen(Screen[Settings | None]):
    """Screen for configuring application settings."""

    CSS = """
    SettingsScreen {
        layout: vertical;
    }

    #settings-container {
        width: 100%;
        height: 1fr;
        padding: 1 2;
    }

    .section-title {
        text-style: bold;
        color: $accent;
        margin: 1 0;
    }

    .section {
        height: auto;
        margin-bottom: 1;
        padding: 1;
        border: solid $surface;
        width: 100%;
    }

    #folder-row {
        height: 3;
        width: 100%;
    }

    #folder-row Label {
        width: 16;
        height: 3;
        content-align: left middle;
    }

    #current-folder {
        width: 1fr;
        height: 3;
        padding: 0 1;
        color: $success;
        background: $surface;
        content-align: left middle;
    }

    #browse-btn {
        margin-left: 1;
    }

    #folder-tree-container {
        height: 20;
        margin-top: 1;
    }

    #folder-tree {
        height: 100%;
    }

    #provider-section {
        height: auto;
    }

    .form-row {
        height: 3;
        margin: 1 0;
        width: 100%;
    }

    .form-row Label {
        width: 16;
        height: 3;
        content-align: left middle;
    }

    .form-row Select {
        width: 1fr;
    }

    #button-row {
        height: 3;
        margin-top: 1;
        align: center middle;
    }

    #button-row Button {
        margin: 0 1;
    }
    """

    BINDINGS = [
        ("escape", "cancel", "Cancel"),
        ("ctrl+s", "save", "Save"),
    ]

    def __init__(
        self,
        settings: Settings | None = None,
        name: str | None = None,
        id: str | None = None,
        classes: str | None = None,
    ) -> None:
        super().__init__(name=name, id=id, classes=classes)
        self.settings = settings or Settings()
        self._selected_folder: Path | None = self.settings.agents_folder

    def compose(self) -> ComposeResult:
        yield Header()
        with Container(id="settings-container"):
            yield Static("Settings", classes="section-title")

            with Vertical(id="folder-section", classes="section"):
                with Horizontal(id="folder-row"):
                    yield Label("Agents Folder:")
                    current = (
                        str(self.settings.agents_folder)
                        if self.settings.agents_folder
                        else "Not set"
                    )
                    yield Static(current, id="current-folder")
                    yield Button("Browse", id="browse-btn")
                with Container(id="folder-tree-container"):
                    yield DirectoryTree(Path.home(), id="folder-tree")

            with Vertical(id="provider-section", classes="section"):
                yield Label("Inference Settings:")
                with Horizontal(classes="form-row"):
                    yield Label("Provider:")
                    yield Select(
                        [(p, p) for p in list_providers()],
                        value=self.settings.default_provider,
                        id="provider-select",
                    )
                with Horizontal(classes="form-row"):
                    yield Label("Model:")
                    yield Select[str](
                        [("Loading...", "")],
                        value="",
                        id="model-select",
                    )

            with Horizontal(id="button-row"):
                yield Button("Save", variant="primary", id="save-btn")
                yield Button("Cancel", variant="default", id="cancel-btn")

        yield Footer()

    def on_mount(self) -> None:
        """Load models when screen mounts."""
        # Hide folder tree initially
        self.query_one("#folder-tree-container").display = False
        # Load models
        provider = self.settings.default_provider
        self._load_models_for_provider(provider)

    def on_directory_tree_directory_selected(self, event: DirectoryTree.DirectorySelected) -> None:
        """Handle folder selection."""
        self._selected_folder = event.path
        current_folder = self.query_one("#current-folder", Static)
        current_folder.update(str(event.path))
        # Hide the tree after selection
        self.query_one("#folder-tree-container").display = False
        browse_btn = self.query_one("#browse-btn", Button)
        browse_btn.label = "Browse"

    @on(Select.Changed, "#provider-select")
    def on_provider_changed(self, event: Select.Changed) -> None:
        """Handle provider selection changes."""
        if event.value != Select.BLANK:
            self._load_models_for_provider(str(event.value))

    @work(exclusive=True, thread=True)
    def _load_models_for_provider(self, provider: str) -> None:
        """Load available models for the selected provider."""
        import asyncio

        self._set_model_options([("Loading...", "loading")])

        try:
            # Run the async fetch in the thread
            models = asyncio.run(fetch_models_for_provider(provider))
            if models:
                options: list[SelectOption] = [(m, m) for m in models]
                self.app.call_from_thread(self._set_model_options, options)
                # Set the value after options are set
                if self.settings.default_model in models:
                    self.app.call_from_thread(self._set_model_value, self.settings.default_model)
                else:
                    self.app.call_from_thread(self._set_model_value, models[0])
            else:
                self.app.call_from_thread(self._set_model_options, [("No models available", "")])
        except ValueError as e:
            # API key not set
            error_msg = str(e)
            self.app.call_from_thread(self._set_model_options, [(f"Error: {error_msg}", "")])
            self.app.call_from_thread(
                self.notify, f"Set {error_msg.upper()} environment variable", severity="error"
            )
        except Exception as e:
            self.app.call_from_thread(self._set_model_options, [(f"Error: {e}", "")])
            self.app.call_from_thread(self.notify, f"Error loading models: {e}", severity="error")

    def _set_model_options(self, options: list[SelectOption]) -> None:
        """Set model select options (must be called from main thread)."""
        model_select = self.query_one("#model-select", Select)
        model_select.set_options(options)

    def _set_model_value(self, value: str) -> None:
        """Set model select value (must be called from main thread)."""
        model_select = self.query_one("#model-select", Select)
        model_select.value = value

    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Handle button presses."""
        if event.button.id == "save-btn":
            self.action_save()
        elif event.button.id == "cancel-btn":
            self.action_cancel()
        elif event.button.id == "browse-btn":
            self._toggle_folder_tree()

    def _toggle_folder_tree(self) -> None:
        """Toggle folder tree visibility."""
        container = self.query_one("#folder-tree-container")
        browse_btn = self.query_one("#browse-btn", Button)
        container.display = not container.display
        browse_btn.label = "Hide" if container.display else "Browse"

    def action_save(self) -> None:
        """Save settings and dismiss screen."""
        provider_select = self.query_one("#provider-select", Select)
        model_select = self.query_one("#model-select", Select)

        provider = str(provider_select.value) if provider_select.value != Select.BLANK else "ollama"
        model = str(model_select.value) if model_select.value != Select.BLANK else ""

        settings = Settings(
            agents_folder=self._selected_folder,
            default_provider=provider,
            default_model=model,
        )
        self.dismiss(settings)

    def action_cancel(self) -> None:
        """Cancel and dismiss screen."""
        self.dismiss(None)

action_cancel()

Cancel and dismiss screen.

Source code in src/opensymbolicai_cli/screens/settings.py
def action_cancel(self) -> None:
    """Cancel and dismiss screen."""
    self.dismiss(None)

action_save()

Save settings and dismiss screen.

Source code in src/opensymbolicai_cli/screens/settings.py
def action_save(self) -> None:
    """Save settings and dismiss screen."""
    provider_select = self.query_one("#provider-select", Select)
    model_select = self.query_one("#model-select", Select)

    provider = str(provider_select.value) if provider_select.value != Select.BLANK else "ollama"
    model = str(model_select.value) if model_select.value != Select.BLANK else ""

    settings = Settings(
        agents_folder=self._selected_folder,
        default_provider=provider,
        default_model=model,
    )
    self.dismiss(settings)

on_button_pressed(event)

Handle button presses.

Source code in src/opensymbolicai_cli/screens/settings.py
def on_button_pressed(self, event: Button.Pressed) -> None:
    """Handle button presses."""
    if event.button.id == "save-btn":
        self.action_save()
    elif event.button.id == "cancel-btn":
        self.action_cancel()
    elif event.button.id == "browse-btn":
        self._toggle_folder_tree()

on_directory_tree_directory_selected(event)

Handle folder selection.

Source code in src/opensymbolicai_cli/screens/settings.py
def on_directory_tree_directory_selected(self, event: DirectoryTree.DirectorySelected) -> None:
    """Handle folder selection."""
    self._selected_folder = event.path
    current_folder = self.query_one("#current-folder", Static)
    current_folder.update(str(event.path))
    # Hide the tree after selection
    self.query_one("#folder-tree-container").display = False
    browse_btn = self.query_one("#browse-btn", Button)
    browse_btn.label = "Browse"

on_mount()

Load models when screen mounts.

Source code in src/opensymbolicai_cli/screens/settings.py
def on_mount(self) -> None:
    """Load models when screen mounts."""
    # Hide folder tree initially
    self.query_one("#folder-tree-container").display = False
    # Load models
    provider = self.settings.default_provider
    self._load_models_for_provider(provider)

on_provider_changed(event)

Handle provider selection changes.

Source code in src/opensymbolicai_cli/screens/settings.py
@on(Select.Changed, "#provider-select")
def on_provider_changed(self, event: Select.Changed) -> None:
    """Handle provider selection changes."""
    if event.value != Select.BLANK:
        self._load_models_for_provider(str(event.value))