lib

package
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2025 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CalculateContextPercentage added in v1.6.0

func CalculateContextPercentage(cfg *config.Config) float64

CalculateContextPercentage calculates the percentage of context window used

func CalculateExponentialBackoff added in v1.8.0

func CalculateExponentialBackoff(attempt int, initialBackoff float64, backoffFactor float64) time.Duration

CalculateExponentialBackoff calculates retry delay using exponential backoff with jitter

func CleanupAndExit added in v1.9.0

func CleanupAndExit(cfg *config.Config, opts CleanupOptions)

CleanupAndExit performs common cleanup, optionally shows cost estimation, and exits when ExitCode >= 0. If ExitCode < 0, it performs cleanup only (no exit). Always restores cursor visibility.

func ColorizeJSONKeyValueLine added in v1.6.0

func ColorizeJSONKeyValueLine(line string, keyColor *color.Color, valueColor *color.Color) (string, bool)

ColorizeJSONKeyValueLine attempts to detect and color a JSON key/value pair on a single line

func ColorizeKVOrFallback added in v1.6.0

func ColorizeKVOrFallback(line string, keyColor *color.Color, valueColor *color.Color, fallback *color.Color) string

ColorizeKVOrFallback applies mono-palette coloring to JSON-like key/value lines

func ConfirmWithSingleKey added in v1.6.0

func ConfirmWithSingleKey(prompt string) bool

ConfirmWithSingleKey prompts the user and returns true only for 'y'/'Y'. It accepts ESC as an immediate "no" without requiring Enter. Enter defaults to "no". Falls back to line mode if raw mode is unavailable.

func CoolClearEffect added in v1.6.0

func CoolClearEffect(cfg *config.Config)

CoolClearEffect creates an animated clearing effect for the terminal

func CosineSimilarity

func CosineSimilarity(a, b []float32) float64

CosineSimilarity computes cosine similarity between two embedding vectors.

func CosineSimilarityMatrix

func CosineSimilarityMatrix(X, Y [][]float32) ([]float32, error)

CosineSimilarityMatrix computes row‑wise cosine similarity between two equal‑shaped matrices X and Y. Each of X and Y must be a slice of the same number of float32 slices, each of equal length. Returns element i: dot(X[i],Y[i]) / (‖X[i]‖ · ‖Y[i]‖).

func CountTokens added in v1.6.0

func CountTokens(text string, messages []llms.ChatMessage) int

CountTokens counts the token usage for a given text string and/or chat messages The function combines both tokens from text and the given messages

func CountTokensWithConfig added in v1.6.0

func CountTokensWithConfig(cfg *config.Config, text string, messages []llms.ChatMessage) int

CountTokensWithConfig estimates token count for text and messages based on cfg.

func DetectPricing added in v1.9.0

func DetectPricing(promptStr, completionStr string) (float64, string)

DetectPricing parses provider pricing strings and returns a representative numeric price and a short display string. The numeric price is the prompt price when available, else the completion price, else 0. Short form: "$<prompt>/$<completion>" or "$<value>".

func Display429Error added in v1.8.0

func Display429Error(err error, cfg *config.Config, maxRetries int)

Display429Error shows enhanced error information for rate limit errors

func EffectiveMaxTokens added in v1.6.0

func EffectiveMaxTokens(cfg *config.Config) int

EffectiveMaxTokens returns a display/budgeting token window; does not alter provider API limits.

func EstimateExpectedIncomingTokens added in v1.6.0

func EstimateExpectedIncomingTokens(cfg *config.Config, outgoing int) int

EstimateExpectedIncomingTokens predicts the likely size of the completion before any tokens are streamed. This is a heuristic tuned per provider.

func EstimateTokens added in v1.6.0

func EstimateTokens(cfg *config.Config, text string) int

EstimateTokens estimates token count for the given text using provider/model heuristics.

func FormatCompactNumber added in v1.6.0

func FormatCompactNumber(value int) string

FormatCompactNumber returns a compact human-readable string for integers using letter suffixes: k (thousands), M (millions), B (billions), T (trillions). Examples: 950 -> "950", 2910 -> "2.9k", 1200000 -> "1.2M".

func FormatContextPrompt added in v1.6.0

func FormatContextPrompt(cfg *config.Config, isCommand bool) string

