util

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultTerminalWidth  = 120
	DefaultTerminalHeight = 80

	DefaultElementsPadding = 2
)

Defaults

View Source
const (
	PromptPaneHeight      = 6
	PromptPanePadding     = 2
	PromptPaneMarginTop   = 0
	StatusBarPaneHeight   = 5
	EditModeUIElementsSum = 4

	ChatPaneMarginRight = 1
	SidePaneLeftPadding = 5

	// A 'counterweight' is a sum of other elements' margins and paggings
	// The counterweight needs to be subtracted when calculating pane sizes
	// in order to properly align elements
	SettingsPaneHeightCounterweight = 3
	SessionsPaneHeightCounterweight = 4 // TODO: info pane hight
	ChatPaneVisualModeCounterweight = 2
)

Panes

View Source
const (
	ListRightShiftedItemPadding    = -2
	TextSelectorMaxWidthCorrection = 6
	InputContainerDelta            = 5

	ListItemMarginLeft  = 2
	ListItemPaddingLeft = 2

	WidthMinScalingLimit  = 120
	HeightMinScalingLimit = 46

	ListItemTrimThreshold  = 10
	ListItemTrimCharAmount = 14
)

UI elements

View Source
const (
	OpenAiProviderType     = "openai"
	GeminiProviderType     = "gemini"
	OpenrouterProviderType = "openrouter"
)
View Source
const ActiveDot = "■"
View Source
const ChunkIndexStart = 1
View Source
const DefaultRequestTimeOutSec = 5
View Source
const DefaultSettingsId = 0
View Source
const ErrorHelp = "" /* 131-byte string literal not displayed */
View Source
const FrequencyRange = "[-2.0, 2.0)"
View Source
const InactiveDot = "•"
View Source
const ListHeadingDot = "■"
View Source
const QuickChatWarning = "" /* 135-byte string literal not displayed */
View Source
const TemperatureRange = "[0.0, 2.0]"
View Source
const TipsSeparator = " • "
View Source
const TopPRange = "[0.0, 1.0]"
View Source
const WordWrapDelta = 7

Variables

View Source
var (
	NormalFocusPanes = []Pane{SettingsPane, SessionsPane, PromptPane, ChatPane}
	ZenFocusPanes    = []Pane{PromptPane, ChatPane}
)
View Source
var DeleteSessionValidator = func(input string) error {
	allowed := []string{"y", "n"}
	if len(input) > 1 || !slices.Contains(allowed, input) {
		return errors.New("Invalid input")
	}
	return nil
}
View Source
var EmptyValidator = func(input string) error {
	return nil
}
View Source
var FrequencyValidator = func(input string) error {
	return validateRangedFloat(input, -2.0, 2.0, false, true)
}
View Source
var HelpStyle = lipgloss.NewStyle().Padding(0, 0, 0, 2).Foreground(SubduedColor)
View Source
var ManualContent string
View Source
var MaxTokensValidator = func(input string) error {
	if input == "" {
		return nil
	}

	min := 0
	max := 1_000_000
	val, err := strconv.Atoi(input)
	if err != nil {
		return err
	}

	if val <= min || val > max {
		logOutOfRange(val, min, max)
		return fmt.Errorf("value %d out of range (%d, %d)", val, min, max)
	}

	return nil
}
View Source
var Slog *slog.Logger
View Source
var SubduedColor = lipgloss.AdaptiveColor{Light: "#9B9B9B", Dark: "#5C5C5C"}
View Source
var TemperatureValidator = func(input string) error {
	return validateRangedFloat(input, 0.0, 2.0, false, false)
}
View Source
var TopPValidator = func(input string) error {
	return validateRangedFloat(input, 0.0, 1.0, false, false)
}

Functions

func AddNewSession

func AddNewSession(isTemporary bool) tea.Cmd

func CalcChatPaneSize

func CalcChatPaneSize(tw, th int, mode ViewMode) (w, h int)

func CalcMaxSettingItemWidth

func CalcMaxSettingItemWidth(containerWidth int) int

func CalcModelsListSize

func CalcModelsListSize(tw, th int) (w, h int)

func CalcPromptPaneSize

func CalcPromptPaneSize(tw, th int, mode ViewMode) (w, h int)

func CalcSessionsListSize

func CalcSessionsListSize(tw, th, tipsOffset int) (w, h int)

func CalcSessionsPaneSize

func CalcSessionsPaneSize(tw, th int) (w, h int)

func CalcSettingsPaneSize

func CalcSettingsPaneSize(tw, th int) (w, h int)

func CalcVisualModeViewSize

func CalcVisualModeViewSize(tw, th int) (w, h int)

func CleanContent added in v0.8.0

func CleanContent(content string) string

func DeleteFilesIfDevMode

func DeleteFilesIfDevMode()

func GetAppDataPath

func GetAppDataPath() (string, error)

func GetAppDirName

func GetAppDirName() string

func GetFilteredModelList

func GetFilteredModelList(providerType string, apiUrl string, models []string) []string

func GetManual

func GetManual(w int, colors SchemeColors) string

func GetMessagesAsPrettyString

func GetMessagesAsPrettyString(
	msgsToRender []LocalStoreMessage,
	w int,
	colors SchemeColors,
	isQuickChat bool,
	settings Settings,
) string

func GetNextProcessResultId added in v0.8.0

func GetNextProcessResultId(chatMsgs []LocalStoreMessage) int

func GetQuickChatDisclaimer

func GetQuickChatDisclaimer(w int, colors SchemeColors) string

func GetVisualModeView

func GetVisualModeView(msgsToRender []LocalStoreMessage, w int, colors SchemeColors, settings Settings) string

func InitDb

func InitDb() *sql.DB

func IsFocusAllowed

func IsFocusAllowed(mode ViewMode, pane Pane, tw int) bool

func IsProcessingActive added in v0.8.0

func IsProcessingActive(state ProcessingState) bool

func IsSystemMessageSupported

func IsSystemMessageSupported(provider ApiProvider, model string) bool

func MakeErrorMsg

func MakeErrorMsg(v string) tea.Cmd

func MakeFocusMsg

func MakeFocusMsg(v bool) tea.Msg

func MigrateFS

func MigrateFS(db *sql.DB, migrationsFS fs.FS, dir string) error

func PurgeModelsCache

func PurgeModelsCache(db *sql.DB) error

func RemoveDuplicates

func RemoveDuplicates[T comparable](slice []T) []T

func RenderBotChunk added in v0.8.0

func RenderBotChunk(
	chunk string,
	width int,
	colors SchemeColors) string

func RenderBotMessage

func RenderBotMessage(
	msg LocalStoreMessage,
	width int,
	colors SchemeColors,
	isVisualMode bool,
	settings Settings,
) string

func RenderErrorMessage

func RenderErrorMessage(msg string, width int, colors SchemeColors) string

func RenderToolCall added in v0.8.0

func RenderToolCall(
	msg LocalStoreMessage,
	width int,
	colors SchemeColors,
	isVisualMode bool,
	settings Settings) string

func RenderUserMessage

func RenderUserMessage(userMessage LocalStoreMessage, width int, colors SchemeColors, isVisualMode bool) string

func SendAsyncDependencyReadyMsg

func SendAsyncDependencyReadyMsg(dependency AsyncDependency) tea.Cmd

func SendCopyAllMsgs

func SendCopyAllMsgs() tea.Msg

func SendCopyLastMsg

func SendCopyLastMsg() tea.Msg

func SendNotificationMsg

func SendNotificationMsg(notification Notification) tea.Cmd

func SendProcessingStateChangedMsg

func SendProcessingStateChangedMsg(processingState ProcessingState) tea.Cmd

func SendPromptReadyMsg

