conversation

package
v0.266.2 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

conversation

What - the conversation bounded context: sessions, message history, the message queue, compaction, pricing, token estimation and title generation. Why - a chat is state that outlives one turn and can sit in any of several storage backends, so it is a domain of its own rather than a field on the agent. How - the agent talks to the domain/ contracts, and persistent_conversation.go implements them over the configured storage backend.

How it plugs in

  • The storage backends (jsonl, SQLite, PostgreSQL, Redis, Cloudflare D1, and in-memory when storage is off) live in internal/platform/storage. The agent never learns which one is configured.
  • internal/container/container.go builds the service and the storage from storage.* config.
  • conversation_optimizer.go compacts history into a checkpoint. What must survive verbatim (loaded skills) is decided by the agent context through the optimizer's RestoreContext hook, wired in the container.
  • infer conversations, infer export, infer conversation-title and the /conversations shortcut are thin adapters over this context.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewConversationOptimizer

func NewConversationOptimizer(cfg OptimizerConfig) convdomain.ConversationOptimizer

NewConversationOptimizer creates a new conversation optimizer with configuration

func NewPricingService

func NewPricingService(cfg *config.PricingConfig) convdomain.PricingService

NewPricingService creates a new pricing service instance.

func PlanExecutionPrompt added in v0.239.0

func PlanExecutionPrompt(planID string) string

PlanExecutionPrompt tells the agent to resume and execute an approved plan. The plan runs in a fresh session, so the prompt points the agent back at the stored plan instead of keeping the planning conversation in context.

func ProcessLog added in v0.254.0

func ProcessLog() convdomain.ProblemLog

ProcessLog is the ProblemLog a session reads its own process's warnings and errors from.

func RecordModels added in v0.239.0

func RecordModels(catalog []sdk.Model) []string

RecordModels publishes the context windows, prices and modalities of the gateway's models to this process and returns the ids of the chat models. Models whose modalities the gateway does not report are left out.

func ReseedConversation added in v0.239.0

func ReseedConversation(repo convdomain.ConversationRepository, messages []sdk.Message, model string) error

ReseedConversation starts a fresh conversation titled "Continued from <old title>" and seeds it with the given messages. The old conversation is preserved in storage. Per-message save failures are logged, not returned.

func SanitizeNextStepSuggestion added in v0.229.0

func SanitizeNextStepSuggestion(raw string) string

SanitizeNextStepSuggestion applies the suggestion output contract: one plain-text line, no surrounding quotes or code fences, at most maxSuggestionChars. Empty and multi-line answers are discarded.

func StartPlanExecution added in v0.239.0

func StartPlanExecution(repo convdomain.ConversationRepository, planID string) error

StartPlanExecution starts the session an approved plan runs in: a fresh conversation titled after the planning one, opened by a hidden message that points the agent at the stored plan. The planning conversation stays stored.

func VisibleMessages added in v0.239.0

func VisibleMessages(entries []convdomain.ConversationEntry) []sdk.Message

VisibleMessages is the message set a compaction sees: hidden entries are dropped so a gate and the compaction itself estimate the same conversation.

Types

type ChatSuggestionGenerator added in v0.229.0

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

ChatSuggestionGenerator produces the one-line next-step suggestion shown as ghost text in the chat input after an assistant turn completes. Unlike the judge it is a convenience call with silent-fail semantics: every problem - disabled, misconfigured, failed request, non-conforming answer - yields no suggestion. Actionable outcomes log at warn, the rest at debug.

func NewChatSuggestionGenerator added in v0.229.0

func NewChatSuggestionGenerator(client sdk.Client, repo convdomain.ConversationRepository, config *config.Config, currentModel func() string, recorder SuggestionTelemetryRecorder) *ChatSuggestionGenerator

NewChatSuggestionGenerator creates the generator. currentModel reports the chat's active model (the fallback when chat.suggestions.model is empty) and recorder is optional telemetry. The repo receives the call's tokens either way.

func (*ChatSuggestionGenerator) GenerateNextStepSuggestion added in v0.229.0

func (g *ChatSuggestionGenerator) GenerateNextStepSuggestion(ctx context.Context) string