FormatContextPrompt formats the prompt with context percentage

func FormatDuration

func FormatDuration(milliseconds int64) string

FormatDuration formats a duration in milliseconds to a human-readable string showing seconds if the duration is more than 1000ms

func FormatEditPromptWith added in v1.6.0

func FormatEditPromptWith(cfg *config.Config) string

FormatEditPrompt returns the edit-mode prompt string without any token counter or context indicator. This is used when the user toggles persistent edit mode by pressing '$'.

func FormatPrice added in v1.9.0

func FormatPrice(price float64) string

FormatPrice formats a price as a per-1M-tokens price string Auto-detects if input is per-token or already per-1M-tokens based on magnitude Examples: 0.00000015 -> "$0.15", 0.000005 -> "$5.00", 0.0 -> "Free"

func FormatPricingInfo added in v1.9.0

func FormatPricingInfo(promptPrice, completionPrice float64, detailed bool) string

FormatPricingInfo formats pricing info for display in model selector Returns short form like "$0.15/$0.6" for autocomplete and detailed for selection

func FormatTotalCostDisplay added in v1.9.0

func FormatTotalCostDisplay(summary *CostSummary) string

FormatTotalCostDisplay creates a pretty formatted cost estimation display block

func GetDefaultContextLengthForModel added in v1.9.0

func GetDefaultContextLengthForModel(model string) int

GetDefaultContextLengthForModel returns a reasonable default context length based on model name

func GetEncodingForModel added in v1.6.0

func GetEncodingForModel(provider string, model string) string

GetEncodingForModel returns a best-effort token encoding name for a provider/model. Note: This is an approximation. For non-OpenAI providers we fall back to cl100k_base.

func GetErrorMessage added in v1.8.0

func GetErrorMessage(err error) string

GetErrorMessage preserves the original error and appends a known code hint.

func GetKubeContextInfo added in v1.6.0

func GetKubeContextInfo(cfg *config.Config) (string, []string, error)

GetKubeContextInfo returns the current Kubernetes context name and cluster-info lines without printing them. The trailing diagnostic hint line from `kubectl cluster-info` is omitted to keep the output concise.

func Is429Error added in v1.8.0

func Is429Error(err error) bool

Is429Error checks if the error is a 429 rate limit error

func IsUserCancel added in v1.9.0

func IsUserCancel(err error) bool

IsUserCancel returns true if error is a user cancellation

func KubeCtxInfo

func KubeCtxInfo(cfg *config.Config) error

KubeCtxInfo shows the user which Kubernetes context is currently active

func LeadingWhitespace added in v1.6.0

func LeadingWhitespace(s string) string

LeadingWhitespace returns the run of leading spaces or tabs from s

func NewUserCancelError added in v1.9.0

func NewUserCancelError(reason string) error

NewUserCancelError creates a new user cancel error with an optional reason

func NextMono added in v1.6.0

func NextMono(palette []*color.Color, start int) *color.Color

NextMono returns the next color in a small mono palette sequence starting at offset

func ParseRetryDelay added in v1.8.0

func ParseRetryDelay(err error) (time.Duration, error)

ParseRetryDelay attempts to extract retry delay from 429 error messages Returns the parsed delay and nil error on success, or zero duration and error on failure

func ReadKey added in v1.6.0

func ReadKey(prompt string) string

ReadKey reads a single key or ANSI escape sequence (e.g., arrow keys) in raw mode and returns a normalized code string: "up", "down", "left", "right", "enter", "esc", "space", or a lowercased single-letter string (e.g., "y", "n", "e", "j", "k", "a").

func ReadSingleKey added in v1.6.0

func ReadSingleKey(prompt string) byte

ReadSingleKey prints a prompt and returns the first key pressed (raw mode if possible). Returns lowercase letter for alphabetic keys. ESC is returned as byte 27.

func RenderTerminalWindow added in v1.8.0

func RenderTerminalWindow(title string, content string, maxLines int, maxLineLen int) string

RenderTerminalWindow renders a modern terminal-like window around the given content. Content is line-trimmed and truncated with a centered ellipsis block when exceeding maxLines. Colors and accents are sourced from config.Colors to ensure consistent theming.

func RuneCount added in v1.6.0

