conversations

package
v0.5.40-beta Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package conversations provides conversation management functionality for kodelet. It offers high-level services for storing, retrieving, querying, and managing conversation records with support for filtering, pagination, and statistics.

Index

Constants

View Source
const (
	ConversationNameMetadataKey     = "conversation_name"
	ConversationAutoNameMetadataKey = "conversation_auto_name"
	MessageDisplayMetadataKey       = "message_display"

	MessageDisplayVersion          = "v1"
	MessageDisplayKindSlashCommand = "slash-command"
	MessageDisplayKindGoal         = "goal"
)
View Source
const (
	DefaultMaxToolResultCharacters = 2000
	DefaultMaxToolResultBytes      = 100 * 1024
	ToolResultTruncationMarker     = "\n[ ... omitted remaining lines to make summarizing use less tokens ... ]"
)
View Source
const ConfigSnapshotMetadataKey = "config_snapshot"

Variables

View Source
var ErrCWDConflict = errors.New("requested cwd does not match conversation cwd")

ErrCWDConflict is returned when a caller requests a cwd that conflicts with an existing conversation binding.

Functions

func AddConfigSnapshot

func AddConfigSnapshot(metadata map[string]any, config llmtypes.Config) (map[string]any, error)

AddConfigSnapshot adds a versioned, sanitized effective LLM configuration snapshot to conversation metadata.

func AddMessageDisplay

func AddMessageDisplay(metadata map[string]any, modelText, displayText, kind, command string) map[string]any

AddMessageDisplay records user-facing display text in metadata.

func AddSlashCommandDisplay

func AddSlashCommandDisplay(metadata map[string]any, modelText, displayText, command string) map[string]any

AddSlashCommandDisplay records compact slash-command display text in metadata.

func ApplyDisplayToLLMMessages

func ApplyDisplayToLLMMessages(messages []llmtypes.Message, metadata map[string]any) []llmtypes.Message

ApplyDisplayToLLMMessages returns a copy of messages with display metadata applied to user messages.

func AutomaticConversationName

func AutomaticConversationName(metadata map[string]any) string

AutomaticConversationName returns the persisted first-message name, if present.

func ConfigSnapshotFromMetadata

func ConfigSnapshotFromMetadata(metadata map[string]any) (*llmtypes.ConversationConfigSnapshot, bool, error)

ConfigSnapshotFromMetadata decodes and validates a persisted configuration snapshot. The boolean is false for legacy conversations without a snapshot.

func ContextWithConversationForkName

func ContextWithConversationForkName(ctx context.Context, name string) context.Context

ContextWithConversationForkName attaches an explicit name requested for a new fork.

func ConversationForkNameFromContext

func ConversationForkNameFromContext(ctx context.Context) string

ConversationForkNameFromContext returns the explicit name requested for a new fork.

func CurrentWorkingDirectory

func CurrentWorkingDirectory() (string, error)

CurrentWorkingDirectory returns the canonical current process working directory.

func EnsureConversationName

func EnsureConversationName(metadata map[string]any, fallback string) (map[string]any, string)

EnsureConversationName persists the deterministic fallback the first time it is available.

func ExplicitConversationName

func ExplicitConversationName(metadata map[string]any) string

ExplicitConversationName returns the user-provided conversation name, if present.

func GetMostRecentConversationID

func GetMostRecentConversationID(ctx context.Context) (string, error)

GetMostRecentConversationID returns the ID of the most recent conversation

func MessageDisplayKey

func MessageDisplayKey(text string) string

MessageDisplayKey returns the metadata lookup key for a model-facing text message.

func NormalizeCWD

func NormalizeCWD(path string) (string, error)

NormalizeCWD resolves a path into a canonical absolute directory path.

func NormalizeConversationName

func NormalizeConversationName(name string) string

NormalizeConversationName converts a conversation name into a single-line label.

func PersistConversationFork

PersistConversationFork saves an isolated fork and transfers durable runner affinity when the store supports it. Identity-bound runner metadata remains excluded from the copied record itself.

func PreserveStoredConversationName

func PreserveStoredConversationName(ctx context.Context, store ConversationStore, conversationID string, metadata map[string]any) map[string]any

PreserveStoredConversationName keeps a persisted explicit name from being overwritten by stale thread metadata.

func RenameThread

func RenameThread(ctx context.Context, thread llmtypes.Thread, name string) (string, error)

RenameThread persists an explicit name on an active conversation thread.

func RenderMarkdown

func RenderMarkdown(
	messages []StreamableMessage,
	toolResults map[string]tooltypes.StructuredToolResult,
	opts MarkdownOptions,
) string

RenderMarkdown converts conversation entries into markdown.

func ResolveConversationName

func ResolveConversationName(metadata map[string]any, fallback string) string

ResolveConversationName prefers an explicit name, then the persisted automatic name, over the deterministic fallback.

func SetAutomaticConversationName