GenerateNextStepSuggestion asks the configured model for a one-line follow-up suggestion grounded in the most recent conversation messages. Returns "" for every failure shape and never surfaces an error.

func (*ChatSuggestionGenerator) ReadingLogs added in v0.254.0

func (g *ChatSuggestionGenerator) ReadingLogs(problems convdomain.ProblemLog, redact func(string) string) *ChatSuggestionGenerator

ReadingLogs lets the suggestion take the session's recent warnings and errors into account. redact masks secrets in what is sent to the model.

type ConversationOptimizer

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

ConversationOptimizer provides methods to optimize conversation history for token efficiency

func (*ConversationOptimizer) GenerateLLMSummary

func (co *ConversationOptimizer) GenerateLLMSummary(messages []sdk.Message, model string) (string, error)

GenerateLLMSummary asks the model for a structured checkpoint of messages. An empty reply is an error so the caller keeps the original messages rather than dropping history without a summary.

func (*ConversationOptimizer) OptimizeMessages

func (co *ConversationOptimizer) OptimizeMessages(messages []sdk.Message, model string, force bool) []sdk.Message

OptimizeMessages reduces token usage by intelligently managing conversation history with LLM summarization. When force is false it is a no-op unless the model has a configured context window and the conversation has crossed auto_at percent of it. When force is true it always compacts (manual /compact and session rollover both rely on this).

type ConversationTitleGenerator

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

ConversationTitleGenerator generates titles for conversations using AI

func NewConversationTitleGenerator

func NewConversationTitleGenerator(client sdk.Client, storage storage.ConversationStorage, config *config.Config) *ConversationTitleGenerator

NewConversationTitleGenerator creates a new conversation title generator

func (*ConversationTitleGenerator) GenerateTitleForConversation

func (g *ConversationTitleGenerator) GenerateTitleForConversation(ctx context.Context, conversationID string) error

GenerateTitleForConversation generates a title for a specific conversation

func (*ConversationTitleGenerator) InvalidateTitle

func (g *ConversationTitleGenerator) InvalidateTitle(ctx context.Context, conversationID string) error

InvalidateTitle marks a conversation title as needing regeneration

func (*ConversationTitleGenerator) ProcessPendingTitles

func (g *ConversationTitleGenerator) ProcessPendingTitles(ctx context.Context) error

ProcessPendingTitles processes a batch of conversations that need title generation

type EventBridge

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

EventBridge multicasts chat events to multiple subscribers without modifying the existing event flow to the terminal UI.

func NewEventBridge

func NewEventBridge() *EventBridge

NewEventBridge creates a new event bridge with a circular buffer

func (*EventBridge) Close

func (eb *EventBridge) Close()

Close closes all subscriber channels and clears the subscribers list

func (*EventBridge) Publish

func (eb *EventBridge) Publish(event agentdomain.ChatEvent)

Publish broadcasts an event to every subscriber. Delivery is non-blocking so one slow subscriber can never stall the bus for the others.

func (*EventBridge) Subscribe

func (eb *EventBridge) Subscribe() chan agentdomain.ChatEvent

Subscribe registers a subscriber and replays the recent-event ring buffer so backfill-less subscribers catch up on connect.

func (*EventBridge) SubscribeFuture

func (eb *EventBridge) SubscribeFuture() chan agentdomain.ChatEvent

