Documentation
¶
Index ¶
- Constants
- Variables
- func BuildAgentMessagesFromEntries(entries []ConversationEntry) []sdk.Message
- func CreateTitleFromMessage(content string) string
- func FormatChannelSessionID(channel, senderID string) string
- func FormatModelPricingLabel(pricingService PricingService, model string) string
- func IsUserBashCall(id string) bool
- func LastAssistantText(entries []ConversationEntry) string
- func NewToolCallEntries(toolCall sdk.ChatCompletionMessageToolCall, ...) (ConversationEntry, ConversationEntry)
- func NewUserBashCallID() string
- func NewUserToolCallID() string
- func ParseChannelSessionID(sessionID string) (channel, recipientID string, ok bool)
- func ToolOutcomes(entries []ConversationEntry) (succeeded, failed int)
- func ToolResultOutput(result *agentdomain.ToolExecutionResult, ...) string
- type ConversationEntry
- type ConversationMetadata
- type ConversationOptimizer
- type ConversationRepository
- type ConversationSummary
- type ExportFormat
- type LoggedProblem
- type MessageQueue
- type ModelCostStats
- type ModelService
- type PersistentConversationRepository
- type PlanApprovalStatus
- type PricingService
- type ProblemLog
- type PromptRef
- type QueuedMessage
- type QueuedMessageSource
- type SessionCostStats
- type SessionID
- type SessionRollover
- type SessionTokenStats
- type SyntheticToolResponse
- type TokenEstimator
- type ToolApprovalStatus
Constants ¶
const CancelledToolResponseContent = "[Tool execution cancelled by user before completion]"
CancelledToolResponseContent is the sentinel body used for synthetic tool responses inserted by EnsureToolCallsClosed. The wording is surfaced to the model in the next turn and to the user via the conversation view, so it must be self-explanatory and stable.
Variables ¶
var ErrConversationNotFound = errors.New("conversation not found")
ErrConversationNotFound is returned by conversation storage when a requested conversation ID does not exist. Callers use errors.Is to tell an expected miss (e.g. the first use of a caller-chosen --session-id, before anything is saved) apart from a real load failure such as a corrupt file or an unreachable store.
var ErrPromptNotFound = errors.New("the conversation has no such prompt")
ErrPromptNotFound is returned when a conversation holds no prompt a PromptRef names, so a rewind leaves it as it was.
Functions ¶
func BuildAgentMessagesFromEntries ¶ added in v0.207.0
func BuildAgentMessagesFromEntries(entries []ConversationEntry) []sdk.Message
BuildAgentMessagesFromEntries converts entries into the SDK messages sent to the model, dropping plan entries, `!command` entries and approval placeholders. The first two lack reasoning_content, which thinking providers reject, and placeholders break tool_calls adjacency.
func CreateTitleFromMessage ¶
CreateTitleFromMessage creates a short title from message content (fallback title)
func FormatChannelSessionID ¶
FormatChannelSessionID builds the session ID the daemon's channel manager uses for a channel/sender pair, the inverse of ParseChannelSessionID. ponytail: channel names must not contain '-' (they're a fixed enum today; sender IDs may contain dashes and are parsed back as the tail).
func FormatModelPricingLabel ¶
func FormatModelPricingLabel(pricingService PricingService, model string) string
FormatModelPricingLabel builds a pricing label for model that marks subscription models. A subscription model's $0 price would read "free", so that becomes "subscription", and a priced subscription model keeps its price plus the marker. It returns "" when there is nothing to show.
func IsUserBashCall ¶ added in v0.245.3
IsUserBashCall reports whether id names the tool call of a user-typed `!command`.
func LastAssistantText ¶ added in v0.207.0
func LastAssistantText(entries []ConversationEntry) string
LastAssistantText returns the trimmed content of the last non-empty assistant message in entries, or "" if there is none.
func NewToolCallEntries ¶ added in v0.182.0
func NewToolCallEntries(toolCall sdk.ChatCompletionMessageToolCall, result *agentdomain.ToolExecutionResult, content string, now time.Time) (ConversationEntry, ConversationEntry)
NewToolCallEntries builds the assistant tool_call entry and its paired tool result entry for a single directly-executed tool call, as persisted by the TUI direct-exec path and the browser extension bridge. content is what the LLM sees as the tool result on later turns.
func NewUserBashCallID ¶ added in v0.245.3
func NewUserBashCallID() string
NewUserBashCallID names the tool call a user-typed `!command` records.
func NewUserToolCallID ¶ added in v0.245.3
func NewUserToolCallID() string
NewUserToolCallID names the tool call a user-typed `!!Tool(...)` records.
func ParseChannelSessionID ¶
ParseChannelSessionID splits a "channel-<name>-<sender_id>" session ID built by the daemon's channel manager into its channel and recipient. It returns ok=false for any other session ID. Channel names cannot contain a '-', while recipient IDs may.
func ToolOutcomes ¶ added in v0.220.0
func ToolOutcomes(entries []ConversationEntry) (succeeded, failed int)
ToolOutcomes counts the executed tool calls in entries by outcome. A rejected call counts as failed.
func ToolResultOutput ¶ added in v0.200.0
func ToolResultOutput(result *agentdomain.ToolExecutionResult, formatForLLM func(*agentdomain.ToolExecutionResult) string) string
ToolResultOutput extracts the human-facing output of a tool result: combined stdout/stderr for Bash, formatForLLM otherwise, or the marshaled data when formatForLLM is nil.
Types ¶
type ConversationEntry ¶
type ConversationEntry struct {
Message sdk.Message `json:"message"`
Model string `json:"model,omitempty"`
Time time.Time `json:"time"`
Hidden bool `json:"hidden,omitempty"`
Images []agentdomain.ImageAttachment `json:"images,omitempty"`
ReasoningContent string `json:"reasoning_content,omitempty"`
ToolExecution *agentdomain.ToolExecutionResult `json:"tool_execution,omitempty"`
PendingToolCall *sdk.ChatCompletionMessageToolCall `json:"pending_tool_call,omitempty"`
ToolApprovalStatus ToolApprovalStatus `json:"tool_approval_status,omitempty"`
Rejected bool `json:"rejected,omitempty"`
IsPlan bool `json:"is_plan,omitempty"`
PlanApprovalStatus PlanApprovalStatus `json:"plan_approval_status,omitempty"`
}
ConversationEntry is a conversation message with its metadata: the model, time, visibility, images and reasoning, its tool execution and approval state, and its plan mode state.
func NewUserBashOutputEntry ¶ added in v0.245.3
func NewUserBashOutputEntry(command, output string, now time.Time) ConversationEntry
NewUserBashOutputEntry carries a user-typed `!command`'s output to the model: its tool pair is dropped from LLM history, while a hidden entry stays out of the view and still reaches the model.
type ConversationMetadata ¶
type ConversationMetadata struct {
ID string `json:"id"`
Title string `json:"title"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
MessageCount int `json:"message_count"`
TokenStats SessionTokenStats `json:"token_stats"`
CostStats SessionCostStats `json:"cost_stats,omitempty"`
Model string `json:"model,omitempty"`
Tags []string `json:"tags,omitempty"`
TitleGenerated bool `json:"title_generated,omitempty"`
TitleInvalidated bool `json:"title_invalidated,omitempty"`
TitleGenerationTime *time.Time `json:"title_generation_time,omitempty"`
ContextID string `json:"context_id,omitempty"`
ActiveDuration time.Duration `json:"active_duration,omitempty"`
ParentSessionID string `json:"parent_session_id"`
InvokedBy string `json:"invoked_by"`
Project string `json:"project"`
}
ConversationMetadata contains metadata about a conversation. ActiveDuration sums the time the agent worked across runs, ParentSessionID names the spawning orchestrator session, InvokedBy is "human" or "agent", and Project is the absolute working directory backends group conversations by.
type ConversationOptimizer ¶
type ConversationOptimizer interface {
OptimizeMessages(messages []sdk.Message, model string, force bool) []sdk.Message
}
ConversationOptimizer optimizes conversation history to reduce token usage
type ConversationRepository ¶
type ConversationRepository interface {
AddMessage(msg ConversationEntry) error
GetMessages() []ConversationEntry
Clear() error
ClearExceptFirstUserMessage() error
GetMessageCount() int
UpdateLastMessage(content string) error
UpdateLastMessageToolCalls(toolCalls *[]sdk.ChatCompletionMessageToolCall) error
DeleteMessagesAfterIndex(index int) error
RewindToPrompt(prompt PromptRef) error
AddTokenUsage(model string, inputTokens, outputTokens, totalTokens, cachedTokens, cacheWriteTokens int) error
AddCachedTokens(tokens int)
GetSessionTokens() SessionTokenStats
GetSessionCostStats() SessionCostStats
StartWorking()
StopWorking()
GetActiveDuration() time.Duration
FormatToolResultForLLM(result *agentdomain.ToolExecutionResult) string
FormatToolResultForUI(result *agentdomain.ToolExecutionResult, terminalWidth int) string
FormatToolResultExpanded(result *agentdomain.ToolExecutionResult, terminalWidth int) string
RemovePendingToolCallByID(toolCallID string)
StartNewConversation(title string) error
LoadConversation(ctx context.Context, conversationID string) error
GetCurrentConversationTitle() string
GetCurrentConversationID() string
Export(format ExportFormat) ([]byte, error)
}
ConversationRepository is the composed interface for all conversation storage and retrieval operations. New code should depend on the narrower sub-interfaces above.
type ConversationSummary ¶
type ConversationSummary struct {
ID string `json:"id"`
Title string `json:"title"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
MessageCount int `json:"message_count"`
TokenStats SessionTokenStats `json:"token_stats"`
CostStats SessionCostStats `json:"cost_stats,omitempty"`
Model string `json:"model,omitempty"`
Tags []string `json:"tags,omitempty"`
Summary string `json:"summary,omitempty"`
TitleGenerated bool `json:"title_generated,omitempty"`
TitleInvalidated bool `json:"title_invalidated,omitempty"`
TitleGenerationTime *time.Time `json:"title_generation_time,omitempty"`
ParentSessionID string `json:"parent_session_id"`
InvokedBy string `json:"invoked_by"`
Project string `json:"project,omitempty"`
Workspace string `json:"workspace,omitempty"`
}
ConversationSummary contains summary information about a conversation, with the same ParentSessionID, InvokedBy and Project as ConversationMetadata. Project is empty for legacy records, and Workspace names where a daemon chat runs.
type ExportFormat ¶
type ExportFormat string
ExportFormat defines the format for exporting conversations
const ( ExportMarkdown ExportFormat = "markdown" ExportJSON ExportFormat = "json" ExportText ExportFormat = "text" )
type LoggedProblem ¶ added in v0.254.0
type LoggedProblem struct {
Time time.Time
Severity string
Message string
Detail string
ConversationID string
}
LoggedProblem is one warning or error the session's process logged. Detail is the error behind it, empty when the message says it all.
type MessageQueue ¶
type MessageQueue interface {
// Enqueue appends a message to the tail of the queue, tagged with where
// it came from.
Enqueue(ctx context.Context, message sdk.Message, source QueuedMessageSource, requestID string) error
// Drain atomically removes and returns every queued message, oldest
// first. On a shared backend two processes never receive the same message.
Drain(ctx context.Context) ([]QueuedMessage, error)
// Dequeue removes and returns the head message, or returns nil when the
// queue is empty.
Dequeue(ctx context.Context) (*QueuedMessage, error)
// Clear removes all messages from the queue.
Clear(ctx context.Context) error
// Size returns the number of messages in the queue. Render-path read: a
// durable backend answers from its local snapshot without a round trip.
Size() int
// IsEmpty returns true when the queue holds no messages. Render-path read.
IsEmpty() bool
// GetAll returns a copy of the queued messages, oldest first, without
// removing them. Render-path read.
GetAll() []QueuedMessage
// BackendName names the active backend ("memory", "sqlite", "postgres",
// "redis") for the status bar indicator.
BackendName() string
// Unreachable reports whether the backend failed its latest operation. A
// render-path read over the persisted failure state, never a live probe.
Unreachable() bool
}
MessageQueue is the message queue port. The in-memory adapter is the process-local default, the durable adapters (sqlite, postgres, redis) keep the queue across restarts and may share one queue with other infer processes.
type ModelCostStats ¶
type ModelCostStats struct {
Model string
InputTokens int
OutputTokens int
InputCost float64
OutputCost float64
TotalCost float64
RequestCount int
}
ModelCostStats tracks cost statistics for a specific model within a session. This allows detailed breakdown when multiple models are used in the same conversation.
type ModelService ¶
type ModelService interface {
ListModels(ctx context.Context) ([]string, error)
SelectModel(modelID string) error
GetCurrentModel() string
IsModelAvailable(modelID string) bool
ValidateModel(modelID string) error
}
ModelService handles model selection and information
type PersistentConversationRepository ¶ added in v0.207.0
type PersistentConversationRepository interface {
ListSavedConversations(ctx context.Context, limit, offset int) ([]ConversationSummary, error)
LoadConversation(ctx context.Context, conversationID string) error
GetCurrentConversationMetadata() ConversationMetadata
SaveConversation(ctx context.Context) error
StartNewConversation(title string) error
GetCurrentConversationID() string
SetConversationID(id string)
SetConversationTitle(title string)
SetAutoSave(enabled bool)
DeleteSavedConversation(ctx context.Context, conversationID string) error
}
PersistentConversationRepository is the storage-backed side of a conversation: list, load, save, delete and re-point at stored conversations. The in-memory repository does not implement it, so callers type-assert a ConversationRepository to find out whether persistence is available.
type PlanApprovalStatus ¶
type PlanApprovalStatus int
PlanApprovalStatus represents the approval status of a plan
const ( PlanApprovalPending PlanApprovalStatus = iota PlanApprovalAccepted PlanApprovalRejected )
type PricingService ¶
type PricingService interface {
// IsEnabled returns whether pricing is enabled in the configuration.
IsEnabled() bool
// GetInputPrice retrieves the input price per million tokens for a specific model.
// Returns 0.0 for unknown models (e.g., Ollama, custom models).
GetInputPrice(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).
GetOutputPrice(model string) float64
// CalculateCost computes the total cost for a given number of input and
// output tokens. cachedTokens and cacheWriteTokens are the cache-read and
// cache-creation subsets of inputTokens, billed at the gateway's
// cache-read/cache-write rates when known (full input rate otherwise).
CalculateCost(model string, inputTokens, outputTokens, cachedTokens, cacheWriteTokens int) (inputCost, outputCost, totalCost float64)
// RequiresPro reports whether the model is gated behind a paid Pro
// subscription (e.g. some Ollama Cloud models). Resolves custom prices
// first, then defaults. Returns false when pricing is disabled or the
// model has no entry.
RequiresPro(model string) bool
// FormatModelPricing returns a formatted string describing the model's pricing.
// Returns empty string if pricing is disabled or the model has no pricing entry.
// Returns "free" only when an explicit pricing entry sets both prices to 0.0.
// Returns "$X.XX/$Y.YY per MTok" for paid models.
FormatModelPricing(model string) string
}
PricingService provides pricing information and cost calculation for different models. Note: This interface returns float64 for pricing to avoid import cycles. The actual ModelPricing struct is defined in the config package.
type ProblemLog ¶ added in v0.254.0
type ProblemLog interface {
ProblemsSince(moment time.Time) []LoggedProblem
}
ProblemLog reads back the warnings and errors logged from a moment on, so a next-step suggestion can take what went wrong into account.
type PromptRef ¶ added in v0.260.0
PromptRef names one of the user's prompts the way a client sees it: by its text, and by which of the times the user sent that text it is, counted from the newest. An Occurrence of 1, or less, is the last time and 2 the time before. Entries carry no id a client could hold on to instead.
type QueuedMessage ¶
type QueuedMessage struct {
Message sdk.Message
QueuedAt time.Time
RequestID string
Source QueuedMessageSource
}
QueuedMessage represents a message in the input queue
type QueuedMessageSource ¶ added in v0.213.0
type QueuedMessageSource string
QueuedMessageSource identifies where a queued message came from. It is set when the entry is enqueued so the UI can tell a typed message from a background job result without guessing from the message text.
const ( QueueSourceComposer QueuedMessageSource = "composer" QueueSourceStdin QueuedMessageSource = "stdin" QueueSourceA2A QueuedMessageSource = "a2a" QueueSourceShell QueuedMessageSource = "shell" QueueSourceSubagent QueuedMessageSource = "subagent" QueueSourceJob QueuedMessageSource = "job" )
type SessionCostStats ¶
type SessionCostStats struct {
TotalCost float64
TotalInputCost float64
TotalOutputCost float64
PerModelStats map[string]*ModelCostStats
Currency string
}
SessionCostStats aggregates cost information for an entire session. It provides both total costs and per-model breakdowns.
type SessionID ¶
type SessionID string
SessionID represents a unique identifier for a chat session. Format: {unix-timestamp}-{8-char-random-hex} Example: 1733678400-a3f2bc8d
func GenerateSessionID ¶
func GenerateSessionID() SessionID
GenerateSessionID creates a new unique session identifier. The ID combines a Unix timestamp (for temporal uniqueness) with random hex characters (for collision resistance).
func (SessionID) Age ¶
Age returns the duration since the session was created. Returns 0 if the session ID format is invalid.
type SessionRollover ¶ added in v0.207.0
type SessionRollover interface {
// ResolveSessionID maps a raw (possibly group) id to the group's current
// session id. Returns (sessionID, groupKey, error).
ResolveSessionID(rawID string) (string, string, error)
ShouldRollover(model string) bool
// MaybeRollover rolls over when ShouldRollover fires and returns the new
// session id and true. Failures are logged and reported as no rollover.
MaybeRollover(ctx context.Context, model, groupKey string) (string, bool)
PerformRollover(ctx context.Context, model, groupKey string) (string, error)
}
SessionRollover continues a conversation in a fresh session (summary preserved) once it crosses the compact threshold, keeping a stable group key across the chain.
type SessionTokenStats ¶
type SessionTokenStats struct {
TotalInputTokens int `json:"total_input_tokens"`
TotalOutputTokens int `json:"total_output_tokens"`
TotalTokens int `json:"total_tokens"`
RequestCount int `json:"request_count"`
LastInputTokens int `json:"last_input_tokens"`
TotalCachedTokens int `json:"total_cached_tokens"`
TotalCacheWriteTokens int `json:"total_cache_write_tokens"`
}
SessionTokenStats tracks accumulated token usage across a session
type SyntheticToolResponse ¶ added in v0.207.0
SyntheticToolResponse pairs a synthesized Tool-role message with the metadata of the assistant tool_call it closes. Callers persist Message to the conversation repository and use ToolCallID / ToolName when emitting UI events.
func EnsureToolCallsClosed ¶ added in v0.207.0
func EnsureToolCallsClosed(conv []sdk.Message) ([]sdk.Message, []SyntheticToolResponse)
EnsureToolCallsClosed makes every assistant tool_call_id answered by a Tool-role message, inserting a CancelledToolResponseContent synthetic after that turn's existing responses in tool_calls order. It returns a copy and the synthetics in insertion order, nil when none were added. It is idempotent.
type TokenEstimator ¶
type TokenEstimator interface {
// GetToolStats returns token count and tool count for a given agent mode
GetToolStats(toolService agentdomain.ToolService, agentMode agentdomain.AgentMode) (tokens int, count int)
// EstimateMessagesTokens estimates the total tokens for a slice of messages
EstimateMessagesTokens(messages []sdk.Message) int
// EffectiveContextTokens estimates what the *next* request will carry: the
// larger of the gateway-reported last-request size and a fresh estimate of
// the current buffer. The max catches a single-turn tool-output spike that a
// stale lastInputTokens alone would miss.
EffectiveContextTokens(lastInputTokens int, messages []sdk.Message) int
}
TokenEstimator provides token count estimation for LLM content
type ToolApprovalStatus ¶
type ToolApprovalStatus int
ToolApprovalStatus represents the approval status of a tool
const ( ToolApprovalPending ToolApprovalStatus = iota ToolApprovalApproved ToolApprovalRejected )