Documentation
¶
Index ¶
- Constants
- Variables
- func NewBackgroundTaskRegistry(maxConcurrentShells int, supervisor *jobs.Supervisor) domain.BackgroundTaskRegistry
- func NewContainerRuntime(sessionID domain.SessionID, runtimeType RuntimeType) (domain.ContainerRuntime, error)
- func NewConversationOptimizer(config OptimizerConfig) domain.ConversationOptimizer
- func NewDockerRuntime(sessionID domain.SessionID) domain.ContainerRuntime
- func NewFileService() domain.FileService
- func NewPodmanRuntime(sessionID domain.SessionID) domain.ContainerRuntime
- func NewPricingService(cfg *config.PricingConfig) domain.PricingService
- type A2AAgentService
- type AgentManager
- func (am *AgentManager) GetAllAgentNames() []string
- func (am *AgentManager) GetExternalAgentURL(agentName string) string
- func (am *AgentManager) GetTotalAgentCount() int
- func (am *AgentManager) IsExternalAgent(agentName string) bool
- func (am *AgentManager) IsRunning() bool
- func (am *AgentManager) SetPullProgressCallback(callback func(agentName string, done, total int))
- func (am *AgentManager) SetStatusCallback(...)
- func (am *AgentManager) StartAgent(ctx context.Context, agent config.AgentEntry) error
- func (am *AgentManager) StartAgents(ctx context.Context) error
- func (am *AgentManager) StopAgent(ctx context.Context, agentName string) error
- func (am *AgentManager) StopAgents(ctx context.Context) error
- type BackgroundJobManager
- type BackgroundShellService
- func (s *BackgroundShellService) CancelShell(shellID string) error
- func (s *BackgroundShellService) DetachToBackground(ctx context.Context, cmd *exec.Cmd, command string, ...) (string, error)
- func (s *BackgroundShellService) GetAllShells() []*domain.BackgroundShell
- func (s *BackgroundShellService) GetShell(shellID string) *domain.BackgroundShell
- func (s *BackgroundShellService) GetShellOutput(shellID string, fromOffset int64) (string, int64, domain.ShellState, error)
- func (s *BackgroundShellService) GetShellOutputWithFilter(shellID string, fromOffset int64, filterPattern string) (string, int64, domain.ShellState, error)
- func (s *BackgroundShellService) GetStats() map[string]int
- func (s *BackgroundShellService) RemoveShell(shellID string) error
- func (s *BackgroundShellService) Stop()
- type BackgroundTaskService
- type BackgroundTasksWaiter
- type ChannelManagerService
- func (cm *ChannelManagerService) GetChannel(name string) domain.Channel
- func (cm *ChannelManagerService) Register(ch domain.Channel)
- func (cm *ChannelManagerService) SetCommandSupport(reg *shortcuts.Registry, conv storage.ConversationStorage, ...)
- func (cm *ChannelManagerService) Start(ctx context.Context) error
- func (cm *ChannelManagerService) Stop() error
- type CircularScreenshotBuffer
- func (b *CircularScreenshotBuffer) Add(screenshot *domain.Screenshot) error
- func (b *CircularScreenshotBuffer) Cleanup() error
- func (b *CircularScreenshotBuffer) Clear() error
- func (b *CircularScreenshotBuffer) Count() int
- func (b *CircularScreenshotBuffer) GetByID(id string) (*domain.Screenshot, error)
- func (b *CircularScreenshotBuffer) GetLatest() (*domain.Screenshot, error)
- func (b *CircularScreenshotBuffer) GetRecent(limit int) []*domain.Screenshot
- type ConversationOptimizer
- type ConversationTitleGenerator
- func (g *ConversationTitleGenerator) GenerateTitleForConversation(ctx context.Context, conversationID string) error
- func (g *ConversationTitleGenerator) InvalidateTitle(ctx context.Context, conversationID string) error
- func (g *ConversationTitleGenerator) ProcessPendingTitles(ctx context.Context) error
- type DockerRuntime
- func (dr *DockerRuntime) CleanupNetwork(ctx context.Context) error
- func (dr *DockerRuntime) ContainerExists(containerIDOrName string) bool
- func (dr *DockerRuntime) EnsureNetwork(ctx context.Context) error
- func (dr *DockerRuntime) GetContainerHealth(ctx context.Context, containerIDOrName string) (domain.HealthStatus, error)
- func (dr *DockerRuntime) GetNetworkName() string
- func (dr *DockerRuntime) ListRunningContainers(ctx context.Context, nameFilter string) ([]domain.ContainerInfo, error)
- func (dr *DockerRuntime) PullImage(ctx context.Context, image string, progress func(done, total int)) error
- func (dr *DockerRuntime) RunContainer(ctx context.Context, opts domain.RunContainerOptions) (string, error)
- func (dr *DockerRuntime) StopContainer(ctx context.Context, containerIDOrName string) error
- type DrainedMessage
- type FileServiceImpl
- func (s *FileServiceImpl) GetFileInfo(path string) (domain.FileInfo, error)
- func (s *FileServiceImpl) ListProjectFiles() ([]string, error)
- func (s *FileServiceImpl) ReadFile(path string) (string, error)
- func (s *FileServiceImpl) ReadFileLines(path string, startLine, endLine int) (string, error)
- func (s *FileServiceImpl) ValidateFile(path string) error
- type GatewayManager
- type HTTPModelService
- func (s *HTTPModelService) GetCurrentModel() string
- func (s *HTTPModelService) IsModelAvailable(modelID string) bool
- func (s *HTTPModelService) ListModels(ctx context.Context) ([]string, error)
- func (s *HTTPModelService) SelectModel(modelID string) error
- func (s *HTTPModelService) ValidateModel(modelID string) error
- type HintProvider
- type ImageOptimizer
- type ImageService
- func (s *ImageService) CreateDataURL(attachment *domain.ImageAttachment) string
- func (s *ImageService) IsImageFile(filePath string) bool
- func (s *ImageService) IsImageURL(urlStr string) bool
- func (s *ImageService) ReadImageFromBinary(imageData []byte, filename string) (*domain.ImageAttachment, error)
- func (s *ImageService) ReadImageFromFile(filePath string) (*domain.ImageAttachment, error)
- func (s *ImageService) ReadImageFromURL(imageURL string) (*domain.ImageAttachment, error)
- type InMemoryConversationRepository
- func (r *InMemoryConversationRepository) AddCachedTokens(tokens int)
- func (r *InMemoryConversationRepository) AddMessage(msg domain.ConversationEntry) error
- func (r *InMemoryConversationRepository) AddPendingToolCall(toolCall sdk.ChatCompletionMessageToolCall, ...) error
- func (r *InMemoryConversationRepository) AddTokenUsage(model string, inputTokens, outputTokens, totalTokens, cachedTokens int) error
- func (r *InMemoryConversationRepository) Clear() error
- func (r *InMemoryConversationRepository) ClearExceptFirstUserMessage() error
- func (r *InMemoryConversationRepository) DeleteMessagesAfterIndex(index int) error
- func (r *InMemoryConversationRepository) Export(format domain.ExportFormat) ([]byte, error)
- func (r *InMemoryConversationRepository) FormatToolResultExpanded(result *domain.ToolExecutionResult, terminalWidth int) string
- func (r *InMemoryConversationRepository) FormatToolResultForLLM(result *domain.ToolExecutionResult) string
- func (r *InMemoryConversationRepository) FormatToolResultForUI(result *domain.ToolExecutionResult, terminalWidth int) string
- func (r *InMemoryConversationRepository) GetCurrentConversationID() string
- func (r *InMemoryConversationRepository) GetCurrentConversationTitle() string
- func (r *InMemoryConversationRepository) GetMessageCount() int
- func (r *InMemoryConversationRepository) GetMessages() []domain.ConversationEntry
- func (r *InMemoryConversationRepository) GetSessionCostStats() domain.SessionCostStats
- func (r *InMemoryConversationRepository) GetSessionTokens() domain.SessionTokenStats
- func (r *InMemoryConversationRepository) LoadConversation(ctx context.Context, conversationID string) error
- func (r *InMemoryConversationRepository) MarkLastMessageAsPlan()
- func (r *InMemoryConversationRepository) MarkMessageAsPlanByIndex(index int)
- func (r *InMemoryConversationRepository) RemovePendingToolCallByID(toolCallID string)
- func (r *InMemoryConversationRepository) SetSessionStats(tokenStats domain.SessionTokenStats, costStats domain.SessionCostStats)
- func (r *InMemoryConversationRepository) StartNewConversation(title string) error
- func (r *InMemoryConversationRepository) UpdateLastMessage(content string) error
- func (r *InMemoryConversationRepository) UpdateLastMessageToolCalls(toolCalls *[]sdk.ChatCompletionMessageToolCall) error
- func (r *InMemoryConversationRepository) UpdatePlanStatus(action domain.PlanApprovalAction)
- func (r *InMemoryConversationRepository) UpdateToolApprovalStatus(action domain.ApprovalAction)
- type LLMToolService
- func (s *LLMToolService) ExecuteTool(ctx context.Context, toolCall sdk.ChatCompletionMessageToolCallFunction) (*domain.ToolExecutionResult, error)
- func (s *LLMToolService) ExecuteToolDirect(ctx context.Context, toolCall sdk.ChatCompletionMessageToolCallFunction) (*domain.ToolExecutionResult, error)
- func (s *LLMToolService) GetA2ATaskTracker() domain.A2ATaskTracker
- func (s *LLMToolService) GetTool(name string) (domain.Tool, error)
- func (s *LLMToolService) IsToolEnabled(name string) bool
- func (s *LLMToolService) ListAvailableTools() []string
- func (s *LLMToolService) ListTools() []sdk.ChatCompletionTool
- func (s *LLMToolService) ListToolsForMode(mode domain.AgentMode) []sdk.ChatCompletionTool
- func (s *LLMToolService) ValidateTool(name string, args map[string]any) error
- type MCPManager
- func (m *MCPManager) ClearToolCount(serverName string)
- func (m *MCPManager) Close() error
- func (m *MCPManager) GetClient(serverName string) domain.MCPClient
- func (m *MCPManager) GetClients() []domain.MCPClient
- func (m *MCPManager) GetTotalServers() int
- func (m *MCPManager) StartMonitoring(ctx context.Context)
- func (m *MCPManager) StartServer(ctx context.Context, server config.MCPServerEntry) error
- func (m *MCPManager) StartServers(ctx context.Context) error
- func (m *MCPManager) StopServers(ctx context.Context) error
- func (m *MCPManager) UpdateToolCount(serverName string, count int)
- type MessageQueueService
- func (mq *MessageQueueService) Clear()
- func (mq *MessageQueueService) Dequeue() *domain.QueuedMessage
- func (mq *MessageQueueService) Enqueue(message sdk.Message, requestID string)
- func (mq *MessageQueueService) GetAll() []domain.QueuedMessage
- func (mq *MessageQueueService) IsEmpty() bool
- func (mq *MessageQueueService) Peek() *domain.QueuedMessage
- func (mq *MessageQueueService) Size() int
- type NoOpToolService
- func (s *NoOpToolService) ExecuteTool(ctx context.Context, toolCall sdk.ChatCompletionMessageToolCallFunction) (*domain.ToolExecutionResult, error)
- func (s *NoOpToolService) ExecuteToolDirect(ctx context.Context, toolCall sdk.ChatCompletionMessageToolCallFunction) (*domain.ToolExecutionResult, error)
- func (s *NoOpToolService) GetA2ATaskTracker() domain.A2ATaskTracker
- func (s *NoOpToolService) GetTool(name string) (domain.Tool, error)
- func (s *NoOpToolService) IsToolEnabled(name string) bool
- func (s *NoOpToolService) ListAvailableTools() []string
- func (s *NoOpToolService) ListTools() []sdk.ChatCompletionTool
- func (s *NoOpToolService) ListToolsForMode(mode domain.AgentMode) []sdk.ChatCompletionTool
- func (s *NoOpToolService) ValidateTool(name string, args map[string]any) error
- type OptimizeResult
- type OptimizerConfig
- type PermissiveApprovalPolicy
- type PersistentConversationRepository
- func (r *PersistentConversationRepository) AddMessage(msg domain.ConversationEntry) error
- func (r *PersistentConversationRepository) AddTokenUsage(model string, inputTokens, outputTokens, totalTokens, cachedTokens int) error
- func (r *PersistentConversationRepository) Clear() error
- func (r *PersistentConversationRepository) Close() error
- func (r *PersistentConversationRepository) DeleteMessagesAfterIndex(index int) error
- func (r *PersistentConversationRepository) DeleteSavedConversation(ctx context.Context, conversationID string) error
- func (r *PersistentConversationRepository) GetCurrentConversationID() string
- func (r *PersistentConversationRepository) GetCurrentConversationMetadata() storage.ConversationMetadata
- func (r *PersistentConversationRepository) GetCurrentConversationTitle() string
- func (r *PersistentConversationRepository) ListSavedConversations(ctx context.Context, limit, offset int) ([]storage.ConversationSummary, error)
- func (r *PersistentConversationRepository) LoadConversation(ctx context.Context, conversationID string) error
- func (r *PersistentConversationRepository) SaveConversation(ctx context.Context) error
- func (r *PersistentConversationRepository) SetA2ATaskTracker(taskTracker domain.A2AClearer)
- func (r *PersistentConversationRepository) SetAutoSave(enabled bool)
- func (r *PersistentConversationRepository) SetConversationID(id string)
- func (r *PersistentConversationRepository) SetConversationTags(tags []string)
- func (r *PersistentConversationRepository) SetConversationTitle(title string)
- func (r *PersistentConversationRepository) SetTitleGenerator(titleGenerator *ConversationTitleGenerator)
- func (r *PersistentConversationRepository) StartNewConversation(title string) error
- type PodmanRuntime
- func (pr *PodmanRuntime) CleanupNetwork(ctx context.Context) error
- func (pr *PodmanRuntime) ContainerExists(containerIDOrName string) bool
- func (pr *PodmanRuntime) EnsureNetwork(ctx context.Context) error
- func (pr *PodmanRuntime) GetContainerHealth(ctx context.Context, containerIDOrName string) (domain.HealthStatus, error)
- func (pr *PodmanRuntime) GetNetworkName() string
- func (pr *PodmanRuntime) ListRunningContainers(ctx context.Context, nameFilter string) ([]domain.ContainerInfo, error)
- func (pr *PodmanRuntime) PullImage(ctx context.Context, image string, progress func(done, total int)) error
- func (pr *PodmanRuntime) RunContainer(ctx context.Context, opts domain.RunContainerOptions) (string, error)
- func (pr *PodmanRuntime) StopContainer(ctx context.Context, containerIDOrName string) error
- type PricingServiceImpl
- func (p *PricingServiceImpl) CalculateCost(model string, inputTokens, outputTokens, cachedTokens int) (inputCost, outputCost, totalCost float64)
- func (p *PricingServiceImpl) FormatModelPricing(model string) string
- func (p *PricingServiceImpl) GetInputPrice(model string) float64
- func (p *PricingServiceImpl) GetOutputPrice(model string) float64
- func (p *PricingServiceImpl) IsEnabled() bool
- func (p *PricingServiceImpl) RequiresPro(model string) bool
- type ResultBodyProvider
- type RuntimeType
- type SSEHTTPClientTransport
- func (t *SSEHTTPClientTransport) Close() error
- func (t *SSEHTTPClientTransport) Send(ctx context.Context, message *transport.BaseJsonRpcMessage) error
- func (t *SSEHTTPClientTransport) SetCloseHandler(handler func())
- func (t *SSEHTTPClientTransport) SetErrorHandler(handler func(error))
- func (t *SSEHTTPClientTransport) SetMessageHandler(handler func(ctx context.Context, message *transport.BaseJsonRpcMessage))
- func (t *SSEHTTPClientTransport) Start(ctx context.Context) error
- func (t *SSEHTTPClientTransport) WithHeader(key, value string) *SSEHTTPClientTransport
- type ScreenshotServer
- type SessionRolloverManager
- func (m *SessionRolloverManager) MaybeRollover(ctx context.Context, model, groupKey string) (string, bool)
- func (m *SessionRolloverManager) PerformRollover(ctx context.Context, model, groupKey string) (string, error)
- func (m *SessionRolloverManager) ResolveSessionID(rawID string) (string, string, error)
- func (m *SessionRolloverManager) ShouldRollover(model string) bool
- type StandardApprovalPolicy
- type StateManager
- func (sm *StateManager) AddQueuedMessage(message sdk.Message, requestID string)
- func (sm *StateManager) AreAllAgentsReady() bool
- func (sm *StateManager) BroadcastEvent(event domain.ChatEvent)
- func (sm *StateManager) ClearAgentReadiness()
- func (sm *StateManager) ClearApprovalUIState()
- func (sm *StateManager) ClearComputerUsePauseState()
- func (sm *StateManager) ClearFileSelectionState()
- func (sm *StateManager) ClearLastClickCoordinates()
- func (sm *StateManager) ClearLastFocusedApp()
- func (sm *StateManager) ClearMessageEditState()
- func (sm *StateManager) ClearPlanApprovalUIState()
- func (sm *StateManager) ClearQueuedMessages()
- func (sm *StateManager) ClearUserQuestionUIState()
- func (sm *StateManager) CompleteCurrentTool(result *domain.ToolExecutionResult) error
- func (sm *StateManager) CycleAgentMode() domain.AgentMode
- func (sm *StateManager) EndChatSession()
- func (sm *StateManager) EndToolExecution()
- func (sm *StateManager) FailCurrentTool(result *domain.ToolExecutionResult) error
- func (sm *StateManager) GetAgentMode() domain.AgentMode
- func (sm *StateManager) GetAgentReadiness() *domain.AgentReadinessState
- func (sm *StateManager) GetApprovalUIState() *domain.ApprovalUIState
- func (sm *StateManager) GetChatSession() *domain.ChatSession
- func (sm *StateManager) GetCurrentView() domain.ViewState
- func (sm *StateManager) GetDimensions() (int, int)
- func (sm *StateManager) GetEventBridge() domain.EventBridge
- func (sm *StateManager) GetFileSelectionState() *domain.FileSelectionState
- func (sm *StateManager) GetLastClickCoordinates() (x, y int)
- func (sm *StateManager) GetLastFocusedApp() string
- func (sm *StateManager) GetMessageEditState() *domain.MessageEditState
- func (sm *StateManager) GetPausedRequestID() string
- func (sm *StateManager) GetPlanApprovalUIState() *domain.PlanApprovalUIState
- func (sm *StateManager) GetPreviousView() domain.ViewState
- func (sm *StateManager) GetQueuedMessages() []domain.QueuedMessage
- func (sm *StateManager) GetRetryStatus() *domain.RetryStatus
- func (sm *StateManager) GetTodos() []domain.TodoItem
- func (sm *StateManager) GetToolExecution() *domain.ToolExecutionSession
- func (sm *StateManager) GetUserQuestionUIState() *domain.UserQuestionUIState
- func (sm *StateManager) InitializeAgentReadiness(totalAgents int)
- func (sm *StateManager) IsAgentBusy() bool
- func (sm *StateManager) IsComputerUsePaused() bool
- func (sm *StateManager) IsDebugMode() bool
- func (sm *StateManager) IsEditingMessage() bool
- func (sm *StateManager) PopQueuedMessage() *domain.QueuedMessage
- func (sm *StateManager) RecoverFromInconsistentState() error
- func (sm *StateManager) RemoveAgent(name string)
- func (sm *StateManager) SetAgentError(name string, err error)
- func (sm *StateManager) SetAgentMode(mode domain.AgentMode)
- func (sm *StateManager) SetChatPending()
- func (sm *StateManager) SetComputerUsePaused(paused bool, requestID string)
- func (sm *StateManager) SetDebugMode(enabled bool)
- func (sm *StateManager) SetDimensions(width, height int)
- func (sm *StateManager) SetEventBridge(bridge domain.EventBridge)
- func (sm *StateManager) SetFileSelectedIndex(index int)
- func (sm *StateManager) SetLastClickCoordinates(x, y int)
- func (sm *StateManager) SetLastFocusedApp(appID string)
- func (sm *StateManager) SetMessageEditState(state *domain.MessageEditState)
- func (sm *StateManager) SetPlanApprovalSelectedIndex(index int)
- func (sm *StateManager) SetRetryStatus(status *domain.RetryStatus)
- func (sm *StateManager) SetStallThreshold(threshold time.Duration)
- func (sm *StateManager) SetTodos(todos []domain.TodoItem)
- func (sm *StateManager) SetupApprovalUIState(toolCall *sdk.ChatCompletionMessageToolCall, ...)
- func (sm *StateManager) SetupFileSelection(files []string)
- func (sm *StateManager) SetupPlanApprovalUIState(planContent, planID string, responseChan chan domain.PlanApprovalAction)
- func (sm *StateManager) SetupUserQuestionUIState(questions []domain.UserQuestion, responseChan chan []domain.UserQuestionAnswer)
- func (sm *StateManager) StartChatSession(requestID, model string, eventChan <-chan domain.ChatEvent) error
- func (sm *StateManager) StartToolExecution(toolCalls []sdk.ChatCompletionMessageToolCall) error
- func (sm *StateManager) TouchChatActivity()
- func (sm *StateManager) TransitionToView(newView domain.ViewState) error
- func (sm *StateManager) UpdateAgentPullProgress(name string, done, total int)
- func (sm *StateManager) UpdateAgentStatus(name string, state domain.AgentState, message string, url string, image string)
- func (sm *StateManager) UpdateChatStatus(status domain.ChatStatus) error
- func (sm *StateManager) UpdateFileSearchQuery(query string)
- type StrictApprovalPolicy
- type SyntheticToolResponse
- type TaskRetentionService
- type TitleGenerator
- type TokenizerConfig
- type TokenizerService
- func (t *TokenizerService) AdjustedEstimate(text string) int
- func (t *TokenizerService) CalculateUsagePolyfill(inputMessages []sdk.Message, outputContent string, ...) *sdk.CompletionUsage
- func (t *TokenizerService) EffectiveContextTokens(lastInputTokens int, messages []sdk.Message) int
- func (t *TokenizerService) EstimateMessageTokens(msg sdk.Message) int
- func (t *TokenizerService) EstimateMessagesTokens(messages []sdk.Message) int
- func (t *TokenizerService) EstimateResponseTokens(response string) int
- func (t *TokenizerService) EstimateTokenCount(text string) int
- func (t *TokenizerService) EstimateToolDefinitionsTokens(tools []sdk.ChatCompletionTool) int
- func (t *TokenizerService) GetToolStats(toolService domain.ToolService, agentMode domain.AgentMode) (tokens int, count int)
- func (t *TokenizerService) IsLikelyCodeContent(text string) bool
- func (t *TokenizerService) ShouldUsePolyfill(usage *sdk.CompletionUsage) bool
- type ToolFormatterService
- func (s *ToolFormatterService) FormatToolCall(toolName string, args map[string]any) string
- func (s *ToolFormatterService) FormatToolResultExpanded(result *domain.ToolExecutionResult, terminalWidth int) string
- func (s *ToolFormatterService) FormatToolResultForLLM(result *domain.ToolExecutionResult) string
- func (s *ToolFormatterService) FormatToolResultForUI(result *domain.ToolExecutionResult, terminalWidth int) string
- func (s *ToolFormatterService) RenderToolSummary(icon, toolName string, args map[string]any, trailing string, terminalWidth int) string
- func (s *ToolFormatterService) SetHintFormatter(h HintProvider)
- func (s *ToolFormatterService) SetMaxResultBytes(n int)
- func (s *ToolFormatterService) ShouldAlwaysExpandTool(toolName string) bool
- type ToolRegistry
Constants ¶
const (
// AgentContainerPrefix is the naming prefix for agent containers
AgentContainerPrefix = "inference-agent-"
)
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.
const (
// InferNetworkPrefix is the prefix for session-specific Docker networks
InferNetworkPrefix = "infer-network"
)
Variables ¶
var ChannelBuiltinCommands = []domain.ChannelCommand{
{Name: "new", Description: "Start a fresh conversation and wipe recent chat messages (previous one is kept)"},
{Name: "conversations", Description: "List past conversations, tap one to switch"},
{Name: "stats", Description: "Usage stats for this conversation — phone-friendly list (/stats 24h; add 'table' for tables)"},
{Name: "help", Description: "List available commands"},
}
ChannelBuiltinCommands are the shortcuts the daemon implements natively for channels (everything else in the registry is either a custom shortcut, executed as-is, or TUI-only and answered with a pointer to `infer chat`).
Functions ¶
func NewBackgroundTaskRegistry ¶ added in v0.101.0
func NewBackgroundTaskRegistry(maxConcurrentShells int, supervisor *jobs.Supervisor) domain.BackgroundTaskRegistry
NewBackgroundTaskRegistry constructs the unified registry. maxConcurrentShells is the per-session cap enforced by the underlying shell tracker. supervisor is the single fan-in that monitors submitted jobs and backs the unified job surface (Submit/Snapshot/Wind).
func NewContainerRuntime ¶ added in v0.82.0
func NewContainerRuntime(sessionID domain.SessionID, runtimeType RuntimeType) (domain.ContainerRuntime, error)
NewContainerRuntime creates a container runtime based on the configured type If runtimeType is empty, returns nil to allow binary mode fallback
func NewConversationOptimizer ¶ added in v0.30.0
func NewConversationOptimizer(config OptimizerConfig) domain.ConversationOptimizer
NewConversationOptimizer creates a new conversation optimizer with configuration
func NewDockerRuntime ¶ added in v0.82.0
func NewDockerRuntime(sessionID domain.SessionID) domain.ContainerRuntime
NewDockerRuntime creates a new Docker runtime manager
func NewFileService ¶ added in v0.15.0
func NewFileService() domain.FileService
NewFileService creates a new file service
func NewPodmanRuntime ¶ added in v0.82.0
func NewPodmanRuntime(sessionID domain.SessionID) domain.ContainerRuntime
NewPodmanRuntime creates a new Podman runtime manager
func NewPricingService ¶ added in v0.86.0
func NewPricingService(cfg *config.PricingConfig) domain.PricingService
NewPricingService creates a new pricing service instance.
Types ¶
type A2AAgentService ¶ added in v0.49.0
type A2AAgentService struct {
// contains filtered or unexported fields
}
func NewA2AAgentService ¶ added in v0.49.0
func NewA2AAgentService(cfg *config.Config) *A2AAgentService
func (*A2AAgentService) GetAgentCard ¶ added in v0.49.0
func (*A2AAgentService) GetAgentCards ¶ added in v0.49.0
func (s *A2AAgentService) GetAgentCards(ctx context.Context) ([]*domain.CachedAgentCard, error)
func (*A2AAgentService) GetConfiguredAgents ¶ added in v0.49.0
func (s *A2AAgentService) GetConfiguredAgents() []string
type AgentManager ¶ added in v0.54.0
type AgentManager struct {
// contains filtered or unexported fields
}
AgentManager manages the lifecycle of A2A agent containers (local and external)
func NewAgentManager ¶ added in v0.54.0
func NewAgentManager(sessionID domain.SessionID, cfg *config.Config, agentsConfig *config.AgentsConfig, runtime domain.ContainerRuntime, a2aService domain.A2AAgentService) *AgentManager
NewAgentManager creates a new agent manager
func (*AgentManager) GetAllAgentNames ¶ added in v0.90.2
func (am *AgentManager) GetAllAgentNames() []string
GetAllAgentNames returns names of all agents (local and external)
func (*AgentManager) GetExternalAgentURL ¶ added in v0.90.2
func (am *AgentManager) GetExternalAgentURL(agentName string) string
GetExternalAgentURL returns the URL for an external agent
func (*AgentManager) GetTotalAgentCount ¶ added in v0.90.2
func (am *AgentManager) GetTotalAgentCount() int
GetTotalAgentCount returns the total number of agents (local + external)
func (*AgentManager) IsExternalAgent ¶ added in v0.90.2
func (am *AgentManager) IsExternalAgent(agentName string) bool
IsExternalAgent returns true if the agent is external (not managed by this CLI)
func (*AgentManager) IsRunning ¶ added in v0.54.0
func (am *AgentManager) IsRunning() bool
IsRunning returns whether any agents are running
func (*AgentManager) SetPullProgressCallback ¶ added in v0.149.0
func (am *AgentManager) SetPullProgressCallback(callback func(agentName string, done, total int))
SetPullProgressCallback sets the callback function for image pull progress updates
func (*AgentManager) SetStatusCallback ¶ added in v0.67.0
func (am *AgentManager) SetStatusCallback(callback func(agentName string, state domain.AgentState, message string, url string, image string))
SetStatusCallback sets the callback function for agent status updates
func (*AgentManager) StartAgent ¶ added in v0.54.0
func (am *AgentManager) StartAgent(ctx context.Context, agent config.AgentEntry) error
StartAgent starts a single agent container with status updates
func (*AgentManager) StartAgents ¶ added in v0.54.0
func (am *AgentManager) StartAgents(ctx context.Context) error
StartAgents starts all local agents (run: true) and monitors external agents
func (*AgentManager) StopAgent ¶ added in v0.54.0
func (am *AgentManager) StopAgent(ctx context.Context, agentName string) error
StopAgent stops a single agent container
func (*AgentManager) StopAgents ¶ added in v0.54.0
func (am *AgentManager) StopAgents(ctx context.Context) error
StopAgents stops all running agent containers, cancels liveness probes, and cleans up the network
type BackgroundJobManager ¶ added in v0.46.0
type BackgroundJobManager struct {
// contains filtered or unexported fields
}
BackgroundJobManager manages background tasks
func NewBackgroundJobManager ¶ added in v0.46.0
func NewBackgroundJobManager(titleGenerator TitleGenerator, config *config.Config) *BackgroundJobManager
NewBackgroundJobManager creates a new background job manager
func (*BackgroundJobManager) IsRunning ¶ added in v0.46.0
func (m *BackgroundJobManager) IsRunning() bool
IsRunning returns whether the job manager is currently running
func (*BackgroundJobManager) Start ¶ added in v0.46.0
func (m *BackgroundJobManager) Start(ctx context.Context)
Start begins running background jobs
func (*BackgroundJobManager) Stop ¶ added in v0.46.0
func (m *BackgroundJobManager) Stop()
Stop stops all background jobs gracefully
func (*BackgroundJobManager) TriggerTitleGeneration ¶ added in v0.46.0
func (m *BackgroundJobManager) TriggerTitleGeneration(ctx context.Context) error
TriggerTitleGeneration manually triggers title generation for pending conversations
type BackgroundShellService ¶ added in v0.81.0
type BackgroundShellService struct {
// contains filtered or unexported fields
}
BackgroundShellService is the thin front-end for background bash shells: it detaches a running command (registering it so the bash tools can read its output), submits a shellJob to the supervisor (which monitors it, notifies the agent, and reaps it), and brokers output retrieval and cancellation. The completion monitoring and reaping that used to live here are now the supervisor's job.
func NewBackgroundShellService ¶ added in v0.81.0
func NewBackgroundShellService( tracker domain.ShellTracker, supervisor *jobs.Supervisor, cfg *config.Config, eventChannel chan<- domain.ChatEvent, ) *BackgroundShellService
NewBackgroundShellService creates a new background shell service. supervisor monitors and reaps each detached shell.
func (*BackgroundShellService) CancelShell ¶ added in v0.81.0
func (s *BackgroundShellService) CancelShell(shellID string) error
CancelShell cancels a running background shell. It hands the kill to the supervisor (WindStop -> SIGKILL); the shellJob's Run then records the Cancelled state and the supervisor delivers the completion notification, so the process is waited on in exactly one place.
func (*BackgroundShellService) DetachToBackground ¶ added in v0.81.0
func (s *BackgroundShellService) DetachToBackground( ctx context.Context, cmd *exec.Cmd, command string, outputBuffer domain.OutputRingBuffer, readersDone <-chan struct{}, ) (string, error)
DetachToBackground moves a running command to background
func (*BackgroundShellService) GetAllShells ¶ added in v0.81.0
func (s *BackgroundShellService) GetAllShells() []*domain.BackgroundShell
GetAllShells returns all tracked shells
func (*BackgroundShellService) GetShell ¶ added in v0.81.0
func (s *BackgroundShellService) GetShell(shellID string) *domain.BackgroundShell
GetShell returns a specific shell by ID
func (*BackgroundShellService) GetShellOutput ¶ added in v0.81.0
func (s *BackgroundShellService) GetShellOutput(shellID string, fromOffset int64) (string, int64, domain.ShellState, error)
GetShellOutput retrieves incremental output from a shell
func (*BackgroundShellService) GetShellOutputWithFilter ¶ added in v0.81.0
func (s *BackgroundShellService) GetShellOutputWithFilter(shellID string, fromOffset int64, filterPattern string) (string, int64, domain.ShellState, error)
GetShellOutputWithFilter retrieves output with optional regex filtering
func (*BackgroundShellService) GetStats ¶ added in v0.81.0
func (s *BackgroundShellService) GetStats() map[string]int
GetStats returns statistics about background shells
func (*BackgroundShellService) RemoveShell ¶ added in v0.81.0
func (s *BackgroundShellService) RemoveShell(shellID string) error
RemoveShell removes a shell from tracking
func (*BackgroundShellService) Stop ¶ added in v0.81.0
func (s *BackgroundShellService) Stop()
Stop is retained for the lifecycle contract. The supervisor owns the monitor goroutines and the cleanup ticker now, so there is nothing to stop here.
type BackgroundTaskService ¶ added in v0.53.3
type BackgroundTaskService struct {
// contains filtered or unexported fields
}
BackgroundTaskService handles background task operations (A2A-specific) Only instantiated when A2A tools are enabled
func NewBackgroundTaskService ¶ added in v0.53.3
func NewBackgroundTaskService(taskTracker domain.A2ATaskTracker, jobs a2aJobController) *BackgroundTaskService
NewBackgroundTaskService creates a new background task service. jobs is the job supervisor - the single source of truth for which A2A tasks are running - while taskTracker still resolves the context graph and a task's agent URL for cancel.
func (*BackgroundTaskService) CancelBackgroundTask ¶ added in v0.53.3
func (s *BackgroundTaskService) CancelBackgroundTask(taskID string) error
CancelBackgroundTask cancels a background task by task ID
func (*BackgroundTaskService) GetBackgroundTasks ¶ added in v0.53.3
func (s *BackgroundTaskService) GetBackgroundTasks() []domain.TaskPollingState
GetBackgroundTasks returns the active A2A tasks from the job supervisor - the single source of truth shared with the status-bar indicator - so the /tasks active list and the indicator can no longer diverge.
type BackgroundTasksWaiter ¶ added in v0.101.0
type BackgroundTasksWaiter struct {
// contains filtered or unexported fields
}
BackgroundTasksWaiter encapsulates the "wait for in-flight background work to quiesce, then drain the shared message queue" pattern that batch (`infer agent`) mode needs between turns.
The notification mechanism is the queue itself: when background work completes (A2A task, bash shell, etc.), it pushes a result onto the shared MessageQueueService. This waiter polls at 1s intervals until the queue has something to drain or all background work finishes.
This is the batch-mode counterpart to chat mode's CheckingQueueState.
func NewBackgroundTasksWaiter ¶ added in v0.101.0
func NewBackgroundTasksWaiter( cfg *config.Config, _ string, registry domain.BackgroundTaskRegistry, messageQueue domain.MessageQueue, _ domain.ConversationRepository, ) *BackgroundTasksWaiter
NewBackgroundTasksWaiter constructs a waiter. If both A2A tools and the Agent tool are disabled, or either of the underlying services is nil, the returned waiter is a no-op for every method, so callers can use it unconditionally. sessionID and conversationRepo are unused now that the job supervisor owns monitoring; they are kept in the signature for call-site stability.
func (*BackgroundTasksWaiter) HasPendingTasks ¶ added in v0.101.0
func (w *BackgroundTasksWaiter) HasPendingTasks() bool
HasPendingTasks reports whether any background work is still in flight.
func (*BackgroundTasksWaiter) Start ¶ added in v0.101.0
func (w *BackgroundTasksWaiter) Start(_ context.Context)
Start is retained for the lifecycle contract; the job supervisor owns all monitor goroutines now, so there is nothing to launch here.
func (*BackgroundTasksWaiter) Stop ¶ added in v0.101.0
func (w *BackgroundTasksWaiter) Stop()
Stop is a no-op for the same reason as Start.
func (*BackgroundTasksWaiter) WaitAndDrain ¶ added in v0.101.0
func (w *BackgroundTasksWaiter) WaitAndDrain(ctx context.Context) []DrainedMessage
WaitAndDrain polls until background tasks complete and the queue has results, or the per-session timeout fires. Returns drained payloads. Returns nil if disabled or no work was pending.
type ChannelManagerService ¶ added in v0.101.0
type ChannelManagerService struct {
// contains filtered or unexported fields
}
ChannelManagerService manages pluggable messaging channels and triggers the agent as a subprocess for each inbound message.
func NewChannelManagerService ¶ added in v0.101.0
func NewChannelManagerService(cfg config.ChannelsConfig, tel *telemetry.Recorder) *ChannelManagerService
NewChannelManagerService creates a new channel manager
func (*ChannelManagerService) GetChannel ¶ added in v0.104.0
func (cm *ChannelManagerService) GetChannel(name string) domain.Channel
GetChannel returns a registered channel by name, or nil if not registered. Used by the scheduler service to deliver scheduled-job output through the in-process channel registry.
func (*ChannelManagerService) Register ¶ added in v0.101.0
func (cm *ChannelManagerService) Register(ch domain.Channel)
Register adds a channel to the manager
func (*ChannelManagerService) SetCommandSupport ¶ added in v0.149.0
func (cm *ChannelManagerService) SetCommandSupport(reg *shortcuts.Registry, conv storage.ConversationStorage, groups storage.SessionGroupStorage)
SetCommandSupport enables slash-command handling for inbound channel messages. A nil registry leaves the feature disabled.
func (*ChannelManagerService) Start ¶ added in v0.101.0
func (cm *ChannelManagerService) Start(ctx context.Context) error
Start begins all registered channels and the message routing loop
func (*ChannelManagerService) Stop ¶ added in v0.101.0
func (cm *ChannelManagerService) Stop() error
Stop gracefully shuts down all channels
type CircularScreenshotBuffer ¶ added in v0.96.0
type CircularScreenshotBuffer struct {
// contains filtered or unexported fields
}
CircularScreenshotBuffer implements a thread-safe ring buffer for screenshots with optional disk persistence
func NewCircularScreenshotBuffer ¶ added in v0.96.0
func NewCircularScreenshotBuffer(maxSize int, tempDir string, sessionID string) (*CircularScreenshotBuffer, error)
NewCircularScreenshotBuffer creates a new circular buffer for screenshots
func (*CircularScreenshotBuffer) Add ¶ added in v0.96.0
func (b *CircularScreenshotBuffer) Add(screenshot *domain.Screenshot) error
Add adds a new screenshot to the buffer If the buffer is full, it evicts the oldest screenshot
func (*CircularScreenshotBuffer) Cleanup ¶ added in v0.96.0
func (b *CircularScreenshotBuffer) Cleanup() error
Cleanup removes the temp directory and all screenshots
func (*CircularScreenshotBuffer) Clear ¶ added in v0.96.0
func (b *CircularScreenshotBuffer) Clear() error
Clear removes all screenshots from the buffer and deletes disk files
func (*CircularScreenshotBuffer) Count ¶ added in v0.96.0
func (b *CircularScreenshotBuffer) Count() int
Count returns the current number of screenshots in the buffer
func (*CircularScreenshotBuffer) GetByID ¶ added in v0.96.0
func (b *CircularScreenshotBuffer) GetByID(id string) (*domain.Screenshot, error)
GetByID returns a screenshot by its ID
func (*CircularScreenshotBuffer) GetLatest ¶ added in v0.96.0
func (b *CircularScreenshotBuffer) GetLatest() (*domain.Screenshot, error)
GetLatest returns the most recent screenshot
func (*CircularScreenshotBuffer) GetRecent ¶ added in v0.96.0
func (b *CircularScreenshotBuffer) GetRecent(limit int) []*domain.Screenshot
GetRecent returns the N most recent screenshots
type ConversationOptimizer ¶ added in v0.30.0
type ConversationOptimizer struct {
// contains filtered or unexported fields
}
ConversationOptimizer provides methods to optimize conversation history for token efficiency
func (*ConversationOptimizer) GenerateLLMSummary ¶ added in v0.95.1
func (co *ConversationOptimizer) GenerateLLMSummary(messages []sdk.Message, model string) (string, error)
GenerateLLMSummary creates a concise summary of conversation messages using an LLM. It uses the SDK client to generate an intelligent summary focused on key tasks, decisions, critical context, and next steps. The summary is limited to 2-3 sentences.
func (*ConversationOptimizer) OptimizeMessages ¶ added in v0.30.0
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 ¶ added in v0.46.0
type ConversationTitleGenerator struct {
// contains filtered or unexported fields
}
ConversationTitleGenerator generates titles for conversations using AI
func NewConversationTitleGenerator ¶ added in v0.46.0
func NewConversationTitleGenerator(client sdk.Client, storage storage.ConversationStorage, config *config.Config) *ConversationTitleGenerator
NewConversationTitleGenerator creates a new conversation title generator
func (*ConversationTitleGenerator) GenerateTitleForConversation ¶ added in v0.46.0
func (g *ConversationTitleGenerator) GenerateTitleForConversation(ctx context.Context, conversationID string) error
GenerateTitleForConversation generates a title for a specific conversation
func (*ConversationTitleGenerator) InvalidateTitle ¶ added in v0.46.0
func (g *ConversationTitleGenerator) InvalidateTitle(ctx context.Context, conversationID string) error
InvalidateTitle marks a conversation title as needing regeneration
func (*ConversationTitleGenerator) ProcessPendingTitles ¶ added in v0.46.0
func (g *ConversationTitleGenerator) ProcessPendingTitles(ctx context.Context) error
ProcessPendingTitles processes a batch of conversations that need title generation
type DockerRuntime ¶ added in v0.82.0
type DockerRuntime struct {
// contains filtered or unexported fields
}
DockerRuntime implements ContainerRuntime interface for Docker
func (*DockerRuntime) CleanupNetwork ¶ added in v0.82.0
func (dr *DockerRuntime) CleanupNetwork(ctx context.Context) error
CleanupNetwork best-effort removes the shared network. Because the network is shared across sessions it may still be in use by another session's containers, in which case removal is refused and we leave it in place (keeping networkCreated set so a later call retries once the network frees up). It is never an error to fail here - shutdown must not block.
func (*DockerRuntime) ContainerExists ¶ added in v0.82.0
func (dr *DockerRuntime) ContainerExists(containerIDOrName string) bool
ContainerExists checks if a Docker container exists by ID or name (running or stopped)
func (*DockerRuntime) EnsureNetwork ¶ added in v0.82.0
func (dr *DockerRuntime) EnsureNetwork(ctx context.Context) error
EnsureNetwork creates the shared Docker network if it doesn't exist. The network is reused across sessions, so at most one ever exists. If creation fails because the IPAM address pools are exhausted (leaked networks from prior sessions), it prunes those and retries once.
func (*DockerRuntime) GetContainerHealth ¶ added in v0.82.0
func (dr *DockerRuntime) GetContainerHealth(ctx context.Context, containerIDOrName string) (domain.HealthStatus, error)
GetContainerHealth returns the health status of a container
func (*DockerRuntime) GetNetworkName ¶ added in v0.82.0
func (dr *DockerRuntime) GetNetworkName() string
GetNetworkName returns the shared infer network name
func (*DockerRuntime) ListRunningContainers ¶ added in v0.82.0
func (dr *DockerRuntime) ListRunningContainers(ctx context.Context, nameFilter string) ([]domain.ContainerInfo, error)
ListRunningContainers lists all running containers matching the name filter
func (*DockerRuntime) PullImage ¶ added in v0.82.0
func (dr *DockerRuntime) PullImage(ctx context.Context, image string, progress func(done, total int)) error
PullImage pulls a Docker image, reporting layer progress via the optional callback
func (*DockerRuntime) RunContainer ¶ added in v0.82.0
func (dr *DockerRuntime) RunContainer(ctx context.Context, opts domain.RunContainerOptions) (string, error)
RunContainer runs a Docker container with the given options
func (*DockerRuntime) StopContainer ¶ added in v0.82.0
func (dr *DockerRuntime) StopContainer(ctx context.Context, containerIDOrName string) error
StopContainer stops a Docker container
type DrainedMessage ¶ added in v0.101.0
DrainedMessage is the opaque payload returned by BackgroundTasksWaiter.WaitAndDrain. Anything that lands on the shared message queue (A2A task completions, background shell completions, user messages typed while the agent is busy) is surfaced through this same shape.
type FileServiceImpl ¶ added in v0.15.0
type FileServiceImpl struct{}
FileServiceImpl implements domain.FileService
func (*FileServiceImpl) GetFileInfo ¶ added in v0.15.0
func (s *FileServiceImpl) GetFileInfo(path string) (domain.FileInfo, error)
GetFileInfo returns information about a file
func (*FileServiceImpl) ListProjectFiles ¶ added in v0.15.0
func (s *FileServiceImpl) ListProjectFiles() ([]string, error)
ListProjectFiles returns a list of all files in the current directory and subdirectories
func (*FileServiceImpl) ReadFile ¶ added in v0.15.0
func (s *FileServiceImpl) ReadFile(path string) (string, error)
ReadFile reads the content of a file
func (*FileServiceImpl) ReadFileLines ¶ added in v0.15.0
func (s *FileServiceImpl) ReadFileLines(path string, startLine, endLine int) (string, error)
ReadFileLines reads specific lines from a file
func (*FileServiceImpl) ValidateFile ¶ added in v0.15.0
func (s *FileServiceImpl) ValidateFile(path string) error
ValidateFile checks if a file path is valid and accessible
type GatewayManager ¶ added in v0.54.0
type GatewayManager struct {
// contains filtered or unexported fields
}
GatewayManager manages the lifecycle of the gateway container or binary
func NewGatewayManager ¶ added in v0.54.0
func NewGatewayManager(sessionID domain.SessionID, cfg *config.Config, runtime domain.ContainerRuntime) *GatewayManager
NewGatewayManager creates a new gateway manager
func (*GatewayManager) EnsureStarted ¶ added in v0.87.0
func (gm *GatewayManager) EnsureStarted() error
EnsureStarted starts the gateway if configured and not already running This is a convenience method that checks config and running state before starting
func (*GatewayManager) GetGatewayURL ¶ added in v0.82.0
func (gm *GatewayManager) GetGatewayURL() string
GetGatewayURL returns the actual gateway URL with the assigned port
func (*GatewayManager) IsRunning ¶ added in v0.54.0
func (gm *GatewayManager) IsRunning() bool
IsRunning returns whether the gateway container is running
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) 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 HintProvider ¶ added in v0.118.0
HintProvider resolves keybinding hints for tool result affordances. It is satisfied by *hints.Formatter.
type ImageOptimizer ¶ added in v0.89.0
type ImageOptimizer struct {
// contains filtered or unexported fields
}
ImageOptimizer handles image optimization for clipboard images
func NewImageOptimizer ¶ added in v0.89.0
func NewImageOptimizer(cfg config.ClipboardImageOptimizeConfig) *ImageOptimizer
NewImageOptimizer creates a new image optimizer with the given configuration
func (*ImageOptimizer) OptimizeImage ¶ added in v0.89.0
func (o *ImageOptimizer) OptimizeImage(imagePath string) (*OptimizeResult, error)
OptimizeImage optimizes an image file according to configuration Returns the optimized image data, extension, and any error encountered
type ImageService ¶ added in v0.57.0
type ImageService struct {
// contains filtered or unexported fields
}
ImageService handles image operations including file-based image loading and base64 encoding Note: Direct clipboard support requires platform-specific dependencies and is not yet implemented
func NewImageService ¶ added in v0.57.0
func NewImageService(cfg *config.Config) *ImageService
NewImageService creates a new image service
func (*ImageService) CreateDataURL ¶ added in v0.57.0
func (s *ImageService) CreateDataURL(attachment *domain.ImageAttachment) string
CreateDataURL creates a data URL from an image attachment
func (*ImageService) IsImageFile ¶ added in v0.57.0
func (s *ImageService) IsImageFile(filePath string) bool
IsImageFile checks if a file is a supported image format
func (*ImageService) IsImageURL ¶ added in v0.72.0
func (s *ImageService) IsImageURL(urlStr string) bool
IsImageURL checks if a string is a valid image URL
func (*ImageService) ReadImageFromBinary ¶ added in v0.57.0
func (s *ImageService) ReadImageFromBinary(imageData []byte, filename string) (*domain.ImageAttachment, error)
ReadImageFromBinary reads an image from binary data and returns it as a base64 attachment
func (*ImageService) ReadImageFromFile ¶ added in v0.57.0
func (s *ImageService) ReadImageFromFile(filePath string) (*domain.ImageAttachment, error)
ReadImageFromFile reads an image from a file path and returns it as a base64 attachment
func (*ImageService) ReadImageFromURL ¶ added in v0.72.0
func (s *ImageService) ReadImageFromURL(imageURL string) (*domain.ImageAttachment, error)
ReadImageFromURL fetches an image from a URL and returns it as a base64 attachment
type InMemoryConversationRepository ¶
type InMemoryConversationRepository struct {
// contains filtered or unexported fields
}
InMemoryConversationRepository implements ConversationRepository using in-memory storage
func NewInMemoryConversationRepository ¶
func NewInMemoryConversationRepository(formatterService *ToolFormatterService, pricingService domain.PricingService) *InMemoryConversationRepository
NewInMemoryConversationRepository creates a new in-memory conversation repository
func (*InMemoryConversationRepository) AddCachedTokens ¶ added in v0.151.0
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 (r *InMemoryConversationRepository) AddMessage(msg domain.ConversationEntry) error
func (*InMemoryConversationRepository) AddPendingToolCall ¶ added in v0.68.0
func (r *InMemoryConversationRepository) AddPendingToolCall(toolCall sdk.ChatCompletionMessageToolCall, responseChan chan domain.ApprovalAction) error
AddPendingToolCall adds a pending tool call entry that requires approval
func (*InMemoryConversationRepository) AddTokenUsage ¶ added in v0.28.0
func (r *InMemoryConversationRepository) AddTokenUsage(model string, inputTokens, outputTokens, totalTokens, cachedTokens 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 (r *InMemoryConversationRepository) Clear() error
func (*InMemoryConversationRepository) ClearExceptFirstUserMessage ¶ added in v0.49.0
func (r *InMemoryConversationRepository) ClearExceptFirstUserMessage() error
func (*InMemoryConversationRepository) DeleteMessagesAfterIndex ¶ added in v0.91.0
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 (r *InMemoryConversationRepository) Export(format domain.ExportFormat) ([]byte, error)
func (*InMemoryConversationRepository) FormatToolResultExpanded ¶ added in v0.48.0
func (r *InMemoryConversationRepository) FormatToolResultExpanded(result *domain.ToolExecutionResult, terminalWidth int) string
FormatToolResultExpanded formats expanded tool execution results
func (*InMemoryConversationRepository) FormatToolResultForLLM ¶ added in v0.48.0
func (r *InMemoryConversationRepository) FormatToolResultForLLM(result *domain.ToolExecutionResult) string
FormatToolResultForLLM formats tool execution results for LLM consumption
func (*InMemoryConversationRepository) FormatToolResultForUI ¶ added in v0.48.0
func (r *InMemoryConversationRepository) FormatToolResultForUI(result *domain.ToolExecutionResult, terminalWidth int) string
FormatToolResultForUI formats tool execution results for UI display
func (*InMemoryConversationRepository) GetCurrentConversationID ¶ added in v0.99.2
func (r *InMemoryConversationRepository) GetCurrentConversationID() string
GetCurrentConversationID returns the current conversation ID (empty for in-memory)
func (*InMemoryConversationRepository) GetCurrentConversationTitle ¶ added in v0.95.1
func (r *InMemoryConversationRepository) GetCurrentConversationTitle() string
GetCurrentConversationTitle returns the current conversation title
func (*InMemoryConversationRepository) GetMessageCount ¶
func (r *InMemoryConversationRepository) GetMessageCount() int
func (*InMemoryConversationRepository) GetMessages ¶
func (r *InMemoryConversationRepository) GetMessages() []domain.ConversationEntry
func (*InMemoryConversationRepository) GetSessionCostStats ¶ added in v0.86.0
func (r *InMemoryConversationRepository) GetSessionCostStats() domain.SessionCostStats
GetSessionCostStats returns the accumulated cost statistics for the session
func (*InMemoryConversationRepository) GetSessionTokens ¶ added in v0.28.0
func (r *InMemoryConversationRepository) GetSessionTokens() domain.SessionTokenStats
GetSessionTokens returns the accumulated token statistics for the session
func (*InMemoryConversationRepository) LoadConversation ¶ added in v0.133.0
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 ¶ added in v0.68.0
func (r *InMemoryConversationRepository) MarkLastMessageAsPlan()
MarkLastMessageAsPlan marks the last assistant message as a plan with pending approval
func (*InMemoryConversationRepository) MarkMessageAsPlanByIndex ¶ added in v0.76.2
func (r *InMemoryConversationRepository) MarkMessageAsPlanByIndex(index int)
MarkMessageAsPlanByIndex marks a specific message by index as a plan with pending approval
func (*InMemoryConversationRepository) RemovePendingToolCallByID ¶ added in v0.68.0
func (r *InMemoryConversationRepository) RemovePendingToolCallByID(toolCallID string)
RemovePendingToolCallByID removes a specific pending tool call by its ID
func (*InMemoryConversationRepository) SetSessionStats ¶ added in v0.97.0
func (r *InMemoryConversationRepository) SetSessionStats(tokenStats domain.SessionTokenStats, costStats domain.SessionCostStats)
SetSessionStats sets the session token and cost statistics (used when loading conversations)
func (*InMemoryConversationRepository) StartNewConversation ¶ added in v0.88.0
func (r *InMemoryConversationRepository) StartNewConversation(title string) error
StartNewConversation clears the current conversation (in-memory doesn't persist)
func (*InMemoryConversationRepository) UpdateLastMessage ¶
func (r *InMemoryConversationRepository) UpdateLastMessage(content string) error
func (*InMemoryConversationRepository) UpdateLastMessageToolCalls ¶
func (r *InMemoryConversationRepository) UpdateLastMessageToolCalls(toolCalls *[]sdk.ChatCompletionMessageToolCall) error
func (*InMemoryConversationRepository) UpdatePlanStatus ¶ added in v0.68.0
func (r *InMemoryConversationRepository) UpdatePlanStatus(action domain.PlanApprovalAction)
UpdatePlanStatus updates the status of the most recent pending plan
func (*InMemoryConversationRepository) UpdateToolApprovalStatus ¶ added in v0.68.0
func (r *InMemoryConversationRepository) UpdateToolApprovalStatus(action domain.ApprovalAction)
UpdateToolApprovalStatus updates the approval status of the most recent pending tool
type LLMToolService ¶
type LLMToolService struct {
// contains filtered or unexported fields
}
LLMToolService implements ToolService with the new tools package architecture
func NewLLMToolServiceWithRegistry ¶ added in v0.14.1
func NewLLMToolServiceWithRegistry(cfg *config.Config, registry *tools.Registry) *LLMToolService
NewLLMToolServiceWithRegistry creates a new LLM tool service with an existing registry
func (*LLMToolService) ExecuteTool ¶
func (s *LLMToolService) ExecuteTool(ctx context.Context, toolCall sdk.ChatCompletionMessageToolCallFunction) (*domain.ToolExecutionResult, error)
ExecuteTool executes a tool with the given arguments
func (*LLMToolService) ExecuteToolDirect ¶ added in v0.68.0
func (s *LLMToolService) ExecuteToolDirect(ctx context.Context, toolCall sdk.ChatCompletionMessageToolCallFunction) (*domain.ToolExecutionResult, error)
ExecuteToolDirect executes a tool directly without checking if it's enabled Used for user-initiated commands where the user explicitly wants to run the tool
func (*LLMToolService) GetA2ATaskTracker ¶ added in v0.101.0
func (s *LLMToolService) GetA2ATaskTracker() domain.A2ATaskTracker
func (*LLMToolService) GetTool ¶ added in v0.81.0
func (s *LLMToolService) GetTool(name string) (domain.Tool, error)
func (*LLMToolService) IsToolEnabled ¶
func (s *LLMToolService) IsToolEnabled(name string) bool
IsToolEnabled checks if a tool is enabled
func (*LLMToolService) ListAvailableTools ¶ added in v0.32.0
func (s *LLMToolService) ListAvailableTools() []string
ListAvailableTools returns names of all enabled tools
func (*LLMToolService) ListTools ¶
func (s *LLMToolService) ListTools() []sdk.ChatCompletionTool
ListTools returns definitions for all enabled tools
func (*LLMToolService) ListToolsForMode ¶ added in v0.56.0
func (s *LLMToolService) ListToolsForMode(mode domain.AgentMode) []sdk.ChatCompletionTool
ListToolsForMode returns definitions for enabled tools filtered by agent mode
func (*LLMToolService) ValidateTool ¶
func (s *LLMToolService) ValidateTool(name string, args map[string]any) error
ValidateTool validates tool arguments
type MCPManager ¶ added in v0.79.0
type MCPManager struct {
// contains filtered or unexported fields
}
MCPManager manages multiple MCP server connections and their container lifecycle
func NewMCPManager ¶ added in v0.79.0
func NewMCPManager(sessionID domain.SessionID, cfg *config.MCPConfig, runtime domain.ContainerRuntime, notifier domain.UINotifier) *MCPManager
NewMCPManager creates a new MCP manager. notifier is the single UI ingress the liveness probes push MCPServerStatusUpdateEvent through; a nil notifier degrades to no UI pushes.
func (*MCPManager) ClearToolCount ¶ added in v0.79.0
func (m *MCPManager) ClearToolCount(serverName string)
ClearToolCount removes the tool count for a specific server
func (*MCPManager) Close ¶ added in v0.79.0
func (m *MCPManager) Close() error
Close stops monitoring, stops containers, and cleans up resources
func (*MCPManager) GetClient ¶ added in v0.109.10
func (m *MCPManager) GetClient(serverName string) domain.MCPClient
GetClient returns the client for a specific server by name, or nil if no such client exists. Direct map lookup - does not perform any network I/O, in contrast to iterating GetClients() and calling DiscoverTools to identify the owning client.
func (*MCPManager) GetClients ¶ added in v0.79.0
func (m *MCPManager) GetClients() []domain.MCPClient
GetClients returns a list of MCP clients
func (*MCPManager) GetTotalServers ¶ added in v0.79.0
func (m *MCPManager) GetTotalServers() int
GetTotalServers returns the total number of configured MCP servers from config
func (*MCPManager) StartMonitoring ¶ added in v0.79.0
func (m *MCPManager) StartMonitoring(ctx context.Context)
StartMonitoring begins background health monitoring, pushing every MCPServerStatusUpdateEvent through the injected UI notifier. It is idempotent - subsequent calls are no-ops. The initial status is emitted from a goroutine because Notify wraps the unbuffered (*tea.Program).Send, which blocks until the Bubble Tea loop consumes; emitting it synchronously from app.Init (before the loop runs) would deadlock.
func (*MCPManager) StartServer ¶ added in v0.80.0
func (m *MCPManager) StartServer(ctx context.Context, server config.MCPServerEntry) error
StartServer starts a single MCP server container
func (*MCPManager) StartServers ¶ added in v0.80.0
func (m *MCPManager) StartServers(ctx context.Context) error
StartServers starts all MCP servers that have run=true This method is non-fatal and always returns nil
func (*MCPManager) StopServers ¶ added in v0.80.0
func (m *MCPManager) StopServers(ctx context.Context) error
StopServers stops all running MCP server containers
func (*MCPManager) UpdateToolCount ¶ added in v0.79.0
func (m *MCPManager) UpdateToolCount(serverName string, count int)
UpdateToolCount updates the tool count for a specific server
type MessageQueueService ¶ added in v0.53.0
type MessageQueueService struct {
// contains filtered or unexported fields
}
MessageQueueService manages a centralized queue for messages waiting to be processed
func NewMessageQueueService ¶ added in v0.53.0
func NewMessageQueueService() *MessageQueueService
NewMessageQueueService creates a new message queue service
func (*MessageQueueService) Clear ¶ added in v0.53.0
func (mq *MessageQueueService) Clear()
Clear removes all messages from the queue
func (*MessageQueueService) Dequeue ¶ added in v0.53.0
func (mq *MessageQueueService) Dequeue() *domain.QueuedMessage
Dequeue removes and returns the next message from the queue Returns nil if the queue is empty
func (*MessageQueueService) Enqueue ¶ added in v0.53.0
func (mq *MessageQueueService) Enqueue(message sdk.Message, requestID string)
Enqueue adds a message to the queue
func (*MessageQueueService) GetAll ¶ added in v0.53.0
func (mq *MessageQueueService) GetAll() []domain.QueuedMessage
GetAll returns all messages in the queue without removing them
func (*MessageQueueService) IsEmpty ¶ added in v0.53.0
func (mq *MessageQueueService) IsEmpty() bool
IsEmpty returns true if the queue has no messages
func (*MessageQueueService) Peek ¶ added in v0.53.0
func (mq *MessageQueueService) Peek() *domain.QueuedMessage
Peek returns the next message without removing it Returns nil if the queue is empty
func (*MessageQueueService) Size ¶ added in v0.53.0
func (mq *MessageQueueService) Size() int
Size returns the number of messages in the queue
type NoOpToolService ¶
type NoOpToolService struct{}
NoOpToolService implements ToolService as a no-op (when tools are disabled)
func NewNoOpToolService ¶
func NewNoOpToolService() *NoOpToolService
NewNoOpToolService creates a new no-op tool service
func (*NoOpToolService) ExecuteTool ¶
func (s *NoOpToolService) ExecuteTool(ctx context.Context, toolCall sdk.ChatCompletionMessageToolCallFunction) (*domain.ToolExecutionResult, error)
func (*NoOpToolService) ExecuteToolDirect ¶ added in v0.68.0
func (s *NoOpToolService) ExecuteToolDirect(ctx context.Context, toolCall sdk.ChatCompletionMessageToolCallFunction) (*domain.ToolExecutionResult, error)
func (*NoOpToolService) GetA2ATaskTracker ¶ added in v0.101.0
func (s *NoOpToolService) GetA2ATaskTracker() domain.A2ATaskTracker
func (*NoOpToolService) GetTool ¶ added in v0.81.0
func (s *NoOpToolService) GetTool(name string) (domain.Tool, error)
func (*NoOpToolService) IsToolEnabled ¶
func (s *NoOpToolService) IsToolEnabled(name string) bool
func (*NoOpToolService) ListAvailableTools ¶ added in v0.32.0
func (s *NoOpToolService) ListAvailableTools() []string
func (*NoOpToolService) ListTools ¶
func (s *NoOpToolService) ListTools() []sdk.ChatCompletionTool
func (*NoOpToolService) ListToolsForMode ¶ added in v0.56.0
func (s *NoOpToolService) ListToolsForMode(mode domain.AgentMode) []sdk.ChatCompletionTool
func (*NoOpToolService) ValidateTool ¶
func (s *NoOpToolService) ValidateTool(name string, args map[string]any) error
type OptimizeResult ¶ added in v0.89.0
OptimizeResult contains the optimized image data and format information
type OptimizerConfig ¶ added in v0.30.0
type OptimizerConfig struct {
Enabled bool
AutoAt int
BufferSize int
KeepFirstMessages int
Client sdk.Client
Config *config.Config
Tokenizer *TokenizerService
// Repo is optional. When provided, OptimizeMessages reads
// LastInputTokens from the repo's session stats and uses it as the
// trigger value (the gateway-reported count includes system prompt and
// tool definitions, matching what `/context` displays). When nil, the
// gate falls back to the entries-only estimate.
Repo domain.ConversationRepository
}
OptimizerConfig represents configuration for the conversation optimizer
type PermissiveApprovalPolicy ¶ added in v0.97.0
type PermissiveApprovalPolicy struct{}
PermissiveApprovalPolicy is an alternative policy that bypasses all approval Useful for automation, testing, or highly trusted environments
func NewPermissiveApprovalPolicy ¶ added in v0.97.0
func NewPermissiveApprovalPolicy() *PermissiveApprovalPolicy
NewPermissiveApprovalPolicy creates a new permissive approval policy
func (*PermissiveApprovalPolicy) ShouldRequireApproval ¶ added in v0.97.0
func (p *PermissiveApprovalPolicy) ShouldRequireApproval( ctx context.Context, toolCall *sdk.ChatCompletionMessageToolCall, isChatMode bool, ) bool
ShouldRequireApproval always returns false (no approval required)
type PersistentConversationRepository ¶ added in v0.45.0
type PersistentConversationRepository struct {
*InMemoryConversationRepository
// contains filtered or unexported fields
}
PersistentConversationRepository wraps the InMemoryConversationRepository and adds persistence capabilities using a storage backend
func NewPersistentConversationRepository ¶ added in v0.45.0
func NewPersistentConversationRepository(formatterService *ToolFormatterService, pricingService domain.PricingService, storageBackend storage.ConversationStorage) *PersistentConversationRepository
NewPersistentConversationRepository creates a new persistent conversation repository
func (*PersistentConversationRepository) AddMessage ¶ added in v0.45.0
func (r *PersistentConversationRepository) AddMessage(msg domain.ConversationEntry) error
Override AddMessage to trigger auto-save
func (*PersistentConversationRepository) AddTokenUsage ¶ added in v0.45.0
func (r *PersistentConversationRepository) AddTokenUsage(model string, inputTokens, outputTokens, totalTokens, cachedTokens int) error
AddTokenUsage wraps the in-memory implementation with persistence and auto-save
func (*PersistentConversationRepository) Clear ¶ added in v0.45.0
func (r *PersistentConversationRepository) Clear() error
Override Clear to handle conversation state
func (*PersistentConversationRepository) Close ¶ added in v0.45.0
func (r *PersistentConversationRepository) Close() error
Close closes the storage connection
func (*PersistentConversationRepository) DeleteMessagesAfterIndex ¶ added in v0.91.0
func (r *PersistentConversationRepository) DeleteMessagesAfterIndex(index int) error
DeleteMessagesAfterIndex wraps the in-memory implementation with auto-save
func (*PersistentConversationRepository) DeleteSavedConversation ¶ added in v0.45.0
func (r *PersistentConversationRepository) DeleteSavedConversation(ctx context.Context, conversationID string) error
DeleteSavedConversation deletes a saved conversation
func (*PersistentConversationRepository) GetCurrentConversationID ¶ added in v0.45.0
func (r *PersistentConversationRepository) GetCurrentConversationID() string
GetCurrentConversationID returns the current conversation ID
func (*PersistentConversationRepository) GetCurrentConversationMetadata ¶ added in v0.45.0
func (r *PersistentConversationRepository) GetCurrentConversationMetadata() storage.ConversationMetadata
GetCurrentConversationMetadata returns the current conversation metadata
func (*PersistentConversationRepository) GetCurrentConversationTitle ¶ added in v0.95.1
func (r *PersistentConversationRepository) GetCurrentConversationTitle() string
GetCurrentConversationTitle returns the current conversation title
func (*PersistentConversationRepository) ListSavedConversations ¶ added in v0.45.0
func (r *PersistentConversationRepository) ListSavedConversations(ctx context.Context, limit, offset int) ([]storage.ConversationSummary, error)
ListSavedConversations returns a list of saved conversations
func (*PersistentConversationRepository) LoadConversation ¶ added in v0.45.0
func (r *PersistentConversationRepository) LoadConversation(ctx context.Context, conversationID string) error
LoadConversation loads a conversation from persistent storage
func (*PersistentConversationRepository) SaveConversation ¶ added in v0.45.0
func (r *PersistentConversationRepository) SaveConversation(ctx context.Context) error
SaveConversation saves the current conversation to persistent storage
func (*PersistentConversationRepository) SetA2ATaskTracker ¶ added in v0.101.0
func (r *PersistentConversationRepository) SetA2ATaskTracker(taskTracker domain.A2AClearer)
SetA2ATaskTracker sets the task tracker for context ID persistence
func (*PersistentConversationRepository) SetAutoSave ¶ added in v0.45.0
func (r *PersistentConversationRepository) SetAutoSave(enabled bool)
SetAutoSave enables or disables automatic saving after each operation
func (*PersistentConversationRepository) SetConversationID ¶ added in v0.101.0
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.
func (*PersistentConversationRepository) SetConversationTags ¶ added in v0.45.0
func (r *PersistentConversationRepository) SetConversationTags(tags []string)
SetConversationTags sets tags for the current conversation
func (*PersistentConversationRepository) SetConversationTitle ¶ added in v0.45.0
func (r *PersistentConversationRepository) SetConversationTitle(title string)
SetConversationTitle sets the title for the current conversation
func (*PersistentConversationRepository) SetTitleGenerator ¶ added in v0.46.0
func (r *PersistentConversationRepository) SetTitleGenerator(titleGenerator *ConversationTitleGenerator)
SetTitleGenerator sets the title generator for automatic title invalidation
func (*PersistentConversationRepository) StartNewConversation ¶ added in v0.45.0
func (r *PersistentConversationRepository) StartNewConversation(title string) error
StartNewConversation saves the current conversation (if any), then begins a new conversation with a unique ID
type PodmanRuntime ¶ added in v0.82.0
type PodmanRuntime struct {
// contains filtered or unexported fields
}
PodmanRuntime implements ContainerRuntime interface for Podman
func (*PodmanRuntime) CleanupNetwork ¶ added in v0.82.0
func (pr *PodmanRuntime) CleanupNetwork(ctx context.Context) error
CleanupNetwork best-effort removes the shared network. Because the network is shared across sessions it may still be in use by another session's containers, in which case removal is refused and we leave it in place (keeping networkCreated set so a later call retries once the network frees up). It is never an error to fail here - shutdown must not block.
func (*PodmanRuntime) ContainerExists ¶ added in v0.82.0
func (pr *PodmanRuntime) ContainerExists(containerIDOrName string) bool
ContainerExists checks if a Podman container exists by ID or name (running or stopped)
func (*PodmanRuntime) EnsureNetwork ¶ added in v0.82.0
func (pr *PodmanRuntime) EnsureNetwork(ctx context.Context) error
EnsureNetwork creates the shared Podman network if it doesn't exist. The network is reused across sessions, so at most one ever exists. If creation fails because the IPAM address pools are exhausted (leaked networks from prior sessions), it prunes those and retries once.
func (*PodmanRuntime) GetContainerHealth ¶ added in v0.82.0
func (pr *PodmanRuntime) GetContainerHealth(ctx context.Context, containerIDOrName string) (domain.HealthStatus, error)
GetContainerHealth returns the health status of a container
func (*PodmanRuntime) GetNetworkName ¶ added in v0.82.0
func (pr *PodmanRuntime) GetNetworkName() string
GetNetworkName returns the shared infer network name
func (*PodmanRuntime) ListRunningContainers ¶ added in v0.82.0
func (pr *PodmanRuntime) ListRunningContainers(ctx context.Context, nameFilter string) ([]domain.ContainerInfo, error)
ListRunningContainers lists all running containers matching the name filter
func (*PodmanRuntime) PullImage ¶ added in v0.82.0
func (pr *PodmanRuntime) PullImage(ctx context.Context, image string, progress func(done, total int)) error
PullImage pulls a Podman image, reporting layer progress via the optional callback
func (*PodmanRuntime) RunContainer ¶ added in v0.82.0
func (pr *PodmanRuntime) RunContainer(ctx context.Context, opts domain.RunContainerOptions) (string, error)
RunContainer runs a Podman container with the given options
func (*PodmanRuntime) StopContainer ¶ added in v0.82.0
func (pr *PodmanRuntime) StopContainer(ctx context.Context, containerIDOrName string) error
StopContainer stops a Podman container
type PricingServiceImpl ¶ added in v0.86.0
type PricingServiceImpl struct {
// contains filtered or unexported fields
}
PricingServiceImpl implements the PricingService interface.
func (*PricingServiceImpl) CalculateCost ¶ added in v0.86.0
func (p *PricingServiceImpl) CalculateCost(model string, inputTokens, outputTokens, cachedTokens int) (inputCost, outputCost, totalCost float64)
CalculateCost computes the total cost for a given number of input, output and cached-prompt tokens. cachedTokens is the cached subset of inputTokens; it is billed at the gateway's cache-read rate when known, otherwise at the full input rate. Returns inputCost, outputCost, and totalCost in USD (or configured currency).
func (*PricingServiceImpl) FormatModelPricing ¶ added in v0.89.0
func (p *PricingServiceImpl) 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 (*PricingServiceImpl) GetInputPrice ¶ added in v0.86.0
func (p *PricingServiceImpl) 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 (*PricingServiceImpl) GetOutputPrice ¶ added in v0.86.0
func (p *PricingServiceImpl) 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 (*PricingServiceImpl) IsEnabled ¶ added in v0.86.1
func (p *PricingServiceImpl) IsEnabled() bool
IsEnabled returns whether pricing is enabled in the configuration.
func (*PricingServiceImpl) RequiresPro ¶ added in v0.118.0
func (p *PricingServiceImpl) 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 ResultBodyProvider ¶ added in v0.118.0
type ResultBodyProvider interface {
FormatResultBody(result *domain.ToolExecutionResult) string
}
ResultBodyProvider is an optional interface a tool may implement to expose its primary output (command stdout, file content, …) for the collapsed preview and the full-on-failure view. It is distinct from FormatPreview (a one-line summary) and FormatForLLM (the full tree) and lives in the services package so adding it does not touch the domain.Tool interface or its generated mocks.
type RuntimeType ¶ added in v0.82.0
type RuntimeType string
RuntimeType represents the type of container runtime
const ( RuntimeTypeDocker RuntimeType = "docker" RuntimeTypePodman RuntimeType = "podman" )
type SSEHTTPClientTransport ¶ added in v0.80.0
type SSEHTTPClientTransport struct {
// contains filtered or unexported fields
}
SSEHTTPClientTransport implements an SSE-aware HTTP client transport for MCP This handles servers that respond with Server-Sent Events format
func NewSSEHTTPClientTransport ¶ added in v0.80.0
func NewSSEHTTPClientTransport(endpoint string) *SSEHTTPClientTransport
NewSSEHTTPClientTransport creates a new SSE-aware HTTP client transport
func (*SSEHTTPClientTransport) Close ¶ added in v0.80.0
func (t *SSEHTTPClientTransport) Close() error
Close implements Transport.Close
func (*SSEHTTPClientTransport) Send ¶ added in v0.80.0
func (t *SSEHTTPClientTransport) Send(ctx context.Context, message *transport.BaseJsonRpcMessage) error
Send implements Transport.Send
func (*SSEHTTPClientTransport) SetCloseHandler ¶ added in v0.80.0
func (t *SSEHTTPClientTransport) SetCloseHandler(handler func())
SetCloseHandler implements Transport.SetCloseHandler
func (*SSEHTTPClientTransport) SetErrorHandler ¶ added in v0.80.0
func (t *SSEHTTPClientTransport) SetErrorHandler(handler func(error))
SetErrorHandler implements Transport.SetErrorHandler
func (*SSEHTTPClientTransport) SetMessageHandler ¶ added in v0.80.0
func (t *SSEHTTPClientTransport) SetMessageHandler(handler func(ctx context.Context, message *transport.BaseJsonRpcMessage))
SetMessageHandler implements Transport.SetMessageHandler
func (*SSEHTTPClientTransport) Start ¶ added in v0.80.0
func (t *SSEHTTPClientTransport) Start(ctx context.Context) error
Start implements Transport.Start
func (*SSEHTTPClientTransport) WithHeader ¶ added in v0.80.0
func (t *SSEHTTPClientTransport) WithHeader(key, value string) *SSEHTTPClientTransport
WithHeader adds a header to the request
type ScreenshotServer ¶ added in v0.96.0
type ScreenshotServer struct {
// contains filtered or unexported fields
}
ScreenshotServer provides an HTTP API for screenshot streaming
func NewScreenshotServer ¶ added in v0.96.0
func NewScreenshotServer(cfg *config.Config, imageService domain.ImageService, sessionID string) *ScreenshotServer
NewScreenshotServer creates a new screenshot server
func (*ScreenshotServer) GetLatestScreenshot ¶ added in v0.96.0
func (s *ScreenshotServer) GetLatestScreenshot() (*domain.Screenshot, error)
GetLatestScreenshot retrieves the latest screenshot from the buffer
func (*ScreenshotServer) Port ¶ added in v0.96.0
func (s *ScreenshotServer) Port() int
Port returns the port the server is listening on
func (*ScreenshotServer) Start ¶ added in v0.96.0
func (s *ScreenshotServer) Start() error
Start starts the HTTP server and background capture loop
func (*ScreenshotServer) Stop ¶ added in v0.96.0
func (s *ScreenshotServer) Stop() error
Stop stops the HTTP server and capture loop
type SessionRolloverManager ¶ added in v0.101.0
type SessionRolloverManager struct {
// contains filtered or unexported fields
}
SessionRolloverManager decides when to roll over a long-running conversation into a new file (matching the chat-mode `/compact` behavior) and exposes the machinery to perform that rollover. It also resolves "group key" inputs from the channel manager (e.g. `channel-telegram-XYZ`) to the current session UUID via the configured SessionGroupStorage backend, so callers like the channel manager can keep using a stable, deterministic identifier without worrying about which physical session it points at right now.
func NewSessionRolloverManager ¶ added in v0.101.0
func NewSessionRolloverManager( cfg *config.Config, optimizer domain.ConversationOptimizer, repo *PersistentConversationRepository, tokenizer *TokenizerService, groupStore storage.SessionGroupStorage, ) *SessionRolloverManager
NewSessionRolloverManager constructs a manager. The optimizer is required for PerformRollover to work; if it's nil, ShouldRollover always returns false and PerformRollover returns an error. This mirrors how the chat-mode /compact shortcut behaves when the optimizer is disabled. groupStore is required for non-UUID session-id resolution; if it is nil, group-keyed lookups will fall back to passing the raw id through.
func (*SessionRolloverManager) MaybeRollover ¶ added in v0.114.0
func (m *SessionRolloverManager) 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 agent` 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 (*SessionRolloverManager) PerformRollover ¶ added in v0.101.0
func (m *SessionRolloverManager) PerformRollover(ctx context.Context, model, groupKey string) (string, error)
PerformRollover runs the optimizer with force=true to produce a summary, calls StartNewConversation on the repo to begin a fresh conversation file, re-adds the summarized messages, and (if groupKey != "") updates the configured SessionGroupStorage to point the group at the new session ID.
This mirrors performCompactAsync in chat_shortcut_handler.go:510-615 - same optimizer call, same StartNewConversation call, same AddMessage loop.
Returns the new session UUID on success.
func (*SessionRolloverManager) ResolveSessionID ¶ added in v0.101.0
func (m *SessionRolloverManager) ResolveSessionID(rawID string) (string, string, error)
ResolveSessionID maps a raw --session-id value to the conversation ID that should actually be loaded.
- If rawID parses as a UUID, it is treated as a literal session ID and returned unchanged with an empty groupKey.
- Otherwise it is treated as a group key. The configured SessionGroupStorage is consulted: if the group exists, its current_session_id is returned; if it does not, the group is registered with rawID as its initial current_session_id (this is the migration path for existing channel JSONL files named after the deterministic group key).
Returns (sessionID, groupKey, error). On any error reading/writing the store, the function logs a warning and falls back to passing rawID through unchanged so the agent can still run.
func (*SessionRolloverManager) ShouldRollover ¶ added in v0.101.0
func (m *SessionRolloverManager) 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 StandardApprovalPolicy ¶ added in v0.97.0
type StandardApprovalPolicy struct {
// contains filtered or unexported fields
}
StandardApprovalPolicy implements the default approval policy with the following rules:
- Computer use tools (mouse, keyboard) always bypass approval (background execution)
- Auto-accept mode bypasses all approval 2.5. ReadOnly mode (Explore-like subagent) bypasses approval; its toolset is read-only by construction so nothing it can call mutates
- Non-chat (headless agent) mode bypasses approval; there the Bash tool's own per-mode gate (executeBash) decides what runs
- Bash commands are governed by the per-mode allow-list (config.IsBashCommandAllowed): reached only in chat, non-auto mode, so allowed commands bypass approval and anything off-list prompts the user
- Other tools check configuration (per-tool or global require_approval setting)
func NewStandardApprovalPolicy ¶ added in v0.97.0
func NewStandardApprovalPolicy(cfg *config.Config, stateManager domain.AgentModeManager) *StandardApprovalPolicy
NewStandardApprovalPolicy creates a new standard approval policy
func (*StandardApprovalPolicy) ShouldRequireApproval ¶ added in v0.97.0
func (p *StandardApprovalPolicy) ShouldRequireApproval( ctx context.Context, toolCall *sdk.ChatCompletionMessageToolCall, isChatMode bool, ) bool
ShouldRequireApproval implements the approval decision logic
type StateManager ¶ added in v0.27.0
type StateManager struct {
// contains filtered or unexported fields
}
StateManager provides centralized state management with proper synchronization
func NewStateManager ¶ added in v0.27.0
func NewStateManager(debugMode bool) *StateManager
NewStateManager creates a new state manager
func (*StateManager) AddQueuedMessage ¶ added in v0.53.0
func (sm *StateManager) AddQueuedMessage(message sdk.Message, requestID string)
AddQueuedMessage adds a message to the input queue
func (*StateManager) AreAllAgentsReady ¶ added in v0.67.0
func (sm *StateManager) AreAllAgentsReady() bool
AreAllAgentsReady returns true if all agents are ready
func (*StateManager) BroadcastEvent ¶ added in v0.96.0
func (sm *StateManager) BroadcastEvent(event domain.ChatEvent)
BroadcastEvent publishes an event to the EventBridge for floating window
func (*StateManager) ClearAgentReadiness ¶ added in v0.67.0
func (sm *StateManager) ClearAgentReadiness()
ClearAgentReadiness clears the agent readiness state
func (*StateManager) ClearApprovalUIState ¶ added in v0.27.0
func (sm *StateManager) ClearApprovalUIState()
ClearApprovalUIState clears the approval UI state
func (*StateManager) ClearComputerUsePauseState ¶ added in v0.96.0
func (sm *StateManager) ClearComputerUsePauseState()
ClearComputerUsePauseState clears the pause state
func (*StateManager) ClearFileSelectionState ¶ added in v0.27.0
func (sm *StateManager) ClearFileSelectionState()
ClearFileSelectionState clears the file selection state
func (*StateManager) ClearLastClickCoordinates ¶ added in v0.96.0
func (sm *StateManager) ClearLastClickCoordinates()
ClearLastClickCoordinates clears the stored click coordinates
func (*StateManager) ClearLastFocusedApp ¶ added in v0.96.0
func (sm *StateManager) ClearLastFocusedApp()
ClearLastFocusedApp clears the stored focused app
func (*StateManager) ClearMessageEditState ¶ added in v0.92.0
func (sm *StateManager) ClearMessageEditState()
ClearMessageEditState clears the message edit state
func (*StateManager) ClearPlanApprovalUIState ¶ added in v0.68.0
func (sm *StateManager) ClearPlanApprovalUIState()
ClearPlanApprovalUIState clears the plan approval UI state
func (*StateManager) ClearQueuedMessages ¶ added in v0.53.0
func (sm *StateManager) ClearQueuedMessages()
ClearQueuedMessages clears all queued messages
func (*StateManager) ClearUserQuestionUIState ¶ added in v0.124.0
func (sm *StateManager) ClearUserQuestionUIState()
ClearUserQuestionUIState clears the AskUserQuestion form state
func (*StateManager) CompleteCurrentTool ¶ added in v0.27.0
func (sm *StateManager) CompleteCurrentTool(result *domain.ToolExecutionResult) error
CompleteCurrentTool marks the current tool as completed
func (*StateManager) CycleAgentMode ¶ added in v0.56.0
func (sm *StateManager) CycleAgentMode() domain.AgentMode
CycleAgentMode cycles to the next agent mode
func (*StateManager) EndChatSession ¶ added in v0.27.0
func (sm *StateManager) EndChatSession()
EndChatSession ends the current chat session
func (*StateManager) EndToolExecution ¶ added in v0.27.0
func (sm *StateManager) EndToolExecution()
EndToolExecution ends the current tool execution session
func (*StateManager) FailCurrentTool ¶ added in v0.27.0
func (sm *StateManager) FailCurrentTool(result *domain.ToolExecutionResult) error
FailCurrentTool marks the current tool as failed
func (*StateManager) GetAgentMode ¶ added in v0.56.0
func (sm *StateManager) GetAgentMode() domain.AgentMode
GetAgentMode returns the current agent mode
func (*StateManager) GetAgentReadiness ¶ added in v0.67.0
func (sm *StateManager) GetAgentReadiness() *domain.AgentReadinessState
GetAgentReadiness returns the current agent readiness state
func (*StateManager) GetApprovalUIState ¶ added in v0.27.0
func (sm *StateManager) GetApprovalUIState() *domain.ApprovalUIState
GetApprovalUIState returns the current approval UI state
func (*StateManager) GetChatSession ¶ added in v0.27.0
func (sm *StateManager) GetChatSession() *domain.ChatSession
GetChatSession returns the current chat session (read-only)
func (*StateManager) GetCurrentView ¶ added in v0.27.0
func (sm *StateManager) GetCurrentView() domain.ViewState
GetCurrentView returns the current view state
func (*StateManager) GetDimensions ¶ added in v0.27.0
func (sm *StateManager) GetDimensions() (int, int)
GetDimensions returns the current UI dimensions
func (*StateManager) GetEventBridge ¶ added in v0.96.0
func (sm *StateManager) GetEventBridge() domain.EventBridge
GetEventBridge returns the event bridge for control event forwarding
func (*StateManager) GetFileSelectionState ¶ added in v0.27.0
func (sm *StateManager) GetFileSelectionState() *domain.FileSelectionState
GetFileSelectionState returns the current file selection state
func (*StateManager) GetLastClickCoordinates ¶ added in v0.96.0
func (sm *StateManager) GetLastClickCoordinates() (x, y int)
GetLastClickCoordinates returns the coordinates of the last click
func (*StateManager) GetLastFocusedApp ¶ added in v0.96.0
func (sm *StateManager) GetLastFocusedApp() string
GetLastFocusedApp returns the bundle ID of the last focused application
func (*StateManager) GetMessageEditState ¶ added in v0.92.0
func (sm *StateManager) GetMessageEditState() *domain.MessageEditState
GetMessageEditState returns the current message edit state
func (*StateManager) GetPausedRequestID ¶ added in v0.96.0
func (sm *StateManager) GetPausedRequestID() string
GetPausedRequestID returns the request ID of the paused execution
func (*StateManager) GetPlanApprovalUIState ¶ added in v0.68.0
func (sm *StateManager) GetPlanApprovalUIState() *domain.PlanApprovalUIState
GetPlanApprovalUIState returns the current plan approval UI state
func (*StateManager) GetPreviousView ¶ added in v0.86.0
func (sm *StateManager) GetPreviousView() domain.ViewState
GetPreviousView returns the previous view state
func (*StateManager) GetQueuedMessages ¶ added in v0.53.0
func (sm *StateManager) GetQueuedMessages() []domain.QueuedMessage
GetQueuedMessages returns the current queued messages
func (*StateManager) GetRetryStatus ¶ added in v0.142.0
func (sm *StateManager) GetRetryStatus() *domain.RetryStatus
GetRetryStatus returns a copy of the current retry status, or nil when the connection is healthy. Besides explicit reconnect attempts (set by the agent's reconnect loop), it synthesizes a zero-attempt status when a streaming session has produced no chunks for stallThreshold - the render tick calls this on every frame, so a stalled connection surfaces without any timer of its own. A synthesized status has Attempt == 0. Terminal sessions never report a status, so a stale explicit retry can't outlive the turn it belonged to (the input field is disabled while this returns non-nil).
func (*StateManager) GetTodos ¶ added in v0.63.1
func (sm *StateManager) GetTodos() []domain.TodoItem
GetTodos returns the current todo list
func (*StateManager) GetToolExecution ¶ added in v0.27.0
func (sm *StateManager) GetToolExecution() *domain.ToolExecutionSession
GetToolExecution returns the current tool execution session (read-only)
func (*StateManager) GetUserQuestionUIState ¶ added in v0.124.0
func (sm *StateManager) GetUserQuestionUIState() *domain.UserQuestionUIState
GetUserQuestionUIState returns the current AskUserQuestion form state
func (*StateManager) InitializeAgentReadiness ¶ added in v0.67.0
func (sm *StateManager) InitializeAgentReadiness(totalAgents int)
InitializeAgentReadiness initializes the agent readiness tracking
func (*StateManager) IsAgentBusy ¶ added in v0.53.0
func (sm *StateManager) IsAgentBusy() bool
IsAgentBusy returns true if the agent is currently processing a request
func (*StateManager) IsComputerUsePaused ¶ added in v0.96.0
func (sm *StateManager) IsComputerUsePaused() bool
IsComputerUsePaused returns whether computer use is currently paused
func (*StateManager) IsDebugMode ¶ added in v0.27.0
func (sm *StateManager) IsDebugMode() bool
IsDebugMode returns whether debug mode is enabled
func (*StateManager) IsEditingMessage ¶ added in v0.92.0
func (sm *StateManager) IsEditingMessage() bool
IsEditingMessage returns true if currently editing a message
func (*StateManager) PopQueuedMessage ¶ added in v0.53.0
func (sm *StateManager) PopQueuedMessage() *domain.QueuedMessage
PopQueuedMessage removes and returns the first message from the queue (FIFO order)
func (*StateManager) RecoverFromInconsistentState ¶ added in v0.27.0
func (sm *StateManager) RecoverFromInconsistentState() error
RecoverFromInconsistentState attempts to recover from an inconsistent state
func (*StateManager) RemoveAgent ¶ added in v0.67.0
func (sm *StateManager) RemoveAgent(name string)
RemoveAgent removes an agent from the readiness tracking
func (*StateManager) SetAgentError ¶ added in v0.67.0
func (sm *StateManager) SetAgentError(name string, err error)
SetAgentError sets an error for a specific agent
func (*StateManager) SetAgentMode ¶ added in v0.56.0
func (sm *StateManager) SetAgentMode(mode domain.AgentMode)
SetAgentMode sets the agent mode
func (*StateManager) SetChatPending ¶ added in v0.63.1
func (sm *StateManager) SetChatPending()
SetChatPending marks the agent as busy before the chat actually starts. This prevents race conditions where messages might not be queued between the time we decide to start a chat and when StartChatSession is called.
Promotes to "pending" if there is no existing chat session OR if the existing session is in a terminal status (Completed/Error/Cancelled/Idle). Terminal sessions are leftovers from a prior chat that hasn't been GC'd yet; treating them as "in progress" would make IsAgentBusy() return false here but true for a subsequent caller that just won the SetChatPending race, which is exactly the window the chat-mode async rollover relies on for queueing.
func (*StateManager) SetComputerUsePaused ¶ added in v0.96.0
func (sm *StateManager) SetComputerUsePaused(paused bool, requestID string)
SetComputerUsePaused sets the paused state for computer use
func (*StateManager) SetDebugMode ¶ added in v0.27.0
func (sm *StateManager) SetDebugMode(enabled bool)
SetDebugMode enables or disables debug mode
func (*StateManager) SetDimensions ¶ added in v0.27.0
func (sm *StateManager) SetDimensions(width, height int)
SetDimensions updates the UI dimensions
func (*StateManager) SetEventBridge ¶ added in v0.96.0
func (sm *StateManager) SetEventBridge(bridge domain.EventBridge)
SetEventBridge sets the event bridge for multicasting events to floating window
func (*StateManager) SetFileSelectedIndex ¶ added in v0.27.0
func (sm *StateManager) SetFileSelectedIndex(index int)
SetFileSelectedIndex sets the selected file index
func (*StateManager) SetLastClickCoordinates ¶ added in v0.96.0
func (sm *StateManager) SetLastClickCoordinates(x, y int)
SetLastClickCoordinates stores the coordinates of the last click
func (*StateManager) SetLastFocusedApp ¶ added in v0.96.0
func (sm *StateManager) SetLastFocusedApp(appID string)
SetLastFocusedApp stores the bundle ID of the last focused application
func (*StateManager) SetMessageEditState ¶ added in v0.92.0
func (sm *StateManager) SetMessageEditState(state *domain.MessageEditState)
SetMessageEditState sets the message edit state
func (*StateManager) SetPlanApprovalSelectedIndex ¶ added in v0.68.0
func (sm *StateManager) SetPlanApprovalSelectedIndex(index int)
SetPlanApprovalSelectedIndex sets the plan approval selection index
func (*StateManager) SetRetryStatus ¶ added in v0.142.0
func (sm *StateManager) SetRetryStatus(status *domain.RetryStatus)
SetRetryStatus updates the retry status on the current chat session. Called by the agent's reconnect loop to provide visual feedback in the status bar while it is reconnecting after a failure.
func (*StateManager) SetStallThreshold ¶ added in v0.142.0
func (sm *StateManager) SetStallThreshold(threshold time.Duration)
SetStallThreshold sets how long a streaming session may go without chunks before GetRetryStatus reports it as reconnecting. Zero or negative disables stall detection.
func (*StateManager) SetTodos ¶ added in v0.63.1
func (sm *StateManager) SetTodos(todos []domain.TodoItem)
SetTodos sets the todo list
func (*StateManager) SetupApprovalUIState ¶ added in v0.56.0
func (sm *StateManager) SetupApprovalUIState(toolCall *sdk.ChatCompletionMessageToolCall, responseChan chan domain.ApprovalAction)
SetupApprovalUIState initializes approval UI state
func (*StateManager) SetupFileSelection ¶ added in v0.27.0
func (sm *StateManager) SetupFileSelection(files []string)
SetupFileSelection initializes file selection state
func (*StateManager) SetupPlanApprovalUIState ¶ added in v0.68.0
func (sm *StateManager) SetupPlanApprovalUIState(planContent, planID string, responseChan chan domain.PlanApprovalAction)
SetupPlanApprovalUIState initializes plan approval UI state
func (*StateManager) SetupUserQuestionUIState ¶ added in v0.124.0
func (sm *StateManager) SetupUserQuestionUIState(questions []domain.UserQuestion, responseChan chan []domain.UserQuestionAnswer)
SetupUserQuestionUIState initializes the AskUserQuestion form state
func (*StateManager) StartChatSession ¶ added in v0.27.0
func (sm *StateManager) StartChatSession(requestID, model string, eventChan <-chan domain.ChatEvent) error
StartChatSession starts a new chat session
func (*StateManager) StartToolExecution ¶ added in v0.27.0
func (sm *StateManager) StartToolExecution(toolCalls []sdk.ChatCompletionMessageToolCall) error
StartToolExecution starts a new tool execution session
func (*StateManager) TouchChatActivity ¶ added in v0.142.0
func (sm *StateManager) TouchChatActivity()
TouchChatActivity records stream output on the current session, clearing any retry status and resetting the stall clock.
func (*StateManager) TransitionToView ¶ added in v0.27.0
func (sm *StateManager) TransitionToView(newView domain.ViewState) error
TransitionToView transitions to a new view with validation and logging
func (*StateManager) UpdateAgentPullProgress ¶ added in v0.149.0
func (sm *StateManager) UpdateAgentPullProgress(name string, done, total int)
UpdateAgentPullProgress updates the image pull layer counts for a specific agent
func (*StateManager) UpdateAgentStatus ¶ added in v0.67.0
func (sm *StateManager) UpdateAgentStatus(name string, state domain.AgentState, message string, url string, image string)
UpdateAgentStatus updates the status of a specific agent
func (*StateManager) UpdateChatStatus ¶ added in v0.27.0
func (sm *StateManager) UpdateChatStatus(status domain.ChatStatus) error
UpdateChatStatus updates the chat session status with validation
func (*StateManager) UpdateFileSearchQuery ¶ added in v0.27.0
func (sm *StateManager) UpdateFileSearchQuery(query string)
UpdateFileSearchQuery updates the file search query
type StrictApprovalPolicy ¶ added in v0.97.0
type StrictApprovalPolicy struct{}
StrictApprovalPolicy is an alternative policy that requires approval for all tools Useful for security-sensitive environments or auditing
func NewStrictApprovalPolicy ¶ added in v0.97.0
func NewStrictApprovalPolicy() *StrictApprovalPolicy
NewStrictApprovalPolicy creates a new strict approval policy
func (*StrictApprovalPolicy) ShouldRequireApproval ¶ added in v0.97.0
func (p *StrictApprovalPolicy) ShouldRequireApproval( ctx context.Context, toolCall *sdk.ChatCompletionMessageToolCall, isChatMode bool, ) bool
ShouldRequireApproval always returns true (approval required for all tools) Exception: Computer use tools still bypass for UX reasons
type SyntheticToolResponse ¶ added in v0.110.1
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.110.1
func EnsureToolCallsClosed(conv []sdk.Message) ([]sdk.Message, []SyntheticToolResponse)
EnsureToolCallsClosed enforces the OpenAI-style invariant that every assistant message with tool_calls is followed by a Tool-role message for each tool_call_id. For every unmatched tool_call_id it inserts a synthetic Tool-role response with CancelledToolResponseContent at the tail of the existing tool responses for that assistant turn, preserving the original tool_calls order.
The returned conversation is a copy; the input slice is not mutated. The returned synthetics list is in insertion order and is non-nil only when at least one synthetic was added.
Idempotent: running on an already-repaired conversation returns the input shape with an empty synthetics slice.
type TaskRetentionService ¶ added in v0.53.3
type TaskRetentionService struct {
// contains filtered or unexported fields
}
TaskRetentionService manages in-memory retention of completed/terminal A2A tasks
func NewTaskRetentionService ¶ added in v0.53.3
func NewTaskRetentionService(maxRetention int) *TaskRetentionService
NewTaskRetentionService creates a new task retention service
func (*TaskRetentionService) AddTask ¶ added in v0.53.3
func (t *TaskRetentionService) AddTask(task domain.TaskInfo)
AddTask adds a terminal task (completed, failed, canceled, etc.) to retention
func (*TaskRetentionService) Clear ¶ added in v0.53.3
func (t *TaskRetentionService) Clear()
Clear removes all retained tasks
func (*TaskRetentionService) GetMaxRetention ¶ added in v0.53.3
func (t *TaskRetentionService) GetMaxRetention() int
GetMaxRetention returns the current maximum retention count
func (*TaskRetentionService) GetTasks ¶ added in v0.53.3
func (t *TaskRetentionService) GetTasks() []domain.TaskInfo
GetTasks returns all retained tasks
func (*TaskRetentionService) SetMaxRetention ¶ added in v0.53.3
func (t *TaskRetentionService) SetMaxRetention(maxRetention int)
SetMaxRetention updates the maximum retention count
type TitleGenerator ¶ added in v0.46.0
TitleGenerator interface for conversation title generation
type TokenizerConfig ¶ added in v0.64.0
type TokenizerConfig struct {
// CharsPerToken is the average characters per token (default: 4.0)
CharsPerToken float64
// MessageOverhead is tokens per message for formatting (default: 4)
MessageOverhead int
// ToolCallOverhead is extra tokens per tool call (default: 10)
ToolCallOverhead int
}
TokenizerConfig holds configuration for the tokenizer service
func DefaultTokenizerConfig ¶ added in v0.64.0
func DefaultTokenizerConfig() TokenizerConfig
DefaultTokenizerConfig returns the default tokenizer configuration
type TokenizerService ¶ added in v0.64.0
type TokenizerService struct {
// contains filtered or unexported fields
}
TokenizerService provides token counting functionality for LLM messages. This is a polyfill for providers (like Ollama Cloud) that don't return token usage metrics in their API responses.
func NewTokenizerService ¶ added in v0.64.0
func NewTokenizerService(config TokenizerConfig) *TokenizerService
NewTokenizerService creates a new tokenizer service with the given configuration
func (*TokenizerService) AdjustedEstimate ¶ added in v0.64.0
func (t *TokenizerService) AdjustedEstimate(text string) int
AdjustedEstimate provides a more accurate estimate for code vs prose
func (*TokenizerService) CalculateUsagePolyfill ¶ added in v0.64.0
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 ¶ added in v0.143.0
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 ¶ added in v0.64.0
func (t *TokenizerService) EstimateMessageTokens(msg sdk.Message) int
EstimateMessageTokens estimates the total tokens for a single message
func (*TokenizerService) EstimateMessagesTokens ¶ added in v0.64.0
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 ¶ added in v0.64.0
func (t *TokenizerService) EstimateResponseTokens(response string) int
EstimateResponseTokens estimates the tokens in an LLM response string
func (*TokenizerService) EstimateTokenCount ¶ added in v0.64.0
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 ¶ added in v0.64.0
func (t *TokenizerService) EstimateToolDefinitionsTokens(tools []sdk.ChatCompletionTool) int
EstimateToolDefinitionsTokens estimates tokens for tool definitions
func (*TokenizerService) GetToolStats ¶ added in v0.81.0
func (t *TokenizerService) GetToolStats(toolService domain.ToolService, agentMode domain.AgentMode) (tokens int, count int)
GetToolStats returns token count and tool count for a given agent mode
func (*TokenizerService) IsLikelyCodeContent ¶ added in v0.64.0
func (t *TokenizerService) IsLikelyCodeContent(text string) bool
IsLikelyCodeContent checks if the text appears to be code Code typically has a higher tokens-per-character ratio
func (*TokenizerService) ShouldUsePolyfill ¶ added in v0.64.0
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 ToolFormatterService ¶ added in v0.33.4
type ToolFormatterService struct {
// contains filtered or unexported fields
}
ToolFormatterService provides formatting for tool results by delegating to individual tools
func NewToolFormatterService ¶ added in v0.33.4
func NewToolFormatterService(registry ToolRegistry, styleProvider *styles.Provider) *ToolFormatterService
NewToolFormatterService creates a new tool formatter service
func (*ToolFormatterService) FormatToolCall ¶ added in v0.33.4
func (s *ToolFormatterService) FormatToolCall(toolName string, args map[string]any) string
FormatToolCall formats a tool call for consistent display
func (*ToolFormatterService) FormatToolResultExpanded ¶ added in v0.33.4
func (s *ToolFormatterService) FormatToolResultExpanded(result *domain.ToolExecutionResult, terminalWidth int) string
FormatToolResultExpanded formats the expanded (ctrl+o) tool result: the tool's existing detail tree, themed for consistency with the rest of the UI (accent+bold tool-call line, dim connectors, accent field labels), with a dim collapse hint. The underlying tree text is unchanged, so tool-specific bodies (diffs, raw output) are preserved exactly.
func (*ToolFormatterService) FormatToolResultForLLM ¶ added in v0.33.4
func (s *ToolFormatterService) FormatToolResultForLLM(result *domain.ToolExecutionResult) string
FormatToolResultForLLM formats tool execution results for LLM consumption
func (*ToolFormatterService) FormatToolResultForUI ¶ added in v0.33.4
func (s *ToolFormatterService) FormatToolResultForUI(result *domain.ToolExecutionResult, terminalWidth int) string
FormatToolResultForUI formats the collapsed (default) tool result: a themed status line followed by an indented dim output preview (first 5 lines on success, the full output on failure) and a "+N lines · ctrl+o to expand" footer.
func (*ToolFormatterService) RenderToolSummary ¶ added in v0.143.0
func (s *ToolFormatterService) RenderToolSummary(icon, toolName string, args map[string]any, trailing string, terminalWidth int) string
RenderToolSummary renders the shared "<icon> Name(args) <trailing>" line used by the collapsed status line, the live preview, the approval summary and the queue preview. icon and trailing are already-styled by the caller (each surface owns its own status semantics); the tool name and the width-aware, path-shortened argument preview are formatted identically everywhere, replacing the per-call-site drift (e.g. the old byte-slice `args[:47]` truncation in the live renderer). Pass icon=="" / trailing=="" to omit either segment.
func (*ToolFormatterService) SetHintFormatter ¶ added in v0.118.0
func (s *ToolFormatterService) SetHintFormatter(h HintProvider)
SetHintFormatter wires the keybinding hint resolver so the collapsed and expanded views can show the "ctrl+o to expand/collapse" affordance. Nil is safe - the hint is simply omitted.
func (*ToolFormatterService) SetMaxResultBytes ¶ added in v0.143.0
func (s *ToolFormatterService) SetMaxResultBytes(n int)
SetMaxResultBytes caps the size of a single tool result fed back to the LLM (FormatToolResultForLLM). 0 disables the cap. Wired from tools.max_result_bytes in the container so one oversized tool output can't dominate the context window.
func (*ToolFormatterService) ShouldAlwaysExpandTool ¶ added in v0.36.0
func (s *ToolFormatterService) ShouldAlwaysExpandTool(toolName string) bool
ShouldAlwaysExpandTool checks if a tool result should always be expanded
Source Files
¶
- agent_manager.go
- agent_manager_additions.go
- agents.go
- approval_policy.go
- background_jobs.go
- background_shell_service.go
- background_task_registry.go
- background_task_service.go
- background_tasks_waiter.go
- channel_commands.go
- channel_manager.go
- circular_screenshot_buffer.go
- container_network.go
- container_runtime_factory.go
- conversation.go
- conversation_optimizer.go
- conversation_title_generator.go
- conversation_validator.go
- docker_runtime.go
- file.go
- gateway_manager.go
- image_optimizer.go
- image_service.go
- mcp_manager.go
- mcp_sse_transport.go
- message_queue.go
- model.go
- persistent_conversation.go
- podman_runtime.go
- pricing_service.go
- pull_progress.go
- screenshot_server.go
- session_rollover_manager.go
- state_manager.go
- task_retention.go
- tokenizer.go
- tool_formatter.go
- tool_result_view.go
- tools.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package agentrunner centralizes spawning `infer agent` as a subprocess and streaming its stdout.
|
Package agentrunner centralizes spawning `infer agent` as a subprocess and streaming its stdout. |
|
Package directexec owns the UI side of user-typed direct-execution commands: `!command` (bash) and `!!Tool(...)` (tool).
|
Package directexec owns the UI side of user-typed direct-execution commands: `!command` (bash) and `!!Tool(...)` (tool). |
|
Package gitdiff is a small, focused data layer behind the `/diff` changes panel.
|
Package gitdiff is a small, focused data layer behind the `/diff` changes panel. |
|
Package githubissues provides cached, gh-CLI-backed access to the current repository's GitHub issues for the chat input's "#" autocomplete and "#N" inline expansion features.
|
Package githubissues provides cached, gh-CLI-backed access to the current repository's GitHub issues for the chat input's "#" autocomplete and "#N" inline expansion features. |
|
Package githubsetup implements domain.GitHubSetupService for the GitHub Action CI setup flow.
|
Package githubsetup implements domain.GitHubSetupService for the GitHub Action CI setup flow. |
|
Package heartbeat implements a periodic "wake-up" service that spawns the agent on a fixed interval to check for pending work.
|
Package heartbeat implements a periodic "wake-up" service that spawns the agent on a fixed interval to check for pending work. |
|
Package jobs provides the Supervisor: the single, long-lived owner of every background-work monitor goroutine in an agent session.
|
Package jobs provides the Supervisor: the single, long-lived owner of every background-work monitor goroutine in an agent session. |
|
Package plugins implements installation and runtime surfacing of Claude Code-format plugins: SKILL.md skills plus an optional AGENTS.md instruction ruleset.
|
Package plugins implements installation and runtime surfacing of Claude Code-format plugins: SKILL.md skills plus an optional AGENTS.md instruction ruleset. |
|
Package provisioner rents on-demand GPU instances running llama.cpp and exposes them as a llamacpp provider endpoint (issue #939).
|
Package provisioner rents on-demand GPU instances running llama.cpp and exposes them as a llamacpp provider endpoint (issue #939). |
|
Package skills implements discovery of Agent Skills.
|
Package skills implements discovery of Agent Skills. |
|
Package toolcoordinator owns the UI side of the tool round-trip - the streaming-status events emitted while the model is producing a tool call, the approval handshake that forwards the user's accept/reject back to the agent, and the execution-progress events while the tool runs.
|
Package toolcoordinator owns the UI side of the tool round-trip - the streaming-status events emitted while the model is producing a tool call, the approval handshake that forwards the user's accept/reject back to the agent, and the execution-progress events while the tool runs. |