SubscribeFuture is Subscribe without the ring-buffer replay, for subscribers that backfill history another way (the extension bridge's conversation snapshot) where a replay would double-render the last turn.

func (*EventBridge) Tap

func (eb *EventBridge) Tap(input <-chan agentdomain.ChatEvent) <-chan agentdomain.ChatEvent

Tap intercepts an event stream and multicasts it to all subscribers Returns a new channel that mirrors the input channel for the terminal UI

func (*EventBridge) Unsubscribe

func (eb *EventBridge) Unsubscribe(ch chan agentdomain.ChatEvent)

Unsubscribe removes a subscriber and closes its channel

type HTTPModelService

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

HTTPModelService implements ModelService using SDK client

func NewHTTPModelService

func NewHTTPModelService(client sdk.Client) *HTTPModelService

NewHTTPModelService creates a new HTTP-based model service with pre-configured client

func (*HTTPModelService) Catalog added in v0.239.0

func (s *HTTPModelService) Catalog() []sdk.Model

Catalog is the gateway's models as last fetched, with their context windows, prices and modalities, for a client that reads them over a daemon.

func (*HTTPModelService) GetCurrentModel

func (s *HTTPModelService) GetCurrentModel() string

func (*HTTPModelService) IsModelAvailable

func (s *HTTPModelService) IsModelAvailable(modelID string) bool

func (*HTTPModelService) ListModels

func (s *HTTPModelService) ListModels(ctx context.Context) ([]string, error)

func (*HTTPModelService) SelectModel

func (s *HTTPModelService) SelectModel(modelID string) error

func (*HTTPModelService) ValidateModel

func (s *HTTPModelService) ValidateModel(modelID string) error

type InMemoryConversationRepository

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

InMemoryConversationRepository implements ConversationRepository using in-memory storage

func NewInMemoryConversationRepository

func NewInMemoryConversationRepository(formatterService ToolFormatter, pricingService convdomain.PricingService) *InMemoryConversationRepository

NewInMemoryConversationRepository creates a new in-memory conversation repository

func (*InMemoryConversationRepository) AddCachedTokens

func (r *InMemoryConversationRepository) AddCachedTokens(tokens int)

AddCachedTokens accumulates provider-reported cached prompt tokens (usage.prompt_tokens_details.cached_tokens) into the session totals.

func (*InMemoryConversationRepository) AddMessage

func (*InMemoryConversationRepository) AddPendingToolCall

func (r *InMemoryConversationRepository) AddPendingToolCall(toolCall sdk.ChatCompletionMessageToolCall, responseChan chan agentdomain.ApprovalAction) error

AddPendingToolCall adds a pending tool call entry that requires approval

func (*InMemoryConversationRepository) AddTokenUsage

func (r *InMemoryConversationRepository) AddTokenUsage(model string, inputTokens, outputTokens, totalTokens, cachedTokens, cacheWriteTokens int) error

AddTokenUsage adds token usage from a single API call to session totals with model tracking. The model parameter is required for cost tracking. Use empty string for unknown models.

func (*InMemoryConversationRepository) Clear

func (*InMemoryConversationRepository) ClearExceptFirstUserMessage

func (r *InMemoryConversationRepository) ClearExceptFirstUserMessage() error

func (*InMemoryConversationRepository) DeleteMessagesAfterIndex

func (r *InMemoryConversationRepository) DeleteMessagesAfterIndex(index int) error

DeleteMessagesAfterIndex deletes all messages after the specified index (keeps messages from 0 to index inclusive, deletes index+1 onward)

func (*InMemoryConversationRepository) Export

func (*InMemoryConversationRepository) FormatToolResultExpanded

func (r *InMemoryConversationRepository) FormatToolResultExpanded(result *agentdomain.ToolExecutionResult, terminalWidth int) string

FormatToolResultExpanded formats expanded tool execution results

func (*InMemoryConversationRepository) FormatToolResultForLLM

func (r *InMemoryConversationRepository) FormatToolResultForLLM(result *agentdomain.ToolExecutionResult) string

FormatToolResultForLLM formats tool execution results for LLM consumption

func (*InMemoryConversationRepository) FormatToolResultForUI

func (r *InMemoryConversationRepository) FormatToolResultForUI(result *agentdomain.ToolExecutionResult, terminalWidth int) string

FormatToolResultForUI formats tool execution results for UI display

func (*InMemoryConversationRepository) GetActiveDuration added in v0.225.0

func (r *InMemoryConversationRepository) GetActiveDuration() time.Duration

GetActiveDuration returns how long the agent has worked in this session, including the run in flight.

func (*InMemoryConversationRepository) GetCurrentConversationID

func (r *InMemoryConversationRepository) GetCurrentConversationID() string

GetCurrentConversationID returns the current conversation ID (empty for in-memory)

func (*InMemoryConversationRepository) GetCurrentConversationTitle

func (r *InMemoryConversationRepository) GetCurrentConversationTitle() string

GetCurrentConversationTitle returns the current conversation title

func (*InMemoryConversationRepository) GetMessageCount

func (r *InMemoryConversationRepository) GetMessageCount() int

func (*InMemoryConversationRepository) GetMessages

func (*InMemoryConversationRepository) GetSessionCostStats

GetSessionCostStats returns the accumulated cost statistics for the session

func (*InMemoryConversationRepository) GetSessionTokens

GetSessionTokens returns the accumulated token statistics for the session

func (*InMemoryConversationRepository) LoadConversation

func (r *InMemoryConversationRepository) LoadConversation(ctx context.Context, conversationID string) error

LoadConversation always fails for in-memory storage: there is nothing persisted to load from.

func (*InMemoryConversationRepository) MarkLastMessageAsPlan

func (r *InMemoryConversationRepository) MarkLastMessageAsPlan()

MarkLastMessageAsPlan marks the last assistant message as a plan with pending approval

func (*InMemoryConversationRepository) MarkMessageAsPlanByIndex

func (r *InMemoryConversationRepository) MarkMessageAsPlanByIndex(index int)

MarkMessageAsPlanByIndex marks a specific message by index as a plan with pending approval

func (*InMemoryConversationRepository) RemovePendingToolCallByID

func (r *InMemoryConversationRepository) RemovePendingToolCallByID(toolCallID string)

RemovePendingToolCallByID removes a specific pending tool call by its ID

func (*InMemoryConversationRepository) RewindToPrompt added in v0.260.0

func (r *InMemoryConversationRepository) RewindToPrompt(prompt convdomain.PromptRef) error

RewindToPrompt drops the prompt and every entry after it, which puts the conversation back where the user was about to send that prompt. Unlike Clear it keeps the conversation's identity, also when no entry is left.

func (*InMemoryConversationRepository) SetSessionStats

SetSessionStats sets the session token and cost statistics (used when loading conversations)

func (*InMemoryConversationRepository) StartNewConversation

func (r *InMemoryConversationRepository) StartNewConversation(title string) error

StartNewConversation clears the current conversation (in-memory doesn't persist)

func (*InMemoryConversationRepository) StartWorking added in v0.226.0

func (r *InMemoryConversationRepository) StartWorking()

StartWorking starts the session stopwatch unless it is already running.

func (*InMemoryConversationRepository) StopWorking added in v0.226.0

func (r *InMemoryConversationRepository) StopWorking()

StopWorking banks the time worked since the stopwatch started.

func (*InMemoryConversationRepository) UpdateLastMessage

func (r *InMemoryConversationRepository) UpdateLastMessage(content string) error

func (*InMemoryConversationRepository) UpdateLastMessageToolCalls

func (r *InMemoryConversationRepository) UpdateLastMessageToolCalls(toolCalls *[]sdk.ChatCompletionMessageToolCall) error

func (*InMemoryConversationRepository) UpdatePlanStatus

UpdatePlanStatus updates the status of the most recent pending plan

func (*InMemoryConversationRepository) UpdateToolApprovalStatus

func (r *InMemoryConversationRepository) UpdateToolApprovalStatus(action agentdomain.ApprovalAction)

UpdateToolApprovalStatus updates the approval status of the most recent pending tool

type OptimizerConfig

type OptimizerConfig struct {
	Enabled           bool
	AutoAt            int
	BufferSize        int
	KeepFirstMessages int
	Client            sdk.Client
	Config            *config.Config
	Tokenizer         *TokenizerService
	Repo              convdomain.ConversationRepository
	RestoreContext    func(summarized []sdk.Message) []sdk.Message
	Strategy          config.CompactStrategy
}

OptimizerConfig configures the conversation optimizer. An optional Repo lets OptimizeMessages trigger on the gateway-reported LastInputTokens instead of an entries-only estimate. An optional RestoreContext returns messages to append after the summary, so loaded skills survive compaction verbatim.

type PersistentConversationRepository

type PersistentConversationRepository struct {
	*InMemoryConversationRepository
	// contains filtered or unexported fields
}

PersistentConversationRepository wraps the InMemoryConversationRepository and adds persistence capabilities using a storage backend. Every session it starts records the parentSessionID and invokedBy set through SetOrigin.

func NewPersistentConversationRepository

func NewPersistentConversationRepository(formatterService ToolFormatter, pricingService convdomain.PricingService, storageBackend storage.ConversationStorage) *PersistentConversationRepository

NewPersistentConversationRepository creates a new persistent conversation repository

func (*PersistentConversationRepository) AddMessage

Override AddMessage to trigger auto-save

func (*PersistentConversationRepository) AddTokenUsage

func (r *PersistentConversationRepository) AddTokenUsage(model string, inputTokens, outputTokens, totalTokens, cachedTokens, cacheWriteTokens int) error

AddTokenUsage wraps the in-memory implementation with persistence and auto-save

func (*PersistentConversationRepository) Clear

Override Clear to handle conversation state

func (*PersistentConversationRepository) Close

Close closes the storage connection

func (*PersistentConversationRepository) DeleteMessagesAfterIndex

func (r *PersistentConversationRepository) DeleteMessagesAfterIndex(index int) error

DeleteMessagesAfterIndex wraps the in-memory implementation with auto-save

func (*PersistentConversationRepository) DeleteSavedConversation

func (r *PersistentConversationRepository) DeleteSavedConversation(ctx context.Context, conversationID string) error

DeleteSavedConversation deletes a saved conversation

func (*PersistentConversationRepository) GetCurrentConversationID

func (r *PersistentConversationRepository) GetCurrentConversationID() string

GetCurrentConversationID returns the current conversation ID

func (*PersistentConversationRepository) GetCurrentConversationMetadata

func (r *PersistentConversationRepository) GetCurrentConversationMetadata() convdomain.ConversationMetadata

GetCurrentConversationMetadata returns the current conversation metadata

func (*PersistentConversationRepository) GetCurrentConversationTitle

func (r *PersistentConversationRepository) GetCurrentConversationTitle() string

GetCurrentConversationTitle returns the current conversation title

func (*PersistentConversationRepository) ListSavedConversations

func (r *PersistentConversationRepository) ListSavedConversations(ctx context.Context, limit, offset int) ([]convdomain.ConversationSummary, error)

ListSavedConversations returns a list of saved conversations

func (*PersistentConversationRepository) LoadConversation

func (r *PersistentConversationRepository) LoadConversation(ctx context.Context, conversationID string) error

LoadConversation loads a conversation from persistent storage

func (*PersistentConversationRepository) RewindToPrompt added in v0.260.0

func (r *PersistentConversationRepository) RewindToPrompt(prompt convdomain.PromptRef) error

RewindToPrompt wraps the in-memory implementation with auto-save

func (*PersistentConversationRepository) SaveConversation

func (r *PersistentConversationRepository) SaveConversation(ctx context.Context) error

SaveConversation saves the current conversation to persistent storage

func (*PersistentConversationRepository) SetA2ATaskTracker

func (r *PersistentConversationRepository) SetA2ATaskTracker(taskTracker a2adomain.Clearer)

SetA2ATaskTracker sets the task tracker for context ID persistence

func (*PersistentConversationRepository) SetAutoSave

func (r *PersistentConversationRepository) SetAutoSave(enabled bool)

SetAutoSave enables or disables automatic saving after each operation

func (*PersistentConversationRepository) SetConversationID

func (r *PersistentConversationRepository) SetConversationID(id string)

SetConversationID pre-sets the conversation ID so that subsequent AddMessage calls use this ID instead of generating a random one. This is used when resuming a session by ID that doesn't exist yet in storage, so the session records its parent and starter the way a freshly started one does.

func (*PersistentConversationRepository) SetConversationTags

func (r *PersistentConversationRepository) SetConversationTags(tags []string)

SetConversationTags sets tags for the current conversation

func (*PersistentConversationRepository) SetConversationTitle

func (r *PersistentConversationRepository) SetConversationTitle(title string)

SetConversationTitle sets the title for the current conversation

func (*PersistentConversationRepository) SetOrigin added in v0.265.3

func (r *PersistentConversationRepository) SetOrigin(parentSessionID, invokedBy string)

SetOrigin sets who started this process's sessions: the session that spawned it as a subagent and the starter it names. Both empty mean a human.

func (*PersistentConversationRepository) SetTitleGenerator

func (r *PersistentConversationRepository) SetTitleGenerator(titleGenerator *ConversationTitleGenerator)

SetTitleGenerator sets the title generator for automatic title invalidation

func (*PersistentConversationRepository) StartNewConversation

func (r *PersistentConversationRepository) StartNewConversation(title string) error

StartNewConversation saves the current conversation (if any), then begins a new conversation with a unique ID

type PricingService added in v0.207.0

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

PricingService implements the PricingService interface.

func (*PricingService) CalculateCost added in v0.207.0

func (p *PricingService) CalculateCost(model string, inputTokens, outputTokens, cachedTokens, cacheWriteTokens int) (inputCost, outputCost, totalCost float64)

CalculateCost returns the input, output and total cost in the configured currency. cachedTokens and cacheWriteTokens are subsets of inputTokens billed at the gateway's cache rates when known and the input rate otherwise. Subscription models are a flat fee, so they cost zero here.

func (*PricingService) FormatModelPricing added in v0.207.0

func (p *PricingService) FormatModelPricing(model string) string

FormatModelPricing returns a formatted string describing the model's pricing. Returns empty string if pricing is disabled or the model has no pricing entry (callers should not assume "no entry" means "free"). Returns "free" only when an explicit pricing entry sets both prices to 0.0. Returns "$X.XX/$Y.YY per MTok" for paid models.

func (*PricingService) GetInputPrice added in v0.207.0

func (p *PricingService) GetInputPrice(model string) float64

GetInputPrice retrieves the input price per million tokens for a specific model. Returns 0.0 for unknown models (e.g., Ollama, custom models).

func (*PricingService) GetOutputPrice added in v0.207.0

func (p *PricingService) GetOutputPrice(model string) float64

GetOutputPrice retrieves the output price per million tokens for a specific model. Returns 0.0 for unknown models (e.g., Ollama, custom models).

func (*PricingService) IsEnabled added in v0.207.0

func (p *PricingService) IsEnabled() bool

IsEnabled returns whether pricing is enabled in the configuration.

func (*PricingService) RequiresPro added in v0.207.0

func (p *PricingService) RequiresPro(model string) bool

RequiresPro reports whether the model is gated behind a paid Pro subscription. Returns false when pricing is disabled or the model has no entry.

type SessionRollover added in v0.207.0

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

SessionRollover decides when a long conversation rolls over into a new file, like the chat `/compact`, and performs it. It also resolves channel group keys such as `channel-telegram-XYZ` to the group's current session UUID, so callers keep a stable identifier whatever session it points at.

func NewSessionRollover added in v0.207.0

NewSessionRollover constructs a SessionRollover. Without an optimizer, ShouldRollover is always false and PerformRollover fails, like /compact with the optimizer disabled. Without a groupStore, group keys pass through as raw ids.

func (*SessionRollover) MaybeRollover added in v0.207.0

func (m *SessionRollover) MaybeRollover(ctx context.Context, model, groupKey string) (string, bool)

MaybeRollover combines the ShouldRollover gate with PerformRollover and the uniform warn-on-failure fallback that both `chat` and `infer headless` need. Returns the new session id and true if a rollover fired. "" and false otherwise (whether because the gate was closed or because PerformRollover errored - callers do not need to distinguish).

func (*SessionRollover) PerformRollover added in v0.207.0

func (m *SessionRollover) PerformRollover(ctx context.Context, model, groupKey string) (string, error)

PerformRollover summarizes the conversation with force=true, starts a fresh conversation file reseeded with the summary through ReseedConversation, like /compact, and points groupKey at the new session when set. It returns the new session UUID.

func (*SessionRollover) ResolveSessionID added in v0.207.0

func (m *SessionRollover) ResolveSessionID(rawID string) (string, string, error)

ResolveSessionID maps a raw --session-id to the conversation ID to load and its group key. A UUID is returned unchanged with no group key. Anything else is a group key resolved to its current session, registering rawID as that session when the group is new. A store error is logged and rawID passes through so the agent still runs.

func (*SessionRollover) ShouldRollover added in v0.207.0

func (m *SessionRollover) ShouldRollover(model string) bool

ShouldRollover checks the currently loaded conversation in the repo against both rollover triggers (idle and token threshold) and returns true if either fires. Returns false on a fresh/empty conversation, when the optimizer is disabled, or when compact.enabled=false.

type SuggestionTelemetryRecorder added in v0.229.0

type SuggestionTelemetryRecorder interface {
	RecordUsage(model string, promptTokens, completionTokens, cachedTokens, cacheWriteTokens int)
}

SuggestionTelemetryRecorder is the slice of the telemetry recorder the suggestion call needs to mirror judge usage accounting.

type TokenizerConfig

type TokenizerConfig struct {
	CharsPerToken float64

	MessageOverhead int

	ToolCallOverhead int
}

TokenizerConfig configures the tokenizer service. The defaults are 4.0 characters per token, 4 tokens of overhead per message and 10 per tool call.

func DefaultTokenizerConfig

func DefaultTokenizerConfig() TokenizerConfig

DefaultTokenizerConfig returns the default tokenizer configuration

type TokenizerService

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

TokenizerService estimates token counts for providers such as Ollama Cloud that return no usage metrics, from an average of characters per token plus fixed overheads per message and per tool call.

func NewTokenizerService

func NewTokenizerService(config TokenizerConfig) *TokenizerService

NewTokenizerService creates a new tokenizer service with the given configuration

func (*TokenizerService) CalculateUsagePolyfill

func (t *TokenizerService) CalculateUsagePolyfill(
	inputMessages []sdk.Message,
	outputContent string,
	outputToolCalls []sdk.ChatCompletionMessageToolCall,
	tools []sdk.ChatCompletionTool,
) *sdk.CompletionUsage

CalculateUsagePolyfill creates a CompletionUsage estimate for providers that don't return usage metrics. This is the main entry point for the polyfill.

func (*TokenizerService) EffectiveContextTokens

func (t *TokenizerService) EffectiveContextTokens(lastInputTokens int, messages []sdk.Message) int

EffectiveContextTokens returns the larger of lastInputTokens and a fresh estimate, so a single-turn tool-output spike isn't masked by a stale count.

func (*TokenizerService) EstimateMessageTokens

func (t *TokenizerService) EstimateMessageTokens(msg sdk.Message) int

EstimateMessageTokens estimates the total tokens for a single message

func (*TokenizerService) EstimateMessagesTokens

func (t *TokenizerService) EstimateMessagesTokens(messages []sdk.Message) int

EstimateMessagesTokens estimates the total tokens for a slice of messages. This is useful for estimating the prompt/input token count.

func (*TokenizerService) EstimateResponseTokens

func (t *TokenizerService) EstimateResponseTokens(response string) int

EstimateResponseTokens estimates the tokens in an LLM response string

func (*TokenizerService) EstimateTokenCount

func (t *TokenizerService) EstimateTokenCount(text string) int

EstimateTokenCount estimates the number of tokens in a text string. This uses a character-based heuristic that provides a reasonable approximation for most English text.

func (*TokenizerService) EstimateToolDefinitionsTokens

func (t *TokenizerService) EstimateToolDefinitionsTokens(tools []sdk.ChatCompletionTool) int

EstimateToolDefinitionsTokens estimates tokens for tool definitions

func (*TokenizerService) GetToolStats

func (t *TokenizerService) GetToolStats(toolService agentdomain.ToolService, agentMode agentdomain.AgentMode) (tokens int, count int)

GetToolStats returns token count and tool count for the tools advertised to the model in the given agent mode. All mid-session modes advertise the full list, ReadOnly keeps its filtered one (see Agent.advertisedTools).

func (*TokenizerService) ShouldUsePolyfill

func (t *TokenizerService) ShouldUsePolyfill(usage *sdk.CompletionUsage) bool

ShouldUsePolyfill determines if token estimation should be used based on whether the provider returned valid usage metrics

type ToolFormatter

type ToolFormatter interface {
	FormatToolCall(toolName string, args map[string]any) string
	FormatToolResultForLLM(result *agentdomain.ToolExecutionResult) string
	FormatToolResultExpanded(result *agentdomain.ToolExecutionResult, terminalWidth int) string
	FormatToolResultForUI(result *agentdomain.ToolExecutionResult, terminalWidth int) string
}

ToolFormatter is the slice of the tool-formatter service the conversation repositories use to render tool calls and results.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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