func SetAutomaticConversationName(metadata map[string]any, name string) map[string]any

SetAutomaticConversationName records the deterministic first-message name.

func SetConversationName

func SetConversationName(metadata map[string]any, name string) map[string]any

SetConversationName records an explicit user-facing conversation name in metadata.

Types

type AtomicConversationForkStore

type AtomicConversationForkStore interface {
	SaveConversationFork(ctx context.Context, sourceConversationID string, forked conversations.ConversationRecord) error
}

AtomicConversationForkStore persists a fork and copies any durable runner affinity in the same transaction.

type CWDResolution

type CWDResolution struct {
	CWD            string
	Locked         bool
	LegacyRecord   bool
	ConversationID string
	Record         *convtypes.ConversationRecord
}

CWDResolution captures the resolved execution directory for a conversation.

func ResolveCWD

func ResolveCWD(
	ctx context.Context,
	store ConversationStore,
	conversationID string,
	requestedCWD string,
	defaultCWD string,
	requireExisting bool,
) (*CWDResolution, error)

ResolveCWD determines the effective cwd for a new or existing conversation. When requireExisting is false, a missing conversation is treated as a new one.

type Config

type Config struct {
	StoreType string // "sqlite"
	BasePath  string // Base storage path
}

Config holds configuration for the conversation store

func DefaultConfig

func DefaultConfig() (*Config, error)

DefaultConfig returns a default configuration

type ConversationRunnerAffinityStore

type ConversationRunnerAffinityStore interface {
	ConversationRunnerAffinity(ctx context.Context, conversationID string) (runnerID, environmentProfile string, ok bool, err error)
	BindConversationRunnerAffinity(ctx context.Context, conversationID, runnerID, environmentProfile string) error
}

ConversationRunnerAffinityStore is an optional store capability for transferring authoritative runner affinity to a new conversation ID.

type ConversationService

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

ConversationService provides high-level conversation operations

func GetDefaultConversationService

func GetDefaultConversationService(ctx context.Context) (*ConversationService, error)

GetDefaultConversationService returns a service with the default store

func NewConversationService

func NewConversationService(store ConversationStore) *ConversationService

NewConversationService creates a new conversation service

func (*ConversationService) Close

func (s *ConversationService) Close() error

Close closes the underlying store

func (*ConversationService) DeleteConversation

func (s *ConversationService) DeleteConversation(ctx context.Context, id string) error

DeleteConversation deletes a conversation

func (*ConversationService) ForkConversation

func (s *ConversationService) ForkConversation(ctx context.Context, id string) (*GetConversationResponse, error)

ForkConversation duplicates a conversation into a new conversation record while resetting token and cost usage counters and preserving context window data.

func (*ConversationService) GetConversation

func (s *ConversationService) GetConversation(ctx context.Context, id string) (*GetConversationResponse, error)

GetConversation retrieves a specific conversation with all its data

func (*ConversationService) GetToolResult

func (s *ConversationService) GetToolResult(ctx context.Context, conversationID, toolCallID string) (*GetToolResultResponse, error)

GetToolResult retrieves a specific tool result from a conversation

func (*ConversationService) ListConversations

ListConversations retrieves conversations with filtering and pagination

func (*ConversationService) RenameConversation

func (s *ConversationService) RenameConversation(ctx context.Context, id, name string) error

RenameConversation sets an explicit user-facing name for a persisted conversation.

type ConversationServiceInterface

type ConversationServiceInterface interface {
	ListConversations(ctx context.Context, req *ListConversationsRequest) (*ListConversationsResponse, error)
	GetConversation(ctx context.Context, id string) (*GetConversationResponse, error)
	GetToolResult(ctx context.Context, conversationID, toolCallID string) (*GetToolResultResponse, error)
	ForkConversation(ctx context.Context, id string) (*GetConversationResponse, error)
	DeleteConversation(ctx context.Context, id string) error
	Close() error
}

ConversationServiceInterface defines the interface for conversation operations

type ConversationStatistics

type ConversationStatistics struct {
	TotalConversations int     `json:"totalConversations"`
	TotalMessages      int     `json:"totalMessages"`
	TotalTokens        int     `json:"totalTokens"`
	TotalCost          float64 `json:"totalCost"`
	InputTokens        int     `json:"inputTokens"`
	OutputTokens       int     `json:"outputTokens"`
	CacheReadTokens    int     `json:"cacheReadTokens"`
	CacheWriteTokens   int     `json:"cacheWriteTokens"`
	InputCost          float64 `json:"inputCost"`
	OutputCost         float64 `json:"outputCost"`
	CacheReadCost      float64 `json:"cacheReadCost"`
	CacheWriteCost     float64 `json:"cacheWriteCost"`
}

ConversationStatistics represents conversation statistics

type ConversationStore