func RuneCount(s string) int

RuneCount returns the number of runes in a string

func StartEscWatcher added in v1.9.0

func StartEscWatcher(ctx context.Context, cancel context.CancelFunc, spinnerManager *SpinnerManager, cfg *config.Config) func()

StartEscWatcher starts a raw-input watcher that cancels the context on a standalone ESC key. It ignores ANSI escape sequences (e.g., arrow keys: ESC [ A) and Alt-modified keys (ESC + key). Ctrl-C/Z/\ trigger appropriate signals and immediate exit via CleanupAndExit. Returns a stop function that restores terminal state and stops the watcher.

func Tokenize

func Tokenize(text string) []string

Tokenize uses tiktoken-go to perform proper tokenization compatible with LLMs.

func TokenizeWithEncoding added in v1.6.0

func TokenizeWithEncoding(encoding string, text string) []string

TokenizeWithEncoding tokenizes text with a specific encoding.

func TrimLine added in v1.6.0

func TrimLine(s string, maxRunes int) string

TrimLine trims a line to maxRunes and adds ellipsis if needed

func TrimText added in v1.9.0

func TrimText(text string, maxWidth ...int) string

TrimText truncates long text to fit within the specified width. If maxWidth is not provided, it attempts to detect terminal width automatically.

Types

type AtomicInt added in v1.6.0

type AtomicInt struct {
	// contains filtered or unexported fields
}

AtomicInt is a small helper for safe concurrent counters.

func (*AtomicInt) Add added in v1.6.0

func (a *AtomicInt) Add(delta int)

func (*AtomicInt) Load added in v1.6.0

func (a *AtomicInt) Load() int

func (*AtomicInt) Reset added in v1.6.0

func (a *AtomicInt) Reset()

func (*AtomicInt) Set added in v1.6.0

func (a *AtomicInt) Set(value int)

type CleanupOptions added in v1.9.0

type CleanupOptions struct {
	Message     string
	ExitCode    int
	CleanupFunc func()
}

CleanupOptions defines options for CleanupAndExit behavior.

type CostSummary added in v1.9.0

type CostSummary struct {
	InputTokens    int
	OutputTokens   int
	InputPrice     float64 // USD per token
	OutputPrice    float64 // USD per token
	InputCost      float64 // Total input cost in USD
	OutputCost     float64 // Total output cost in USD
	TotalCost      float64 // Total cost in USD
	ModelID        string
	HasPricingData bool
}

CostSummary holds token usage and cost information for a session

func CalculateTotalCost added in v1.9.0

func CalculateTotalCost(inputTokens, outputTokens int, inputPrice, outputPrice float64, modelID string) *CostSummary

CalculateTotalCost calculates the total cost for a session given token counts and per-token prices

type ModelSelector added in v1.9.0

type ModelSelector struct {
	// contains filtered or unexported fields
}

ModelSelector provides an interactive model selection interface

func NewModelSelector added in v1.9.0

func NewModelSelector(cfg *config.Config) *ModelSelector

NewModelSelector creates a new model selector instance

func (*ModelSelector) SelectModel added in v1.9.0

func (ms *ModelSelector) SelectModel() (string, error)

SelectModel launches an interactive model selection menu

type RenderBlock added in v1.6.0

type RenderBlock struct {
	Title      string
	Sections   []RenderSection
	MaxLineLen int
	MaxLines   int
}

RenderBlock builds a colored block with gradient borders and content

func (*RenderBlock) Format added in v1.6.0

func (rb *RenderBlock) Format() string

Format builds the complete formatted block as a string

type RenderSection added in v1.6.0

type RenderSection struct {
	Label   string
	Content string
}

RenderSection represents a section within a render block

type SpinnerContext added in v1.9.0

type SpinnerContext struct {
	Type    SpinnerType
	Message string
	// contains filtered or unexported fields
}

SpinnerContext represents an active spinner operation

type SpinnerManager added in v1.9.0

type SpinnerManager struct {
	// contains filtered or unexported fields
}

SpinnerManager provides thread-safe, coordinated spinner management

func GetSpinnerManager added in v1.9.0

func GetSpinnerManager(cfg *config.Config) *SpinnerManager

GetSpinnerManager returns the global spinner manager instance

func (*SpinnerManager) GetContext added in v1.9.0

func (sm *SpinnerManager) GetContext() *SpinnerContext

GetContext returns the current spinner context if active

func (*SpinnerManager) Hide added in v1.9.0

func (sm *SpinnerManager) Hide()

Hide stops the current spinner and clears the line

func (*SpinnerManager) IsActive added in v1.9.0

func (sm *SpinnerManager) IsActive() bool

IsActive returns whether a spinner is currently active

func (*SpinnerManager) Show added in v1.9.0

func (sm *SpinnerManager) Show(spinnerType SpinnerType, message string) context.CancelFunc

Show starts or updates the spinner with the given type and message

func (*SpinnerManager) ShowDiagnostic added in v1.9.0

func (sm *SpinnerManager) ShowDiagnostic(message string) context.CancelFunc

ShowDiagnostic is a convenience method for diagnostic operations

func (*SpinnerManager) ShowGeneration added in v1.9.0

func (sm *SpinnerManager) ShowGeneration(message string) context.CancelFunc

ShowGeneration is a convenience method for generation operations

func (*SpinnerManager) ShowLLM added in v1.9.0

func (sm *SpinnerManager) ShowLLM(message string) context.CancelFunc

ShowLLM is a convenience method for LLM operations

func (*SpinnerManager) ShowRAG added in v1.9.0

func (sm *SpinnerManager) ShowRAG(message string) context.CancelFunc

ShowRAG is a convenience method for RAG operations

func (*SpinnerManager) ShowThrottle added in v1.9.0

func (sm *SpinnerManager) ShowThrottle(message string, duration time.Duration) context.CancelFunc

ShowThrottle is a convenience method for throttling operations with countdown

func (*SpinnerManager) ShowWithCountdown added in v1.9.0

func (sm *SpinnerManager) ShowWithCountdown(spinnerType SpinnerType, baseMessage string, duration time.Duration) context.CancelFunc

ShowWithCountdown displays a spinner with a countdown timer

func (*SpinnerManager) Update added in v1.9.0

func (sm *SpinnerManager) Update(message string)

Update changes the message of the currently active spinner

type SpinnerType added in v1.9.0

type SpinnerType int

SpinnerType defines different spinner contexts and their visual styles

const (
	SpinnerDiagnostic SpinnerType = iota // For kubectl diagnostic commands
	SpinnerLLM                           // For LLM API calls
	SpinnerGeneration                    // For command generation
	SpinnerRAG                           // For RAG operations
	SpinnerThrottle                      // For throttling delays
)

type TokenMeter added in v1.6.0

type TokenMeter struct {
	// contains filtered or unexported fields
}

TokenMeter renders a compact real-time token counter to stderr. It shows outgoing (prompt/history) and incoming (streamed) token counts using arrows.

func NewTokenMeter added in v1.6.0

func NewTokenMeter(cfg *config.Config, outgoing int) *TokenMeter

NewTokenMeter creates a token meter with a known outgoing token count.

func (*TokenMeter) AddIncoming added in v1.6.0

func (tm *TokenMeter) AddIncoming(delta int)

AddIncoming adds to the incoming token counter and triggers a re-render.

func (*TokenMeter) AddIncomingSilent added in v1.6.0

func (tm *TokenMeter) AddIncomingSilent(delta int)

AddIncomingSilent updates incoming tokens without rendering.

func (*TokenMeter) Clear added in v1.6.0

func (tm *TokenMeter) Clear()

Clear erases the meter line from stderr.

func (*TokenMeter) Incoming added in v1.6.0

func (tm *TokenMeter) Incoming() int

Incoming returns the current accumulated incoming token count.

func (*TokenMeter) Outgoing added in v1.6.0

func (tm *TokenMeter) Outgoing() int

Outgoing returns the initial outgoing token count.

func (*TokenMeter) Render added in v1.6.0

func (tm *TokenMeter) Render()

Render redraws the meter on a single stderr line.

type UserCancelError added in v1.9.0

type UserCancelError struct {
	Reason string
}

UserCancelError indicates that the user explicitly cancelled the in-flight operation (e.g., by pressing ESC)

func (*UserCancelError) Error added in v1.9.0

func (e *UserCancelError) Error() string

Jump to

Keyboard shortcuts

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