Documentation
¶
Index ¶
- Variables
- func BaseStyle() lipgloss.Style
- func CreateBadge(text string, color lipgloss.AdaptiveColor) string
- func CreateGradientText(text string, startColor, endColor lipgloss.AdaptiveColor) string
- func CreateProgressBar(width int, percentage float64, theme Theme) string
- func CreateSeparator(width int, char string, color lipgloss.AdaptiveColor) string
- func EstimateTokens(text string) int
- func FormatCompactLine(symbol, label, content string, ...) string
- func GetAllCommandNames() []string
- func GetMarkdownRenderer(width int) *glamour.TermRenderer
- func SetTheme(theme Theme)
- func StyleCard(width int, theme Theme) lipgloss.Style
- func StyleCompactContent(color lipgloss.AdaptiveColor) lipgloss.Style
- func StyleCompactLabel(color lipgloss.AdaptiveColor) lipgloss.Style
- func StyleCompactSymbol(symbol string, color lipgloss.AdaptiveColor) lipgloss.Style
- func StyleError(theme Theme) lipgloss.Style
- func StyleHeader(theme Theme) lipgloss.Style
- func StyleInfo(theme Theme) lipgloss.Style
- func StyleMuted(theme Theme) lipgloss.Style
- func StyleSubheader(theme Theme) lipgloss.Style
- func StyleSuccess(theme Theme) lipgloss.Style
- func StyleWarning(theme Theme) lipgloss.Style
- func WithAlign(align lipgloss.Position) renderingOption
- func WithBorderColor(color lipgloss.AdaptiveColor) renderingOption
- func WithFullWidth() renderingOption
- func WithMarginBottom(margin int) renderingOption
- func WithMarginTop(margin int) renderingOption
- func WithPaddingBottom(padding int) renderingOption
- func WithPaddingLeft(padding int) renderingOption
- func WithPaddingRight(padding int) renderingOption
- func WithPaddingTop(padding int) renderingOption
- func WithWidth(width int) renderingOption
- type AgentInterface
- type CLI
- func (c *CLI) ClearMessages()
- func (c *CLI) CreateCallbackHandler() callbacks.Handler
- func (c *CLI) DisplayAssistantMessage(message string) error
- func (c *CLI) DisplayAssistantMessageWithModel(message, modelName string) error
- func (c *CLI) DisplayCancellation()
- func (c *CLI) DisplayDebugConfig(config map[string]any)
- func (c *CLI) DisplayDebugMessage(message string)
- func (c *CLI) DisplayError(err error)
- func (c *CLI) DisplayHelp()
- func (c *CLI) DisplayInfo(message string)
- func (c *CLI) DisplayServers(servers []string)
- func (c *CLI) DisplayToolCallMessage(toolName, toolArgs string)
- func (c *CLI) DisplayToolMessage(toolName, toolArgs, toolResult string, isError bool)
- func (c *CLI) DisplayTools(tools []string)
- func (c *CLI) DisplayUsageAfterResponse()
- func (c *CLI) DisplayUsageStats()
- func (c *CLI) DisplayUserMessage(message string)
- func (c *CLI) GetDebugLogger() *CLIDebugLogger
- func (c *CLI) GetPrompt() (string, error)
- func (c *CLI) HandleSlashCommand(input string, servers []string, tools []string) SlashCommandResult
- func (c *CLI) IsSlashCommand(input string) bool
- func (c *CLI) ResetUsageStats()
- func (c *CLI) SetModelName(modelName string)
- func (c *CLI) SetUsageTracker(tracker *UsageTracker)
- func (c *CLI) ShowSpinner(message string, action func() error) error
- func (c *CLI) StartStreamingMessage(modelName string)
- func (c *CLI) UpdateStreamingMessage(content string)
- func (c *CLI) UpdateUsage(inputText, outputText string)
- func (c *CLI) UpdateUsageFromResponse(response *schema.Message, inputText string)
- type CLIDebugLogger
- type CLISetupOptions
- type CompactRenderer
- func (r *CompactRenderer) RenderAssistantMessage(content string, timestamp time.Time, modelName string) UIMessage
- func (r *CompactRenderer) RenderDebugConfigMessage(config map[string]any, timestamp time.Time) UIMessage
- func (r *CompactRenderer) RenderDebugMessage(message string, timestamp time.Time) UIMessage
- func (r *CompactRenderer) RenderErrorMessage(errorMsg string, timestamp time.Time) UIMessage
- func (r *CompactRenderer) RenderSystemMessage(content string, timestamp time.Time) UIMessage
- func (r *CompactRenderer) RenderToolCallMessage(toolName, toolArgs string, timestamp time.Time) UIMessage
- func (r *CompactRenderer) RenderToolMessage(toolName, toolArgs, toolResult string, isError bool) UIMessage
- func (r *CompactRenderer) RenderUserMessage(content string, timestamp time.Time) UIMessage
- func (r *CompactRenderer) SetWidth(width int)
- type FuzzyMatch
- type MessageContainer
- func (c *MessageContainer) AddMessage(msg UIMessage)
- func (c *MessageContainer) Clear()
- func (c *MessageContainer) Render() string
- func (c *MessageContainer) SetModelName(modelName string)
- func (c *MessageContainer) SetSize(width, height int)
- func (c *MessageContainer) UpdateLastMessage(content string)
- type MessageRenderer
- func (r *MessageRenderer) RenderAssistantMessage(content string, timestamp time.Time, modelName string) UIMessage
- func (r *MessageRenderer) RenderDebugConfigMessage(config map[string]any, timestamp time.Time) UIMessage
- func (r *MessageRenderer) RenderDebugMessage(message string, timestamp time.Time) UIMessage
- func (r *MessageRenderer) RenderErrorMessage(errorMsg string, timestamp time.Time) UIMessage
- func (r *MessageRenderer) RenderSystemMessage(content string, timestamp time.Time) UIMessage
- func (r *MessageRenderer) RenderToolCallMessage(toolName, toolArgs string, timestamp time.Time) UIMessage
- func (r *MessageRenderer) RenderToolMessage(toolName, toolArgs, toolResult string, isError bool) UIMessage
- func (r *MessageRenderer) RenderUserMessage(content string, timestamp time.Time) UIMessage
- func (r *MessageRenderer) SetWidth(width int)
- type MessageType
- type SessionStats
- type SlashCommand
- type SlashCommandInput
- type SlashCommandResult
- type Spinner
- type Theme
- type UIMessage
- type UsageStats
- type UsageTracker
- func (ut *UsageTracker) EstimateAndUpdateUsage(inputText, outputText string)
- func (ut *UsageTracker) EstimateAndUpdateUsageFromText(inputText, outputText string)
- func (ut *UsageTracker) GetLastRequestStats() *UsageStats
- func (ut *UsageTracker) GetSessionStats() SessionStats
- func (ut *UsageTracker) RenderUsageInfo() string
- func (ut *UsageTracker) Reset()
- func (ut *UsageTracker) SetWidth(width int)
- func (ut *UsageTracker) UpdateUsage(inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens int)
Constants ¶
This section is empty.
Variables ¶
var SlashCommands = []SlashCommand{ { Name: "/help", Description: "Show available commands and usage information", Category: "Info", Aliases: []string{"/h", "/?"}, }, { Name: "/tools", Description: "List all available MCP tools", Category: "Info", Aliases: []string{"/t"}, }, { Name: "/servers", Description: "Show connected MCP servers", Category: "Info", Aliases: []string{"/s"}, }, { Name: "/clear", Description: "Clear conversation and start fresh", Category: "System", Aliases: []string{"/c", "/cls"}, }, { Name: "/usage", Description: "Show token usage statistics", Category: "Info", Aliases: []string{"/u"}, }, { Name: "/reset-usage", Description: "Reset usage statistics", Category: "System", Aliases: []string{"/ru"}, }, { Name: "/quit", Description: "Exit the application", Category: "System", Aliases: []string{"/q", "/exit"}, }, }
SlashCommands provides the global registry of all available slash commands in the application. Commands are organized by category (Info, System) and include their primary names, descriptions, and alternative aliases.
Functions ¶
func BaseStyle ¶
BaseStyle returns a new, empty lipgloss style that can be customized with additional styling methods. This serves as the foundation for building more complex styled components.
func CreateBadge ¶ added in v0.17.0
func CreateBadge(text string, color lipgloss.AdaptiveColor) string
CreateBadge generates a styled badge or label with inverted colors (text on colored background) for highlighting important tags, statuses, or categories.
func CreateGradientText ¶ added in v0.17.0
func CreateGradientText(text string, startColor, endColor lipgloss.AdaptiveColor) string
CreateGradientText creates styled text with a gradient-like effect. Currently implements a simplified version using the start color only, as true gradients require more complex terminal capabilities.
func CreateProgressBar ¶ added in v0.17.0
CreateProgressBar generates a visual progress bar with filled and empty segments based on the percentage complete. The bar uses Unicode block characters for smooth appearance and theme colors to indicate progress.
func CreateSeparator ¶ added in v0.17.0
func CreateSeparator(width int, char string, color lipgloss.AdaptiveColor) string
CreateSeparator generates a horizontal separator line with the specified width, character, and color. Useful for visually dividing sections of content in the UI.
func EstimateTokens ¶ added in v0.14.0
EstimateTokens provides a rough estimate of the number of tokens in the given text. This uses a simple heuristic of approximately 4 characters per token, which is a reasonable approximation for most models but not precise. Actual token counts may vary significantly based on the specific tokenizer used by each model.
func FormatCompactLine ¶ added in v0.19.0
func FormatCompactLine(symbol, label, content string, symbolColor, labelColor, contentColor lipgloss.AdaptiveColor) string
FormatCompactLine assembles a complete compact mode message line with consistent spacing and styling. Combines a symbol, fixed-width label, and content with their respective colors to create a uniform appearance across all message types.
func GetAllCommandNames ¶ added in v0.21.0
func GetAllCommandNames() []string
GetAllCommandNames returns a complete list of all command names and their aliases. This is useful for command completion, validation, and help display. The returned slice contains both primary command names and all alternative aliases.
func GetMarkdownRenderer ¶
func GetMarkdownRenderer(width int) *glamour.TermRenderer
GetMarkdownRenderer creates and returns a configured glamour.TermRenderer for rendering markdown content with syntax highlighting and proper formatting. The renderer is customized with our theme colors and adapted to the specified width.
func SetTheme ¶ added in v0.17.0
func SetTheme(theme Theme)
SetTheme updates the global UI theme, affecting all subsequent rendering operations. This allows runtime theme switching for different visual preferences.
func StyleCard ¶ added in v0.17.0
StyleCard creates a lipgloss style for card-like containers with rounded borders, padding, and appropriate width. Used for grouping related content in a visually distinct box.
func StyleCompactContent ¶ added in v0.19.0
func StyleCompactContent(color lipgloss.AdaptiveColor) lipgloss.Style
StyleCompactContent creates a simple lipgloss style for message content in compact mode, applying only color without additional formatting.
func StyleCompactLabel ¶ added in v0.19.0
func StyleCompactLabel(color lipgloss.AdaptiveColor) lipgloss.Style
StyleCompactLabel creates a lipgloss style for message labels in compact mode with fixed width for alignment and bold colored text for readability.
func StyleCompactSymbol ¶ added in v0.19.0
func StyleCompactSymbol(symbol string, color lipgloss.AdaptiveColor) lipgloss.Style
StyleCompactSymbol creates a lipgloss style for message type indicators in compact mode, using bold colored text to distinguish different message categories.
func StyleError ¶ added in v0.17.0
StyleError creates a lipgloss style for error messages using red colors with bold text to ensure visibility of problems or failures.
func StyleHeader ¶ added in v0.17.0
StyleHeader creates a lipgloss style for primary headers using the theme's primary color with bold text for emphasis and hierarchy.
func StyleInfo ¶ added in v0.17.0
StyleInfo creates a lipgloss style for informational messages using blue colors with bold text for general notifications and status updates.
func StyleMuted ¶ added in v0.17.0
StyleMuted creates a lipgloss style for de-emphasized text using muted colors and italic formatting, suitable for supplementary or less important information.
func StyleSubheader ¶ added in v0.17.0
StyleSubheader creates a lipgloss style for secondary headers using the theme's secondary color with bold text, providing visual hierarchy below primary headers.
func StyleSuccess ¶ added in v0.17.0
StyleSuccess creates a lipgloss style for success messages using green colors with bold text to indicate successful operations or positive outcomes.
func StyleWarning ¶ added in v0.17.0
StyleWarning creates a lipgloss style for warning messages using yellow/amber colors with bold text to draw attention to potential issues or cautions.
func WithAlign ¶ added in v0.17.0
WithAlign returns a renderingOption that sets the horizontal alignment of the block content within its container. The align parameter accepts lipgloss.Left, lipgloss.Center, or lipgloss.Right positions.
func WithBorderColor ¶ added in v0.17.0
func WithBorderColor(color lipgloss.AdaptiveColor) renderingOption
WithBorderColor returns a renderingOption that sets the border color for the block. The color parameter uses lipgloss.AdaptiveColor to support both light and dark terminal themes automatically.
func WithFullWidth ¶ added in v0.17.0
func WithFullWidth() renderingOption
WithFullWidth returns a renderingOption that configures the block renderer to expand to the full available width of its container. When enabled, the block will fill the entire horizontal space rather than sizing to its content.
func WithMarginBottom ¶ added in v0.17.0
func WithMarginBottom(margin int) renderingOption
WithMarginBottom returns a renderingOption that sets the bottom margin for the block. The margin is specified in number of lines and adds vertical space below the block.
func WithMarginTop ¶ added in v0.17.0
func WithMarginTop(margin int) renderingOption
WithMarginTop returns a renderingOption that sets the top margin for the block. The margin is specified in number of lines and adds vertical space above the block.
func WithPaddingBottom ¶ added in v0.17.0
func WithPaddingBottom(padding int) renderingOption
WithPaddingBottom returns a renderingOption that sets the bottom padding for the block content. The padding is specified in number of lines and adds vertical space between the content and the bottom border.
func WithPaddingLeft ¶ added in v0.17.0
func WithPaddingLeft(padding int) renderingOption
WithPaddingLeft returns a renderingOption that sets the left padding for the block content. The padding is specified in number of characters and adds horizontal space between the left border and the content.
func WithPaddingRight ¶ added in v0.17.0
func WithPaddingRight(padding int) renderingOption
WithPaddingRight returns a renderingOption that sets the right padding for the block content. The padding is specified in number of characters and adds horizontal space between the content and the right border.
func WithPaddingTop ¶ added in v0.17.0
func WithPaddingTop(padding int) renderingOption
WithPaddingTop returns a renderingOption that sets the top padding for the block content. The padding is specified in number of lines and adds vertical space between the top border and the content.
Types ¶
type AgentInterface ¶ added in v0.19.0
type AgentInterface interface {
GetLoadingMessage() string
GetTools() []any // Using any to avoid importing tool types
GetLoadedServerNames() []string // Add this method for debug config
}
AgentInterface defines the minimal interface required from the agent package to avoid circular dependencies while still accessing necessary agent functionality.
type CLI ¶
type CLI struct {
// contains filtered or unexported fields
}
CLI manages the command-line interface for MCPHost, providing message rendering, user input handling, and display management. It supports both standard and compact display modes, handles streaming responses, tracks token usage, and manages the overall conversation flow between the user and AI assistants.
func NewCLI ¶
NewCLI creates and initializes a new CLI instance with the specified display modes. The debug parameter enables debug message rendering, while compact enables a more condensed display format. Returns an initialized CLI ready for interaction or an error if initialization fails.
func SetupCLI ¶ added in v0.19.0
func SetupCLI(opts *CLISetupOptions) (*CLI, error)
SetupCLI creates, configures, and initializes a CLI instance with the provided options. It sets up model display, usage tracking for supported providers, and shows initial loading information. Returns nil in quiet mode or an initialized CLI instance ready for user interaction.
func (*CLI) ClearMessages ¶
func (c *CLI) ClearMessages()
ClearMessages removes all messages from the display container and refreshes the screen. This is typically used when starting a new conversation or clearing the chat history.
func (*CLI) CreateCallbackHandler ¶
CreateCallbackHandler creates and returns a callbacks.Handler that manages tool execution callbacks for the CLI. The handler displays tool calls, handles errors, and manages streaming output for interactive tool operations. It integrates with the eino callback system to provide real-time UI feedback during tool execution.
func (*CLI) DisplayAssistantMessage ¶
DisplayAssistantMessage renders and displays an AI assistant's response message with appropriate formatting. This method delegates to DisplayAssistantMessageWithModel with an empty model name for backward compatibility.
func (*CLI) DisplayAssistantMessageWithModel ¶
DisplayAssistantMessageWithModel renders and displays an AI assistant's response with the specified model name shown in the message header. The message is formatted according to the current display mode and includes timestamp information.
func (*CLI) DisplayCancellation ¶ added in v0.14.0
func (c *CLI) DisplayCancellation()
DisplayCancellation displays a system message indicating that the current AI generation has been cancelled by the user (typically via ESC key).
func (*CLI) DisplayDebugConfig ¶ added in v0.12.0
DisplayDebugConfig renders and displays configuration settings in a formatted debug message. The config parameter should contain key-value pairs representing configuration options that will be displayed for debugging purposes.
func (*CLI) DisplayDebugMessage ¶ added in v0.28.0
DisplayDebugMessage renders and displays a debug message if debug mode is enabled. Debug messages are formatted distinctively and only shown when the CLI is initialized with debug=true.
func (*CLI) DisplayError ¶
DisplayError renders and displays an error message with distinctive formatting to ensure visibility. The error is timestamped and styled according to the current display mode's error theme.
func (*CLI) DisplayHelp ¶
func (c *CLI) DisplayHelp()
DisplayHelp renders and displays comprehensive help information showing all available slash commands, keyboard shortcuts, and usage instructions in a formatted system message block.
func (*CLI) DisplayInfo ¶
DisplayInfo renders and displays an informational system message. These messages are typically used for status updates, notifications, or other non-error system communications to the user.
func (*CLI) DisplayServers ¶
DisplayServers renders and displays a formatted list of all configured MCP (Model Context Protocol) servers. Each server is numbered and shown in a system message block for easy reference.
func (*CLI) DisplayToolCallMessage ¶
DisplayToolCallMessage renders and displays a message indicating that a tool is being executed. Shows the tool name and its arguments formatted appropriately for the current display mode. This is typically shown while a tool is running.
func (*CLI) DisplayToolMessage ¶
DisplayToolMessage renders and displays the complete result of a tool execution, including the tool name, arguments, and result. The isError parameter determines whether the result should be displayed as an error or success message.
func (*CLI) DisplayTools ¶
DisplayTools renders and displays a formatted list of all available tools that can be used by the AI assistant. Each tool is numbered and shown in a system message block for easy reference.
func (*CLI) DisplayUsageAfterResponse ¶ added in v0.19.0
func (c *CLI) DisplayUsageAfterResponse()
DisplayUsageAfterResponse renders and displays token usage information immediately following an AI response. This provides real-time feedback about the cost and token consumption of each interaction.
func (*CLI) DisplayUsageStats ¶ added in v0.14.0
func (c *CLI) DisplayUsageStats()
DisplayUsageStats renders and displays comprehensive token usage statistics including the last request's token counts and costs, as well as session totals. Shows a message if usage tracking is not available for the current model.
func (*CLI) DisplayUserMessage ¶
DisplayUserMessage renders and displays a user's message with appropriate formatting based on the current display mode (standard or compact). The message is timestamped and styled according to the active theme.
func (*CLI) GetDebugLogger ¶ added in v0.28.0
func (c *CLI) GetDebugLogger() *CLIDebugLogger
GetDebugLogger returns a CLIDebugLogger instance that routes debug output through the CLI's rendering system for consistent message formatting and display.
func (*CLI) GetPrompt ¶
GetPrompt displays an interactive prompt and waits for user input. It provides slash command support, multi-line editing, and cancellation handling. Returns the user's input as a string, or an error if the operation was cancelled or failed. Returns io.EOF for clean exit signals.
func (*CLI) HandleSlashCommand ¶
func (c *CLI) HandleSlashCommand(input string, servers []string, tools []string) SlashCommandResult
HandleSlashCommand processes and executes slash commands, returning a result that indicates whether the command was handled and any side effects. The servers and tools parameters provide context for commands that display available resources. Supported commands include /help, /tools, /servers, /clear, /usage, /reset-usage, and /quit.
func (*CLI) IsSlashCommand ¶
IsSlashCommand determines whether the provided input string is a slash command by checking if it starts with a forward slash (/). Returns true for commands like "/help", "/tools", etc.
func (*CLI) ResetUsageStats ¶ added in v0.14.0
func (c *CLI) ResetUsageStats()
ResetUsageStats clears all accumulated usage statistics, resetting token counts and costs to zero. Displays a confirmation message after resetting or an info message if usage tracking is not available.
func (*CLI) SetModelName ¶ added in v0.19.0
SetModelName updates the current AI model name being used in the conversation. This name is displayed in message headers to indicate which model is responding.
func (*CLI) SetUsageTracker ¶ added in v0.14.0
func (c *CLI) SetUsageTracker(tracker *UsageTracker)
SetUsageTracker attaches a usage tracker to the CLI for monitoring token consumption and costs. The tracker will be automatically updated with the current display width for proper rendering.
func (*CLI) ShowSpinner ¶
ShowSpinner displays an animated spinner with the specified message while executing the provided action function. The spinner automatically stops when the action completes. Returns any error returned by the action function.
func (*CLI) StartStreamingMessage ¶ added in v0.18.0
StartStreamingMessage initializes a new streaming message display for real-time AI responses. The message will be progressively updated as content arrives. The modelName parameter indicates which AI model is generating the response.
func (*CLI) UpdateStreamingMessage ¶ added in v0.18.0
UpdateStreamingMessage updates the currently streaming message with new content. This method should be called after StartStreamingMessage to progressively display AI responses as they are generated in real-time.
func (*CLI) UpdateUsage ¶ added in v0.14.0
UpdateUsage estimates and records token usage based on input and output text. This method uses text-based estimation when actual token counts are not available from the AI provider's response metadata.
func (*CLI) UpdateUsageFromResponse ¶ added in v0.14.0
UpdateUsageFromResponse records token usage using metadata from the AI provider's response when available. Falls back to text-based estimation if the metadata is missing or appears unreliable. This provides more accurate usage tracking when providers supply token count information.
type CLIDebugLogger ¶ added in v0.28.0
type CLIDebugLogger struct {
// contains filtered or unexported fields
}
CLIDebugLogger implements the tools.DebugLogger interface using CLI rendering. It provides debug logging functionality that integrates with the CLI's display system, ensuring debug messages are properly formatted and displayed alongside other conversation content.
func NewCLIDebugLogger ¶ added in v0.28.0
func NewCLIDebugLogger(cli *CLI) *CLIDebugLogger
NewCLIDebugLogger creates and returns a new CLIDebugLogger instance that routes debug output through the provided CLI instance. The logger will respect the CLI's debug mode setting and display format preferences.
func (*CLIDebugLogger) IsDebugEnabled ¶ added in v0.28.0
func (l *CLIDebugLogger) IsDebugEnabled() bool
IsDebugEnabled checks whether debug logging is currently active. Returns true if the CLI instance exists and has debug mode enabled, allowing callers to conditionally perform expensive debug operations only when necessary.
func (*CLIDebugLogger) LogDebug ¶ added in v0.28.0
func (l *CLIDebugLogger) LogDebug(message string)
LogDebug processes and displays a debug message through the CLI's rendering system. Messages are formatted with appropriate emojis and tags based on their content type (DEBUG, POOL, etc.) and only displayed when debug mode is enabled. The method handles multi-line debug output and connection pool status messages with context-aware formatting.
type CLISetupOptions ¶ added in v0.19.0
type CLISetupOptions struct {
Agent AgentInterface
ModelString string
Debug bool
Compact bool
Quiet bool
ShowDebug bool // Whether to show debug config
ProviderAPIKey string // For OAuth detection
}
CLISetupOptions encapsulates all configuration parameters needed to initialize and set up a CLI instance, including display preferences, model information, and debugging settings.
type CompactRenderer ¶ added in v0.19.0
type CompactRenderer struct {
// contains filtered or unexported fields
}
CompactRenderer handles rendering messages in a space-efficient compact format, optimized for terminals with limited vertical space. It displays messages with minimal decorations while maintaining readability and essential information.
func NewCompactRenderer ¶ added in v0.19.0
func NewCompactRenderer(width int, debug bool) *CompactRenderer
NewCompactRenderer creates and initializes a new CompactRenderer with the specified terminal width and debug mode setting. The width parameter determines line wrapping, while debug enables additional diagnostic output in rendered messages.
func (*CompactRenderer) RenderAssistantMessage ¶ added in v0.19.0
func (r *CompactRenderer) RenderAssistantMessage(content string, timestamp time.Time, modelName string) UIMessage
RenderAssistantMessage renders an AI assistant's response in compact format with a distinctive symbol (<) and the model name as label. Empty content is displayed as "(no output)". Returns a UIMessage with formatted content and metadata.
func (*CompactRenderer) RenderDebugConfigMessage ¶ added in v0.19.0
func (r *CompactRenderer) RenderDebugConfigMessage(config map[string]any, timestamp time.Time) UIMessage
RenderDebugConfigMessage renders configuration settings in compact format for debugging purposes. Config entries are displayed as key=value pairs separated by commas, truncated if necessary to fit on a single line.
func (*CompactRenderer) RenderDebugMessage ¶ added in v0.28.0
func (r *CompactRenderer) RenderDebugMessage(message string, timestamp time.Time) UIMessage
RenderDebugMessage renders diagnostic information in compact format when debug mode is enabled. Messages are truncated if they exceed the available width to maintain single-line display.
func (*CompactRenderer) RenderErrorMessage ¶ added in v0.19.0
func (r *CompactRenderer) RenderErrorMessage(errorMsg string, timestamp time.Time) UIMessage
RenderErrorMessage renders an error notification in compact format with a distinctive error symbol (!) and styling to ensure visibility. The error content is displayed in a single line with appropriate color highlighting.
func (*CompactRenderer) RenderSystemMessage ¶ added in v0.19.0
func (r *CompactRenderer) RenderSystemMessage(content string, timestamp time.Time) UIMessage
RenderSystemMessage renders a system notification or informational message in compact format with a distinctive symbol (*) and "System" label. Content is formatted to fit on a single line for minimal space usage.
func (*CompactRenderer) RenderToolCallMessage ¶ added in v0.19.0
func (r *CompactRenderer) RenderToolCallMessage(toolName, toolArgs string, timestamp time.Time) UIMessage
RenderToolCallMessage renders a tool call notification in compact format, showing the tool being executed with its arguments in a single line. The tool name is highlighted and arguments are displayed in a muted color for visual distinction.
func (*CompactRenderer) RenderToolMessage ¶ added in v0.19.0
func (r *CompactRenderer) RenderToolMessage(toolName, toolArgs, toolResult string, isError bool) UIMessage
RenderToolMessage renders the result of a tool execution in compact format, displaying the outcome with appropriate styling based on success or error status. Results are limited to 5 lines to maintain compact display while preserving key information.
func (*CompactRenderer) RenderUserMessage ¶ added in v0.19.0
func (r *CompactRenderer) RenderUserMessage(content string, timestamp time.Time) UIMessage
RenderUserMessage renders a user's input message in compact format with a distinctive symbol (>) and label. The content is formatted to preserve structure while minimizing vertical space usage. Returns a UIMessage with formatted content and metadata.
func (*CompactRenderer) SetWidth ¶ added in v0.19.0
func (r *CompactRenderer) SetWidth(width int)
SetWidth updates the terminal width for the renderer, affecting how content is wrapped and formatted in subsequent render operations.
type FuzzyMatch ¶ added in v0.21.0
type FuzzyMatch struct {
Command *SlashCommand
Score int
}
FuzzyMatch represents the result of a fuzzy string matching operation, containing the matched command and its relevance score. Higher scores indicate better matches.
func FuzzyMatchCommands ¶ added in v0.21.0
func FuzzyMatchCommands(query string, commands []SlashCommand) []FuzzyMatch
FuzzyMatchCommands performs fuzzy string matching on the provided slash commands based on the query string. Returns a slice of matches sorted by relevance score in descending order. An empty query returns all commands with zero scores.
type MessageContainer ¶
type MessageContainer struct {
// contains filtered or unexported fields
}
MessageContainer manages a collection of UI messages, handling their display, updates, and layout within the terminal. It supports both standard and compact display modes and maintains state for streaming message updates.
func NewMessageContainer ¶
func NewMessageContainer(width, height int, compact bool) *MessageContainer
NewMessageContainer creates and initializes a new MessageContainer with the specified dimensions and display mode. The container starts empty and will display a welcome message until the first message is added.
func (*MessageContainer) AddMessage ¶
func (c *MessageContainer) AddMessage(msg UIMessage)
AddMessage appends a new UIMessage to the container's collection and resets the cleared state flag. Messages are displayed in the order they were added.
func (*MessageContainer) Clear ¶
func (c *MessageContainer) Clear()
Clear removes all messages from the container and sets a flag to prevent showing the welcome screen. Used when starting a fresh conversation.
func (*MessageContainer) Render ¶
func (c *MessageContainer) Render() string
Render generates the complete visual representation of all messages in the container. Returns an empty state display if no messages exist, or formats all messages according to the current display mode (standard or compact).
func (*MessageContainer) SetModelName ¶ added in v0.19.0
func (c *MessageContainer) SetModelName(modelName string)
SetModelName updates the AI model name used for rendering assistant messages. This name is displayed in message headers to indicate which model is responding.
func (*MessageContainer) SetSize ¶
func (c *MessageContainer) SetSize(width, height int)
SetSize updates the container's dimensions, typically called when the terminal is resized. This affects how messages are wrapped and displayed.
func (*MessageContainer) UpdateLastMessage ¶ added in v0.18.0
func (c *MessageContainer) UpdateLastMessage(content string)
UpdateLastMessage efficiently updates the content of the most recent message in the container. This is primarily used for streaming responses where the assistant's message is progressively built. Only works for assistant messages.
type MessageRenderer ¶
type MessageRenderer struct {
// contains filtered or unexported fields
}
MessageRenderer handles the formatting and rendering of different message types with consistent styling, markdown support, and appropriate visual hierarchies for the standard (non-compact) display mode.
func NewMessageRenderer ¶
func NewMessageRenderer(width int, debug bool) *MessageRenderer
NewMessageRenderer creates and initializes a new MessageRenderer with the specified terminal width and debug mode setting. The width parameter determines line wrapping and layout calculations.
func (*MessageRenderer) RenderAssistantMessage ¶
func (r *MessageRenderer) RenderAssistantMessage(content string, timestamp time.Time, modelName string) UIMessage
RenderAssistantMessage renders an AI assistant's response with left-aligned formatting, including the model name, timestamp, and markdown-rendered content. Empty responses are displayed with a special "Finished without output" message. The message features a colored left border for visual distinction.
func (*MessageRenderer) RenderDebugConfigMessage ¶ added in v0.12.0
func (r *MessageRenderer) RenderDebugConfigMessage(config map[string]any, timestamp time.Time) UIMessage
RenderDebugConfigMessage renders configuration settings in a formatted debug display with key-value pairs shown in a structured layout. Used to display runtime configuration for debugging purposes with a distinctive icon and border styling.
func (*MessageRenderer) RenderDebugMessage ¶ added in v0.28.0
func (r *MessageRenderer) RenderDebugMessage(message string, timestamp time.Time) UIMessage
RenderDebugMessage renders diagnostic and debugging information with special formatting including a debug icon, colored border, and structured layout. Debug messages are only displayed when debug mode is enabled and help developers troubleshoot issues.
func (*MessageRenderer) RenderErrorMessage ¶
func (r *MessageRenderer) RenderErrorMessage(errorMsg string, timestamp time.Time) UIMessage
RenderErrorMessage renders error notifications with distinctive red coloring and bold text to ensure visibility. Error messages include timestamp information and are displayed with an error-colored border for immediate recognition.
func (*MessageRenderer) RenderSystemMessage ¶
func (r *MessageRenderer) RenderSystemMessage(content string, timestamp time.Time) UIMessage
RenderSystemMessage renders MCPHost system messages such as help text, command outputs, and informational notifications. These messages are displayed with a distinctive system color border and "MCPHost System" label to differentiate them from user and AI content.
func (*MessageRenderer) RenderToolCallMessage ¶
func (r *MessageRenderer) RenderToolCallMessage(toolName, toolArgs string, timestamp time.Time) UIMessage
RenderToolCallMessage renders a notification that a tool is being executed, showing the tool name, formatted arguments (if any), and execution timestamp. The message uses tool-specific coloring to distinguish it from regular conversation messages.
func (*MessageRenderer) RenderToolMessage ¶
func (r *MessageRenderer) RenderToolMessage(toolName, toolArgs, toolResult string, isError bool) UIMessage
RenderToolMessage renders the result of a tool execution, formatting the output based on the tool type and whether it succeeded or failed. Error results are displayed in red, while successful results are formatted according to the tool's output type (bash, file content, etc.).
func (*MessageRenderer) RenderUserMessage ¶
func (r *MessageRenderer) RenderUserMessage(content string, timestamp time.Time) UIMessage
RenderUserMessage renders a user's input message with distinctive right-aligned formatting, including the system username, timestamp, and markdown-rendered content. The message is displayed with a colored right border for visual distinction.
func (*MessageRenderer) SetWidth ¶
func (r *MessageRenderer) SetWidth(width int)
SetWidth updates the terminal width for the renderer, affecting how content is wrapped and formatted in subsequent render operations.
type MessageType ¶
type MessageType int
MessageType represents different categories of messages displayed in the UI, each with distinct visual styling and formatting rules.
const ( UserMessage MessageType = iota AssistantMessage ToolMessage ToolCallMessage // New type for showing tool calls in progress SystemMessage // New type for MCPHost system messages (help, tools, etc.) ErrorMessage // New type for error messages )
type SessionStats ¶ added in v0.14.0
type SessionStats struct {
TotalInputTokens int
TotalOutputTokens int
TotalCacheReadTokens int
TotalCacheWriteTokens int
TotalCost float64
RequestCount int
}
SessionStats aggregates token usage and cost information across all requests in a session, providing totals and request counts for usage analysis and cost tracking.
type SlashCommand ¶ added in v0.21.0
type SlashCommand struct {
Name string
Description string
Aliases []string
Category string // e.g., "Navigation", "System", "Info"
}
SlashCommand represents a user-invokable slash command with its metadata. Commands can have multiple aliases and are organized by category for better discoverability and help display.
func GetCommandByName ¶ added in v0.21.0
func GetCommandByName(name string) *SlashCommand
GetCommandByName looks up a slash command by its primary name or any of its aliases. Returns a pointer to the matching SlashCommand, or nil if no command matches the provided name.
type SlashCommandInput ¶ added in v0.21.0
type SlashCommandInput struct {
// contains filtered or unexported fields
}
SlashCommandInput provides an interactive text input field with intelligent slash command autocomplete functionality. It displays a popup menu of matching commands as the user types, supporting fuzzy matching and keyboard navigation.
func NewSlashCommandInput ¶ added in v0.21.0
func NewSlashCommandInput(width int, title string) *SlashCommandInput
NewSlashCommandInput creates and initializes a new slash command input field with the specified width and title. The input supports multi-line text entry, command autocomplete, and is styled to match the application's theme.
func (*SlashCommandInput) Cancelled ¶ added in v0.21.0
func (s *SlashCommandInput) Cancelled() bool
Cancelled returns true if the user cancelled the input operation (e.g., by pressing ESC or Ctrl+C) without submitting any text.
func (*SlashCommandInput) Init ¶ added in v0.21.0
func (s *SlashCommandInput) Init() tea.Cmd
Init implements the tea.Model interface, returning the initial command to start the cursor blinking animation for the text input field.
func (*SlashCommandInput) RenderedLines ¶ added in v0.21.0
func (s *SlashCommandInput) RenderedLines() int
RenderedLines returns the total number of terminal lines used by the last rendered view, including the title, input area, popup, and help text. This is used for proper screen clearing when the input is dismissed.
func (*SlashCommandInput) Update ¶ added in v0.21.0
Update implements the tea.Model interface, handling keyboard input for text entry, command selection, and navigation. Manages the autocomplete popup display and processes submission or cancellation actions.
func (*SlashCommandInput) Value ¶ added in v0.21.0
func (s *SlashCommandInput) Value() string
Value returns the final text value entered by the user after submission. This will be empty if the input was cancelled.
func (*SlashCommandInput) View ¶ added in v0.21.0
func (s *SlashCommandInput) View() string
View implements the tea.Model interface, rendering the complete input field including the title, text area, autocomplete popup (when active), and help text. The view adapts based on whether single or multi-line input is detected.
type SlashCommandResult ¶ added in v0.17.0
SlashCommandResult encapsulates the outcome of processing a slash command, indicating whether the command was recognized and handled, and whether the conversation history should be cleared as a result of the command.
type Spinner ¶
type Spinner struct {
// contains filtered or unexported fields
}
Spinner provides an animated loading indicator that displays while long-running operations are in progress. It wraps the bubbles spinner component and manages its lifecycle through a tea.Program for proper terminal handling.
func NewSpinner ¶
NewSpinner creates a new animated spinner with the specified message. The spinner uses the theme's primary color and a modern animation style. It runs in a separate tea.Program to avoid interfering with other terminal operations.
func NewThemedSpinner ¶
func NewThemedSpinner(message string, color lipgloss.AdaptiveColor) *Spinner
NewThemedSpinner creates a new animated spinner with custom color styling. This allows for different spinner colors based on the operation type or status. The spinner runs independently in its own tea.Program.
type Theme ¶ added in v0.17.0
type Theme struct {
Primary lipgloss.AdaptiveColor
Secondary lipgloss.AdaptiveColor
Success lipgloss.AdaptiveColor
Warning lipgloss.AdaptiveColor
Error lipgloss.AdaptiveColor
Info lipgloss.AdaptiveColor
Text lipgloss.AdaptiveColor
Muted lipgloss.AdaptiveColor
VeryMuted lipgloss.AdaptiveColor
Background lipgloss.AdaptiveColor
Border lipgloss.AdaptiveColor
MutedBorder lipgloss.AdaptiveColor
System lipgloss.AdaptiveColor
Tool lipgloss.AdaptiveColor
Accent lipgloss.AdaptiveColor
Highlight lipgloss.AdaptiveColor
}
Theme defines a comprehensive color scheme for the application's UI, supporting both light and dark terminal modes through adaptive colors. It includes semantic colors for different message types and UI elements, based on the Catppuccin color palette.
func DefaultTheme ¶ added in v0.17.0
func DefaultTheme() Theme
DefaultTheme creates and returns the default MCPHost theme based on the Catppuccin Mocha (dark) and Latte (light) color palettes. This theme provides a cohesive, pleasant visual experience with carefully selected colors for different UI elements.
type UIMessage ¶
type UIMessage struct {
ID string
Type MessageType
Position int
Height int
Content string
Timestamp time.Time
Streaming bool
}
UIMessage encapsulates a fully rendered message ready for display in the UI, including its formatted content, display metrics, and metadata. Messages can be static or streaming (progressively updated).
type UsageStats ¶ added in v0.14.0
type UsageStats struct {
InputTokens int
OutputTokens int
CacheReadTokens int
CacheWriteTokens int
InputCost float64
OutputCost float64
CacheReadCost float64
CacheWriteCost float64
TotalCost float64
}
UsageStats encapsulates detailed token usage and cost breakdown for a single LLM request/response cycle, including input, output, and cache token counts along with their associated costs.
type UsageTracker ¶ added in v0.14.0
type UsageTracker struct {
// contains filtered or unexported fields
}
UsageTracker monitors and accumulates token usage statistics and associated costs for LLM interactions throughout a session. It provides real-time usage information and supports both estimated and actual token counts. OAuth users see $0 costs.
func NewUsageTracker ¶ added in v0.14.0
func NewUsageTracker(modelInfo *models.ModelInfo, provider string, width int, isOAuth bool) *UsageTracker
NewUsageTracker creates and initializes a new UsageTracker for the specified model. The tracker uses model-specific pricing information to calculate costs, unless OAuth credentials are being used (in which case costs are shown as $0). Width determines the display formatting.
func (*UsageTracker) EstimateAndUpdateUsage ¶ added in v0.14.0
func (ut *UsageTracker) EstimateAndUpdateUsage(inputText, outputText string)
EstimateAndUpdateUsage estimates token counts from raw text strings and updates the usage statistics. This method is used when actual token counts are not available from the API response.
func (*UsageTracker) EstimateAndUpdateUsageFromText ¶ added in v0.14.0
func (ut *UsageTracker) EstimateAndUpdateUsageFromText(inputText, outputText string)
EstimateAndUpdateUsageFromText is an alias for EstimateAndUpdateUsage, providing backward compatibility. It estimates token counts from text and updates usage statistics.
func (*UsageTracker) GetLastRequestStats ¶ added in v0.14.0
func (ut *UsageTracker) GetLastRequestStats() *UsageStats
GetLastRequestStats returns a copy of the usage statistics from the most recent request, or nil if no requests have been made. The returned copy is safe to use without additional synchronization.
func (*UsageTracker) GetSessionStats ¶ added in v0.14.0
func (ut *UsageTracker) GetSessionStats() SessionStats
GetSessionStats returns a copy of the cumulative session statistics including total token counts, costs, and request count. The returned copy is safe to use without additional synchronization.
func (*UsageTracker) RenderUsageInfo ¶ added in v0.14.0
func (ut *UsageTracker) RenderUsageInfo() string
RenderUsageInfo generates a formatted string displaying current usage statistics including token counts, context utilization percentage, and costs. The display adapts colors based on usage levels and formats large numbers with K/M suffixes for readability.
func (*UsageTracker) Reset ¶ added in v0.14.0
func (ut *UsageTracker) Reset()
Reset clears all accumulated usage statistics, resetting both session totals and last request information to their initial empty state. This is typically used when starting a new conversation or clearing usage history.
func (*UsageTracker) SetWidth ¶ added in v0.14.0
func (ut *UsageTracker) SetWidth(width int)
SetWidth updates the terminal width used for formatting usage information display. This should be called when the terminal is resized to ensure proper text wrapping and alignment.
func (*UsageTracker) UpdateUsage ¶ added in v0.14.0
func (ut *UsageTracker) UpdateUsage(inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens int)
UpdateUsage records new token usage data and calculates associated costs based on the model's pricing. Updates both the last request statistics and cumulative session totals. For OAuth users, costs are recorded as $0 while still tracking token counts.