type ConversationStore interface {
	// Basic CRUD operations
	Save(ctx context.Context, record conversations.ConversationRecord) error
	Load(ctx context.Context, id string) (conversations.ConversationRecord, error)
	Delete(ctx context.Context, id string) error

	// Advanced query operations
	Query(ctx context.Context, options conversations.QueryOptions) (conversations.QueryResult, error)

	// Lifecycle methods
	Close() error // Close doesn't need context
}

ConversationStore defines the interface for conversation persistence

func GetConversationStore

func GetConversationStore(ctx context.Context) (ConversationStore, error)

GetConversationStore is a convenience function that creates a store with default configuration

func NewConversationStore

func NewConversationStore(ctx context.Context, config *Config) (ConversationStore, error)

NewConversationStore creates the appropriate ConversationStore implementation based on the provided configuration

type GetConversationResponse

type GetConversationResponse struct {
	ID           string                                `json:"id"`
	CWD          string                                `json:"cwd,omitempty"`
	CreatedAt    time.Time                             `json:"createdAt"`
	UpdatedAt    time.Time                             `json:"updatedAt"`
	Provider     string                                `json:"provider"`
	Summary      string                                `json:"summary,omitempty"`
	Usage        llmtypes.Usage                        `json:"usage"`
	RawMessages  json.RawMessage                       `json:"rawMessages"`
	Metadata     map[string]any                        `json:"metadata,omitempty"`
	ToolResults  map[string]tools.StructuredToolResult `json:"toolResults,omitempty"`
	MessageCount int                                   `json:"messageCount"`
}

GetConversationResponse represents the response from getting a conversation

type GetToolResultResponse

type GetToolResultResponse struct {
	ToolCallID string                     `json:"toolCallId"`
	Result     tools.StructuredToolResult `json:"result"`
}

GetToolResultResponse represents the response from getting a tool result

type ListConversationsRequest

type ListConversationsRequest struct {
	StartDate     *time.Time `json:"startDate,omitempty"`
	EndDate       *time.Time `json:"endDate,omitempty"`
	SearchTerm    string     `json:"searchTerm,omitempty"`
	SearchCWDTerm string     `json:"-"`
	CWD           string     `json:"cwd,omitempty"`
	RunnerID      string     `json:"runnerId,omitempty"`
	Limit         int        `json:"limit,omitempty"`
	Offset        int        `json:"offset,omitempty"`
	SortBy        string     `json:"sortBy,omitempty"`
	SortOrder     string     `json:"sortOrder,omitempty"`
}

ListConversationsRequest represents a request to list conversations

type ListConversationsResponse

type ListConversationsResponse struct {
	Conversations []conversations.ConversationSummary `json:"conversations"`
	Total         int                                 `json:"total"`
	CWDs          []string                            `json:"cwds,omitempty"`
	Limit         int                                 `json:"limit"`
	Offset        int                                 `json:"offset"`
	HasMore       bool                                `json:"hasMore"`
	Stats         *ConversationStatistics             `json:"stats,omitempty"`
}

ListConversationsResponse represents the response from listing conversations

type MarkdownOptions

type MarkdownOptions struct {
	TruncateToolResults bool
	MaxToolResultChars  int
	MaxToolResultBytes  int
	ExcludeThinking     bool
}

MarkdownOptions controls markdown rendering for conversation messages.

type MessageDisplay

type MessageDisplay struct {
	Text    string `json:"text"`
	Kind    string `json:"kind,omitempty"`
	Command string `json:"command,omitempty"`
}

MessageDisplay describes user-facing text for a model-facing message.

func LookupMessageDisplay

func LookupMessageDisplay(metadata map[string]any, modelText string) (MessageDisplay, bool)

LookupMessageDisplay returns user-facing display text for a model-facing message.

type StreamableMessage

type StreamableMessage struct {
	Kind       string          `json:"kind"`                 // "text", "tool-use", "tool-result", "thinking"
	Role       string          `json:"role"`                 // "user", "assistant", "system"
	Content    string          `json:"content,omitempty"`    // Text content
	RawItem    json.RawMessage `json:"rawItem,omitempty"`    // Original provider item when needed for rich content
	ToolName   string          `json:"toolName,omitempty"`   // For tool use/result
	ToolCallID string          `json:"toolCallId,omitempty"` // For matching tool results
	Input      string          `json:"input,omitempty"`      // For tool use (JSON string)
	ToolOutput string          `json:"toolOutput,omitempty"` // Display output retained alongside structured results
}

StreamableMessage represents a normalized entry from a persisted conversation.

func ApplyDisplayToStreamableMessages

func ApplyDisplayToStreamableMessages(messages []StreamableMessage, metadata map[string]any) []StreamableMessage

ApplyDisplayToStreamableMessages returns a copy of messages with display metadata applied to user text messages.

Directories

Path Synopsis
Package sqlite provides SQLite-specific implementation for conversation storage.
Package sqlite provides SQLite-specific implementation for conversation storage.

Jump to

Keyboard shortcuts

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