func SendPromptReadyMsg(prompt string, attachments []Attachment) tea.Cmd

func SendViewModeChangedMsg

func SendViewModeChangedMsg(mode ViewMode) tea.Cmd

func SortByNumberDesc added in v0.8.0

func SortByNumberDesc[T any, V int | int64 | float64](slice []T, keyFunc func(T) V)

func StripAnsiCodes

func StripAnsiCodes(str string) string

func SwitchToEditor

func SwitchToEditor(content string, op Operation, isFocused bool) tea.Cmd

func TransformRequestHeaders

func TransformRequestHeaders(provider ApiProvider, params map[string]any) map[string]any

func TrimListItem

func TrimListItem(value string, listWidth int) string

func UpdateSystemPrompt

func UpdateSystemPrompt(prompt string) tea.Cmd

func WriteToResponseChannel added in v0.8.0

func WriteToResponseChannel(ctx context.Context, ch chan<- ProcessApiCompletionResponse, msg ProcessApiCompletionResponse)

Types

type AddNewSessionMsg

type AddNewSessionMsg struct {
	IsTemporary bool
}

type ApiProvider

type ApiProvider int
const (
	OpenAi ApiProvider = iota
	Local
	Mistral
	Gemini
	Openrouter
)

func GetOpenAiInferenceProvider

func GetOpenAiInferenceProvider(providerType string, apiUrl string) ApiProvider

type AsyncDependency

type AsyncDependency int
const (
	SettingsPaneModule AsyncDependency = iota
	Orchestrator
)

type AsyncDependencyReady

type AsyncDependencyReady struct {
	Dependency AsyncDependency
}

type Attachment added in v0.7.9

type Attachment struct {
	Path    string `json:"path"`
	Content string `json:"content"`
	Type    string `json:"type"`
}

type Choice

type Choice struct {
	Index        int            `json:"index"`
	Delta        map[string]any `json:"delta"`
	ToolCalls    []ToolCall     `json:"tool_calls"`
	FinishReason string         `json:"finish_reason"`
}

type ColorScheme

type ColorScheme string
const (
	OriginalPink ColorScheme = "pink"
	SmoothBlue   ColorScheme = "blue"
	Groovebox    ColorScheme = "groove"
)

func (ColorScheme) GetColors

func (s ColorScheme) GetColors() SchemeColors

type CompletionChunk

type CompletionChunk struct {
	ID               string      `json:"id"`
	Object           string      `json:"object"`
	Created          int         `json:"created"`
	Model            string      `json:"model"`
	SystemFingerpint string      `json:"system_fingerprint"`
	Choices          []Choice    `json:"choices"`
	Usage            *TokenUsage `json:"usage"`
}

type CompletionResponse

type CompletionResponse struct {
	Data CompletionChunk `json:"data"`
}

type CopyAllMsgs

type CopyAllMsgs struct{}

type CopyLastMsg

type CopyLastMsg struct{}

type ErrorEvent

type ErrorEvent struct {
	Message string
}

type FocusEvent

type FocusEvent struct {
	IsFocused bool
}

type LlmClient

type LlmClient interface {
	RequestCompletion(
		ctx context.Context,
		chatMsgs []LocalStoreMessage,
		modelSettings Settings,
		resultChan chan ProcessApiCompletionResponse,
	) tea.Cmd
	RequestModelsList(ctx context.Context) ProcessModelsResponse
}

type LocalStoreMessage added in v0.7.9

type LocalStoreMessage struct {
	Model       string       `json:"model"`
	Role        string       `json:"role"`
	Content     string       `json:"content"`
	Resoning    string       `json:"reasoning"`
	Attachments []Attachment `json:"attachments"`
	ToolCalls   []ToolCall   `json:"tool_calls"`
}

type ModelDescription

type ModelDescription struct {
	Id      string `json:"id"`
	Object  string `json:"object"`
	Created int64  `json:"created"`
	OwnedBy string `json:"owned_by"`
}

