chat

package
v5.36.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 18, 2026 License: Apache-2.0 Imports: 26 Imported by: 0

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

Constants

This section is empty.

Variables

View Source
var ErrNoSessions = errors.New("no sessions available")

ErrNoSessions is returned when there are no sessions available.

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 CreateTUIPermissionHandler added in v5.26.0

func CreateTUIPermissionHandler(
	eventChan chan<- tea.Msg,
	yoloModeRef *YoloModeRef,
) copilot.PermissionHandler

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. 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

func FilterEnabledModels(allModels []copilot.ModelInfo) []copilot.ModelInfo

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

func FormatRelativeTime(timestamp time.Time) string

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 Run

func Run(ctx context.Context, params Params) error

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).

func SyncSessionMetadata added in v5.26.0

func SyncSessionMetadata(ctx context.Context, client *copilot.Client, appDir string) error

SyncSessionMetadata synchronizes local session files with SDK sessions. It removes local session files that no longer exist in the SDK (excluding remote sessions). Returns an error if sync fails (caller should display as non-blocking toast).

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.

const (
	// AgentMode allows full tool execution with permission prompts for write operations.
	AgentMode ChatMode = iota
	// PlanMode blocks all tool execution; the model describes what it would do.
	PlanMode
	// AskMode allows read-only tool execution; write tools are blocked.
	AskMode
)

func (ChatMode) Icon added in v5.32.0

func (m ChatMode) Icon() string

Icon returns the TUI icon for the chat mode.

func (ChatMode) Label added in v5.32.0

func (m ChatMode) Label() string

Label returns the icon and text label for the chat mode (e.g. "</> agent").

func (ChatMode) Next added in v5.32.0

func (m ChatMode) Next() ChatMode

Next cycles to the next chat mode: Agent -> Plan -> Ask -> Agent.

func (ChatMode) String added in v5.32.0

func (m ChatMode) String() string

String returns a human-readable label for the chat mode.

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

type CommandBuilder func(args map[string]any) string

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
	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

func (k KeyMap) FullHelp() [][]key.Binding

FullHelp returns keybindings for the expanded help view (overlay). This implements help.KeyMap interface.

func (KeyMap) PermissionShortHelp added in v5.26.0

func (k KeyMap) PermissionShortHelp() []key.Binding

PermissionShortHelp returns keybindings for the permission modal.

func (KeyMap) PickerShortHelp added in v5.26.0

func (k KeyMap) PickerShortHelp() []key.Binding

PickerShortHelp returns keybindings for picker modals.

func (KeyMap) SessionPickerShortHelp added in v5.26.0

func (k KeyMap) SessionPickerShortHelp() []key.Binding

SessionPickerShortHelp returns keybindings for the session picker.

func (KeyMap) ShortHelp added in v5.26.0

func (k KeyMap) ShortHelp() []key.Binding

ShortHelp returns keybindings for the mini help view (footer). This implements help.KeyMap interface.

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

func NewModeRef(initial bool) *ModeRef

NewModeRef creates a new ModeRef with the given initial state.

func (*ModeRef) IsEnabled added in v5.31.0

func (r *ModeRef) IsEnabled() bool

IsEnabled returns true if the mode is enabled.

func (*ModeRef) SetEnabled added in v5.31.0

func (r *ModeRef) SetEnabled(enabled bool)

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

func NewModel(params Params) *Model

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

func (m *Model) GetEventChannel() chan tea.Msg

GetEventChannel returns the model's event channel for external use. This is useful for creating permission handlers that can send events to the TUI.

func (*Model) Init

func (m *Model) Init() tea.Cmd

Init initializes the model and returns an initial command.

func (*Model) Update

func (m *Model) Update(
	msg tea.Msg,
) (tea.Model, tea.Cmd)

Update handles messages and updates the model.

func (*Model) View

func (m *Model) View() string

View renders 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 GetMostRecentSession added in v5.25.0

func GetMostRecentSession(
	ctx context.Context,
	client *copilot.Client,
	appDir string,
) (*SessionMetadata, error)

GetMostRecentSession returns the most recently updated session metadata. Returns ErrNoSessions if no sessions exist.

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 ThemeConfig added in v5.31.2

type ThemeConfig struct {
	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

	// 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

type ToolOutputChunkMsg struct {
	ToolID string
	Chunk  string
}

ToolOutputChunkMsg is the exported version of toolOutputChunkMsg for external use.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL