Documentation
¶
Overview ¶
Package chat provides an interactive Bubbletea TUI for conversing with GitHub Copilot. It renders assistant responses as markdown with syntax highlighting using glamour.
Index ¶
- func BuildSystemContext(cfg SystemContextConfig) (string, error)
- func BuildSystemSections(cfg SystemContextConfig) map[string]copilot.SectionOverride
- func CreateTUIPermissionHandler(eventChan chan<- tea.Msg, yoloModeRef *YoloModeRef) copilot.PermissionHandlerFunc
- func DeleteSession(ctx context.Context, client *copilot.Client, sessionID string, appDir string) error
- func FilterEnabledModels(allModels []copilot.ModelInfo) []copilot.ModelInfo
- func FormatRelativeTime(timestamp time.Time) string
- func GenerateSessionName(messages []message) string
- func IsReadOperation(kind copilot.PermissionRequestKind) bool
- func Run(ctx context.Context, params Params) error
- func SaveSession(session *SessionMetadata, appDir string) error
- type ChatMode
- type ChatModeRef
- type CommandBuilder
- type KeyMap
- type MessageMetadata
- type ModeRef
- type Model
- type Params
- type PermissionRequestMsg
- type SessionMetadata
- type SystemContextConfig
- type TaskCompleteMsg
- type ThemeConfig
- type ToolDisplayConfig
- type ToolOutputChunkMsg
- type ToolProgressMsg
- type YoloModeRef
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BuildSystemContext ¶ added in v5.31.2
func BuildSystemContext(cfg SystemContextConfig) (string, error)
BuildSystemContext builds a formatted system context string from the given configuration. This produces the system prompt passed to the AI assistant session.
func BuildSystemSections ¶ added in v5.80.0
func BuildSystemSections(cfg SystemContextConfig) map[string]copilot.SectionOverride
BuildSystemSections builds system prompt section overrides for the "customize" mode. This maps the SystemContextConfig fields to SDK section identifiers.
func CreateTUIPermissionHandler ¶ added in v5.26.0
func CreateTUIPermissionHandler( eventChan chan<- tea.Msg, yoloModeRef *YoloModeRef, ) copilot.PermissionHandlerFunc
CreateTUIPermissionHandler creates a permission handler that integrates with the TUI. It sends permission requests to the provided event channel and waits for a response. This allows the TUI to display permission prompts and collect user input. Read and URL operations are auto-approved to avoid excessive prompting. When yoloModeRef is provided and YOLO mode is enabled, permissions are auto-approved.
func DeleteSession ¶ added in v5.25.0
func DeleteSession( ctx context.Context, client *copilot.Client, sessionID string, appDir string, ) error
DeleteSession removes a chat session from both SDK and local disk.
func FilterEnabledModels ¶ added in v5.33.0
FilterEnabledModels returns only models with an enabled policy state. This is used by the lazy-load model picker and can be called from outside the package.
func FormatRelativeTime ¶ added in v5.25.0
FormatRelativeTime formats a time as a relative string (e.g., "2 hours ago").
func GenerateSessionName ¶ added in v5.25.0
func GenerateSessionName(messages []message) string
GenerateSessionName creates a session name from the first user message.
func IsReadOperation ¶ added in v5.80.0
func IsReadOperation(kind copilot.PermissionRequestKind) bool
IsReadOperation determines if a permission request is for a read-only operation. This is shared by both TUI and non-TUI permission handlers.
func Run ¶
Run starts the chat TUI with the given parameters. This is the primary entry point for running the chat interface.
func SaveSession ¶ added in v5.25.0
func SaveSession(session *SessionMetadata, appDir string) error
SaveSession saves session metadata to disk. The ID must be provided (typically from the Copilot SDK session.SessionID).
Types ¶
type ChatMode ¶ added in v5.32.0
type ChatMode int //nolint:revive // ChatMode is clearer than Mode given existing ModeRef type in this package.
ChatMode represents the chat interaction mode.
func (ChatMode) Label ¶ added in v5.32.0
Label returns the icon and text label for the chat mode (e.g. "</> agent").
type ChatModeRef ¶ added in v5.32.0
type ChatModeRef struct {
// contains filtered or unexported fields
}
ChatModeRef is a thread-safe reference to the current chat mode. It allows tool handlers to check the mode at execution time.
func NewChatModeRef ¶ added in v5.32.0
func NewChatModeRef(initial ChatMode) *ChatModeRef
NewChatModeRef creates a new ChatModeRef with the given initial mode.
func (*ChatModeRef) Mode ¶ added in v5.32.0
func (r *ChatModeRef) Mode() ChatMode
Mode returns the current chat mode.
func (*ChatModeRef) SetMode ¶ added in v5.32.0
func (r *ChatModeRef) SetMode(mode ChatMode)
SetMode updates the chat mode.
type CommandBuilder ¶ added in v5.31.2
CommandBuilder extracts a display command string from tool arguments for display in the TUI.
type KeyMap ¶ added in v5.26.0
type KeyMap struct {
// Navigation
Up key.Binding
Down key.Binding
PageUp key.Binding
PageDown key.Binding
// Actions
Send key.Binding
Queue key.Binding
DeletePending key.Binding
NewLine key.Binding
Cancel key.Binding
Quit key.Binding
ToggleMode key.Binding
ToggleHelp key.Binding
// Tools
ExpandTools key.Binding
// Output
CopyOutput key.Binding
// YOLO mode
ToggleYolo key.Binding
// Modals
OpenSessions key.Binding
OpenModel key.Binding
NewChat key.Binding
// Permission modal
Allow key.Binding
Deny key.Binding
// Picker navigation
Select key.Binding
Rename key.Binding
Delete key.Binding
// Filter/search
Filter key.Binding
}
KeyMap defines all keybindings for the chat TUI. It implements the help.KeyMap interface for contextual help rendering.
func DefaultKeyMap ¶ added in v5.26.0
func DefaultKeyMap() KeyMap
DefaultKeyMap returns the default keybindings.
func (KeyMap) FullHelp ¶ added in v5.26.0
FullHelp returns keybindings for the expanded help view (overlay). This implements help.KeyMap interface.
func (KeyMap) PermissionShortHelp ¶ added in v5.26.0
PermissionShortHelp returns keybindings for the permission modal.
func (KeyMap) PickerShortHelp ¶ added in v5.26.0
PickerShortHelp returns keybindings for picker modals.
func (KeyMap) SessionPickerShortHelp ¶ added in v5.26.0
SessionPickerShortHelp returns keybindings for the session picker.
type MessageMetadata ¶ added in v5.25.1
type MessageMetadata struct {
// ChatMode stores the chat mode when the message was sent.
// 0 = agent, 1 = plan, 2 = ask.
ChatMode ChatMode `json:"chatMode"`
}
MessageMetadata represents metadata for a single message in a session.
type ModeRef ¶ added in v5.31.0
type ModeRef struct {
// contains filtered or unexported fields
}
ModeRef is a thread-safe reference to a boolean mode state. It allows tool handlers to check and update mode state at execution time. The enabled field is unexported to ensure all access goes through mutex-protected methods.
func NewModeRef ¶ added in v5.31.0
NewModeRef creates a new ModeRef with the given initial state.
func (*ModeRef) SetEnabled ¶ added in v5.31.0
SetEnabled updates the mode state.
type Model ¶
type Model struct {
// contains filtered or unexported fields
}
Model is the Bubbletea model for the chat TUI.
func NewModel ¶ added in v5.31.2
NewModel creates a new chat TUI model from the given parameters. If params.EventChan is nil, a new channel is created. If params.Theme or params.ToolDisplay are zero-valued, defaults are applied.
func (*Model) GetEventChannel ¶
GetEventChannel returns the model's event channel for external use. This is useful for creating permission handlers that can send events to the TUI.
type Params ¶ added in v5.31.2
type Params struct {
// Session is the active Copilot chat session.
Session *copilot.Session
// Client is the Copilot client used for API calls.
Client *copilot.Client
// SessionConfig holds the session configuration.
SessionConfig *copilot.SessionConfig
// Models is the list of available models.
Models []copilot.ModelInfo
// CurrentModel is the initially-selected model identifier.
CurrentModel string
// Timeout controls the per-request timeout.
Timeout time.Duration
// EventChan is an optional pre-created event channel for sending external events to the TUI.
// If nil, a new channel is created internally.
EventChan chan tea.Msg
// ChatModeRef is an optional reference to synchronize chat mode state with tool handlers.
ChatModeRef *ChatModeRef
// YoloModeRef is an optional reference to synchronize YOLO mode state with tool handlers.
YoloModeRef *YoloModeRef
// Theme configures colors, logo, labels, and other visual aspects.
// Zero value applies DefaultThemeConfig().
Theme ThemeConfig
// ToolDisplay configures tool name mappings and command builders.
// Zero value applies DefaultToolDisplayConfig().
ToolDisplay ToolDisplayConfig
}
Params bundles the parameters for creating and running the chat TUI. Use this struct with NewModel or Run to configure the chat session.
type PermissionRequestMsg ¶ added in v5.25.0
type PermissionRequestMsg struct {
ToolCallID string
ToolName string
Command string
Arguments string
Response chan<- bool
}
PermissionRequestMsg is the exported version of permissionRequestMsg for external use.
type SessionMetadata ¶ added in v5.25.0
type SessionMetadata struct {
ID string `json:"id"`
Name string `json:"name"`
Model string `json:"model,omitempty"`
ChatMode *ChatMode `json:"chatMode,omitempty"` // nil = agent mode (default)
// Messages stores per-message metadata (chatMode for each user message).
Messages []MessageMetadata `json:"messages,omitempty"`
SDKMetadata *copilot.SessionMetadata `json:"-"` // SDK metadata (not persisted)
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
SessionMetadata represents metadata for a chat session stored locally. Message content is stored server-side by Copilot and retrieved via ResumeSession.
func ListSessions ¶ added in v5.25.0
func ListSessions( ctx context.Context, client *copilot.Client, appDir string, ) ([]SessionMetadata, error)
ListSessions returns all local session metadata from SDK, enriched with local metadata. Remote sessions are excluded from the returned slice. Sessions are sorted by ModifiedTime (most recent first).
func LoadSession ¶ added in v5.25.0
func LoadSession( sessionID string, appDir string, ) (*SessionMetadata, error)
LoadSession loads session metadata by ID.
func (*SessionMetadata) GetDisplayName ¶ added in v5.26.0
func (s *SessionMetadata) GetDisplayName() string
GetDisplayName returns the display name using hierarchy: Local Name → SDK Summary → "Unnamed". User-defined names take precedence over SDK-generated summaries.
type SystemContextConfig ¶ added in v5.31.2
type SystemContextConfig struct {
// Identity is the assistant's identity and role description.
Identity string
// Documentation is reference documentation embedded in the system prompt.
Documentation string
// CLIHelp is pre-rendered CLI help text (e.g., from --help output).
CLIHelp string
// Instructions are behavioral instructions for the assistant.
Instructions string
// IncludeWorkingDirContext enables auto-detection of current working directory
// and config file content to include in the prompt.
IncludeWorkingDirContext bool
// ConfigFileName is the config file to detect in the working directory (e.g., "ksail.yaml").
// Only used when IncludeWorkingDirContext is true.
ConfigFileName string
}
SystemContextConfig configures the system prompt for the AI assistant. Use BuildSystemContext() to produce a formatted system context string from this config.
type TaskCompleteMsg ¶ added in v5.80.0
type TaskCompleteMsg struct {
Message string
}
TaskCompleteMsg signals that the session has completed a task. Exported so the OnEvent handler in tui.go can create instances.
type ThemeConfig ¶ added in v5.31.2
type ThemeConfig struct {
// Logo returns the ASCII art logo text (multi-line). Called on each render.
Logo func() string
// Tagline returns the tagline text displayed below the logo.
Tagline func() string
// LogoHeight is the number of lines in the logo (used for layout calculations).
LogoHeight int
// AssistantLabel is the label shown before assistant messages (e.g., "▶ KSail").
AssistantLabel string
// Placeholder is the textarea placeholder text.
Placeholder string
// WelcomeMessage is shown in the viewport before any messages.
WelcomeMessage string
// ExitMessage is shown as the title in the exit confirmation modal (e.g., "Exit chat?").
ExitMessage string
// GoodbyeMessage is shown when the user quits.
GoodbyeMessage string
// SessionDir is the app-specific directory name for session storage under $HOME.
// For example, ".ksail" stores sessions at ~/.ksail/chat/sessions.
SessionDir string
// PrimaryColor is used for main accents (header border, input border, logo).
PrimaryColor lipgloss.AdaptiveColor
// AccentColor is used for tagline and spinner.
AccentColor lipgloss.AdaptiveColor
// SecondaryColor is used for borders and muted elements.
SecondaryColor lipgloss.AdaptiveColor
// UserColor styles user messages.
UserColor lipgloss.AdaptiveColor
// AssistantColor styles assistant message labels.
AssistantColor lipgloss.AdaptiveColor
// ToolColor styles tool calls and help keybindings.
ToolColor lipgloss.AdaptiveColor
// SuccessColor styles success indicators and completed tools.
SuccessColor lipgloss.AdaptiveColor
// DimColor styles muted/less important text.
DimColor lipgloss.AdaptiveColor
// ErrorColor styles error messages.
ErrorColor lipgloss.AdaptiveColor
}
ThemeConfig configures the visual appearance and branding of the chat TUI. All fields have sensible defaults — use DefaultThemeConfig() as a starting point and override the fields you need.
func DefaultThemeConfig ¶ added in v5.31.2
func DefaultThemeConfig() ThemeConfig
DefaultThemeConfig returns the default theme configuration with KSail branding.
type ToolDisplayConfig ¶ added in v5.31.2
type ToolDisplayConfig struct {
// NameMappings maps tool names to human-readable labels.
// Example: {"my_tool_list": "Listing items", "bash": "Running command"}
// The generic fallback (snake_case → Title Case) is used for unmapped names.
NameMappings map[string]string
// CommandBuilders maps tool names to functions that extract display commands from arguments.
CommandBuilders map[string]CommandBuilder
}
ToolDisplayConfig configures how tool names and commands are displayed in the TUI.
func DefaultToolDisplayConfig ¶ added in v5.31.2
func DefaultToolDisplayConfig() ToolDisplayConfig
DefaultToolDisplayConfig returns the default tool display configuration with KSail tool mappings.
type ToolOutputChunkMsg ¶
ToolOutputChunkMsg is the exported version of toolOutputChunkMsg for external use.
type ToolProgressMsg ¶ added in v5.80.0
ToolProgressMsg carries a progress update from a running tool. Exported so the OnEvent handler in tui.go can create instances.
type YoloModeRef ¶ added in v5.31.0
type YoloModeRef = ModeRef
YoloModeRef is a thread-safe reference to the YOLO mode state. When enabled, write operations are auto-approved without prompting the user.
func NewYoloModeRef ¶ added in v5.31.0
func NewYoloModeRef(initial bool) *YoloModeRef
NewYoloModeRef creates a new YoloModeRef with the given initial state.