type ModelsListResponse

type ModelsListResponse struct {
	Object string             `json:"object"`
	Data   []ModelDescription `json:"data"`
}

func (ModelsListResponse) GetModelNamesFromResponse

func (m ModelsListResponse) GetModelNamesFromResponse() []string

type ModelsLoaded

type ModelsLoaded struct {
	Models []string
}

type Notification

type Notification int
const (
	CopiedNotification Notification = iota
	CancelledNotification
	SysPromptChangedNotification
	PresetSavedNotification
	SessionSavedNotification
)

type NotificationMsg

type NotificationMsg struct {
	Notification Notification
}

type OpenTextEditorMsg

type OpenTextEditorMsg struct {
	Content   string
	Operation Operation
	IsFocused bool
}

type Operation

type Operation int
const (
	NoOperaton Operation = iota
	SystemMessageEditing
)

type Pane

type Pane int
const (
	SettingsPane Pane = iota
	SessionsPane
	PromptPane
	ChatPane
)

fake enum to keep tab of the currently focused pane

func GetNewFocusMode

func GetNewFocusMode(mode ViewMode, currentFocus Pane, tw int, isBackward bool) Pane

type ProcessApiCompletionResponse

type ProcessApiCompletionResponse struct {
	ID     int
	Result CompletionChunk // or whatever type you need
	Err    error
	Final  bool
}

type ProcessModelsResponse

type ProcessModelsResponse struct {
	Result ModelsListResponse
	Err    error
	Final  bool
}

type ProcessingState added in v0.8.0

type ProcessingState int
const (
	Idle ProcessingState = iota
	ProcessingChunks
	AwaitingToolCallResult
	AwaitingFinalization
	Finalized
	Error
)

type ProcessingStateChanged

type ProcessingStateChanged struct {
	State ProcessingState
}

type PrompInputMode

type PrompInputMode int
const (
	PromptInsertMode PrompInputMode = iota
	PromptNormalMode
)

type PromptReady

type PromptReady struct {
	Prompt      string
	Attachments []Attachment
}

type SchemeColors

type SchemeColors struct {
	MainColor            lipgloss.AdaptiveColor
	AccentColor          lipgloss.AdaptiveColor
	HighlightColor       lipgloss.AdaptiveColor
	DefaultTextColor     lipgloss.AdaptiveColor
	ErrorColor           lipgloss.AdaptiveColor
	NormalTabBorderColor lipgloss.AdaptiveColor
	ActiveTabBorderColor lipgloss.AdaptiveColor
	RendererThemeOption  glamour.TermRendererOption
}

type Settings

type Settings struct {
	ID               int
	Model            string
	MaxTokens        int
	Frequency        *float32
	SystemPrompt     *string
	TopP             *float32
	Temperature      *float32
	PresetName       string
	WebSearchEnabled bool
	HideReasoning    bool
}

type SwitchToPaneMsg

type SwitchToPaneMsg struct {
	Target Pane
}

type SystemPromptUpdatedMsg

type SystemPromptUpdatedMsg struct {
	SystemPrompt string
}

type TokenUsage

type TokenUsage struct {
	Prompt     int `json:"prompt_tokens"`
	Completion int `json:"completion_tokens"`
	Total      int `json:"total_tokens"`
}

type ToolCall added in v0.8.0

type ToolCall struct {
	Id       string       `json:"id"`
	Type     string       `json:"type"`
	Function ToolFunction `json:"function"`
	Result   *string      `json:"result"`
}

type ToolFunction added in v0.8.0

type ToolFunction struct {
	Args map[string]string `json:"arguments"`
	Name string            `json:"name"`
}

type ViewMode

type ViewMode int
const (
	ZenMode ViewMode = iota
	TextEditMode
	NormalMode
	FilePickerMode
)

type ViewModeChanged

type ViewModeChanged struct {
	Mode ViewMode
}

Jump to

Keyboard shortcuts

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