Documentation
¶
Index ¶
- Constants
- Variables
- func AnyToolFailed(results []ConversationEntry) bool
- func AnyToolRejected(results []ConversationEntry) bool
- func BashAllowModeKey(ctx context.Context) string
- func CreateTitleFromMessage(content string) string
- func FormatChannelSessionID(channel, senderID string) string
- func FormatModelPricingLabel(pricingService PricingService, model string) string
- func GetBashDetachChannel(ctx context.Context) <-chan struct{}
- func GetModel(ctx context.Context) string
- func GetSessionID(ctx context.Context) string
- func GetToolCallID(ctx context.Context) string
- func GetTraceEnv(ctx context.Context) []string
- func HasBashDetachChannel(ctx context.Context) bool
- func HasBashOutputCallback(ctx context.Context) bool
- func HasChatHandler(ctx context.Context) bool
- func HasSessionID(ctx context.Context) bool
- func HasUserQuestionBroker(ctx context.Context) bool
- func IsDirectExecution(ctx context.Context) bool
- func IsToolApproved(ctx context.Context) bool
- func ParseChannelSessionID(sessionID string) (channel, recipientID string, ok bool)
- func WithAgentMode(ctx context.Context, mode AgentMode) context.Context
- func WithBashDetachChannel(ctx context.Context, ch <-chan struct{}) context.Context
- func WithBashOutputCallback(ctx context.Context, callback BashOutputCallback) context.Context
- func WithChatHandler(ctx context.Context, handler BashDetachChannelHolder) context.Context
- func WithDirectExecution(ctx context.Context) context.Context
- func WithModel(ctx context.Context, model string) context.Context
- func WithSessionID(ctx context.Context, sessionID string) context.Context
- func WithToolApproved(ctx context.Context) context.Context
- func WithToolCallID(ctx context.Context, id string) context.Context
- func WithTraceEnv(ctx context.Context, env []string) context.Context
- func WithUserQuestionBroker(ctx context.Context, broker UserQuestionBroker) context.Context
- type A2AAgentService
- type A2AClearer
- type A2AStateProvider
- type A2ATaskCompletedEvent
- type A2ATaskCoordinator
- type A2ATaskFailedEvent
- type A2ATaskInputRequiredEvent
- type A2ATaskStatusUpdateEvent
- type A2ATaskSubmittedEvent
- type A2ATaskTracker
- type A2AToolCallExecutedEvent
- type ActiveToolTracker
- type AgentContext
- type AgentErrorMessage
- type AgentEvent
- type AgentExecutionState
- type AgentManager
- type AgentMode
- type AgentModeManager
- type AgentReadinessManager
- type AgentReadinessState
- type AgentRequest
- type AgentService
- type AgentState
- type AgentStateMachine
- type AgentStatus
- type AgentStatusUpdateEvent
- type AllToolsProcessedEvent
- type ApplicationState
- func (s *ApplicationState) AddQueuedMessage(message sdk.Message, requestID string)
- func (s *ApplicationState) AreAllAgentsReady() bool
- func (s *ApplicationState) ClearAgentReadiness()
- func (s *ApplicationState) ClearApprovalUIState()
- func (s *ApplicationState) ClearComputerUsePauseState()
- func (s *ApplicationState) ClearFileSelectionState()
- func (s *ApplicationState) ClearLastClickCoordinates()
- func (s *ApplicationState) ClearLastFocusedApp()
- func (s *ApplicationState) ClearMessageEditState()
- func (s *ApplicationState) ClearPlanApprovalUIState()
- func (s *ApplicationState) ClearQueuedMessages()
- func (s *ApplicationState) ClearUserQuestionUIState()
- func (s *ApplicationState) CompleteCurrentTool(result *ToolExecutionResult) error
- func (s *ApplicationState) CycleAgentMode() AgentMode
- func (s *ApplicationState) EndChatSession()
- func (s *ApplicationState) EndToolExecution()
- func (s *ApplicationState) FailCurrentTool(result *ToolExecutionResult) error
- func (s *ApplicationState) GetAgentMode() AgentMode
- func (s *ApplicationState) GetAgentReadiness() *AgentReadinessState
- func (s *ApplicationState) GetApprovalUIState() *ApprovalUIState
- func (s *ApplicationState) GetChatSession() *ChatSession
- func (s *ApplicationState) GetCurrentView() ViewState
- func (s *ApplicationState) GetDimensions() (int, int)
- func (s *ApplicationState) GetFileSelectionState() *FileSelectionState
- func (s *ApplicationState) GetLastClickCoordinates() (x, y int)
- func (s *ApplicationState) GetLastFocusedApp() string
- func (s *ApplicationState) GetMessageEditState() *MessageEditState
- func (s *ApplicationState) GetPausedRequestID() string
- func (s *ApplicationState) GetPlanApprovalUIState() *PlanApprovalUIState
- func (s *ApplicationState) GetPreviousView() ViewState
- func (s *ApplicationState) GetQueuedMessages() []QueuedMessage
- func (s *ApplicationState) GetRetryStatus() *RetryStatus
- func (s *ApplicationState) GetTodos() []TodoItem
- func (s *ApplicationState) GetToolExecution() *ToolExecutionSession
- func (s *ApplicationState) GetUserQuestionUIState() *UserQuestionUIState
- func (s *ApplicationState) InitializeAgentReadiness(totalAgents int)
- func (s *ApplicationState) IsComputerUsePaused() bool
- func (s *ApplicationState) IsDebugMode() bool
- func (s *ApplicationState) IsEditingMessage() bool
- func (s *ApplicationState) PopQueuedMessage() *QueuedMessage
- func (s *ApplicationState) RemoveAgent(name string)
- func (s *ApplicationState) SetAgentError(name string, err error)
- func (s *ApplicationState) SetAgentMode(mode AgentMode)
- func (s *ApplicationState) SetChatPending()
- func (s *ApplicationState) SetComputerUsePaused(paused bool, requestID string)
- func (s *ApplicationState) SetDebugMode(enabled bool)
- func (s *ApplicationState) SetDimensions(width, height int)
- func (s *ApplicationState) SetFileSelectedIndex(index int)
- func (s *ApplicationState) SetLastClickCoordinates(x, y int)
- func (s *ApplicationState) SetLastFocusedApp(appID string)
- func (s *ApplicationState) SetMessageEditState(state *MessageEditState)
- func (s *ApplicationState) SetPlanApprovalSelectedIndex(index int)
- func (s *ApplicationState) SetRetryStatus(status *RetryStatus)
- func (s *ApplicationState) SetTodos(todos []TodoItem)
- func (s *ApplicationState) SetupApprovalUIState(toolCall *sdk.ChatCompletionMessageToolCall, responseChan chan ApprovalAction)
- func (s *ApplicationState) SetupFileSelection(files []string)
- func (s *ApplicationState) SetupPlanApprovalUIState(planContent, planID string, responseChan chan PlanApprovalAction)
- func (s *ApplicationState) SetupUserQuestionUIState(questions []UserQuestion, responseChan chan []UserQuestionAnswer)
- func (s *ApplicationState) StartChatSession(requestID, model string, eventChan <-chan ChatEvent)
- func (s *ApplicationState) StartToolExecution(tools []ToolCall)
- func (s *ApplicationState) TouchChatActivity()
- func (s *ApplicationState) TransitionToView(newView ViewState) error
- func (s *ApplicationState) UpdateAgentPullProgress(name string, done, total int)
- func (s *ApplicationState) UpdateAgentStatus(name string, state AgentState, message string, url string, image string)
- func (s *ApplicationState) UpdateChatStatus(status ChatStatus) error
- func (s *ApplicationState) UpdateFileSearchQuery(query string)
- type ApprovalAction
- type ApprovalChannel
- type ApprovalCoordinator
- type ApprovalFailedEvent
- type ApprovalPolicy
- type ApprovalRequest
- type ApprovalResponse
- type ApprovalUIManager
- type ApprovalUIState
- type AutocompleteCompleteEvent
- type AutocompleteHideEvent
- type AutocompleteUpdateEvent
- type BackgroundJob
- type BackgroundShell
- type BackgroundShellRequestEvent
- type BackgroundShellService
- type BackgroundTaskRegistry
- type BackgroundTaskService
- type BackgroundTasksChangedEvent
- type BaseChatEvent
- type BaseFormatter
- func (f BaseFormatter) FormatAsJSON(data any) string
- func (f BaseFormatter) FormatDuration(result *ToolExecutionResult) string
- func (f BaseFormatter) FormatExpanded(result *ToolExecutionResult, dataContent string) string
- func (f BaseFormatter) FormatStatus(success bool) string
- func (f BaseFormatter) FormatStatusIcon(success bool) string
- func (f BaseFormatter) FormatToolCall(args map[string]any, expanded bool) string
- func (f BaseFormatter) GetDomainFromURL(url string) string
- func (f BaseFormatter) GetFileName(path string) string
- func (f BaseFormatter) ShouldCollapseArg(key string) bool
- func (f BaseFormatter) TruncateText(text string, maxLength int) string
- type BashCommandCompletedEvent
- type BashDetachChannelHolder
- type BashOutputCallback
- type BashOutputChunkEvent
- type BashToolResult
- type BorderOverlayEvent
- type CachedAgentCard
- type Channel
- type ChannelCommand
- type CharmTheme
- func (t *CharmTheme) GetAccentColor() string
- func (t *CharmTheme) GetAssistantColor() string
- func (t *CharmTheme) GetBorderColor() string
- func (t *CharmTheme) GetDiffAddColor() string
- func (t *CharmTheme) GetDiffRemoveColor() string
- func (t *CharmTheme) GetDimColor() string
- func (t *CharmTheme) GetErrorColor() string
- func (t *CharmTheme) GetStatusColor() string
- func (t *CharmTheme) GetSuccessColor() string
- func (t *CharmTheme) GetUserColor() string
- type ChatChunkEvent
- type ChatCompleteEvent
- type ChatCompletionRunner
- type ChatErrorEvent
- type ChatEvent
- type ChatEventListener
- type ChatHandler
- type ChatMetrics
- type ChatService
- type ChatSession
- type ChatSessionManager
- type ChatStartEvent
- type ChatStatus
- type ChatSyncResponse
- type ClearErrorEvent
- type ClearInputEvent
- type ClickIndicatorEvent
- type CompletionRequestedEvent
- type ComputerUsePauseManager
- type ComputerUsePausedEvent
- type ComputerUseResumedEvent
- type ContainerInfo
- type ContainerRuntime
- type ContextKey
- type ConversationEntry
- type ConversationExporter
- type ConversationLifecycleManager
- type ConversationMetadata
- type ConversationOptimizer
- type ConversationRepository
- type ConversationSelectedEvent
- type ConversationSummary
- type ConversationsLoadedEvent
- type CustomFormatter
- type DebugKeyEvent
- type DeleteToolResult
- type DimensionsManager
- type DirectExecutionService
- type DraculaTheme
- func (t *DraculaTheme) GetAccentColor() string
- func (t *DraculaTheme) GetAssistantColor() string
- func (t *DraculaTheme) GetBorderColor() string
- func (t *DraculaTheme) GetDiffAddColor() string
- func (t *DraculaTheme) GetDiffRemoveColor() string
- func (t *DraculaTheme) GetDimColor() string
- func (t *DraculaTheme) GetErrorColor() string
- func (t *DraculaTheme) GetStatusColor() string
- func (t *DraculaTheme) GetSuccessColor() string
- func (t *DraculaTheme) GetUserColor() string
- type DrainQueueEvent
- type DrainQueueRetryEvent
- type EditOperationResult
- type EditToolResult
- type EventBridge
- type EventBridgeManager
- type ExportFormat
- type FetchResult
- type FileInfo
- type FileReadToolResult
- type FileSelectionManager
- type FileSelectionRequestEvent
- type FileSelectionState
- type FileService
- type FileWriteToolResult
- type FocusManager
- type FocusStatusBarEvent
- type FormatterType
- type GatewayManager
- type GitHubIssue
- type GitHubIssueComment
- type GitHubIssueService
- type GitHubSetupService
- type GitPRResolvedEvent
- type GithubLightTheme
- func (t *GithubLightTheme) GetAccentColor() string
- func (t *GithubLightTheme) GetAssistantColor() string
- func (t *GithubLightTheme) GetBorderColor() string
- func (t *GithubLightTheme) GetDiffAddColor() string
- func (t *GithubLightTheme) GetDiffRemoveColor() string
- func (t *GithubLightTheme) GetDimColor() string
- func (t *GithubLightTheme) GetErrorColor() string
- func (t *GithubLightTheme) GetStatusColor() string
- func (t *GithubLightTheme) GetSuccessColor() string
- func (t *GithubLightTheme) GetUserColor() string
- type HealthCheckConfig
- type HealthStatus
- type HideHelpBarEvent
- type HistoryCleaner
- type HookCommand
- type HookCommandProvider
- type HookPoint
- type ImageAttachment
- type ImageService
- type InboundMessage
- type JobKind
- type JobLivenessReporter
- type JobMeta
- type JobNotifier
- type JobOutputProvider
- type JobSignal
- type JobStatus
- type JobStopper
- type JobSubmitter
- type KeyboardTypeToolResult
- type MCPClient
- type MCPDiscoveredTool
- type MCPManager
- type MCPServerEntry
- type MCPServerStatus
- type MCPServerStatusUpdateEvent
- type MCPToolResult
- type MarkdownRenderer
- type MemoryBackend
- type Message
- type MessageButton
- type MessageEditManager
- type MessageEditState
- type MessageEditSubmitEvent
- type MessageHistoryEditEvent
- type MessageHistoryEditReadyEvent
- type MessageHistoryReadyEvent
- type MessageHistoryRestoreEvent
- type MessageQueue
- type MessageQueuedEvent
- type MessageReceivedEvent
- type MessageRepository
- type MessageSnapshot
- type ModelCostStats
- type ModelSelectedEvent
- type ModelService
- type MouseClickToolResult
- type MouseMoveToolResult
- type MoveIndicatorEvent
- type MultiEditToolResult
- type NavigateBackInTimeEvent
- type NoopUINotifier
- type NotifierFunc
- type OptimizationStatusEvent
- type OutboundMessage
- type OutputRingBuffer
- type PaneObservation
- type PendingToolCallManager
- type PlanApprovalAction
- type PlanApprovalRequestedEvent
- type PlanApprovalResponseEvent
- type PlanApprovalSelectionChangedEvent
- type PlanApprovalStatus
- type PlanApprovalUIManager
- type PlanApprovalUIState
- type PricingService
- type QueuedMessage
- type RateLimiter
- type RefreshAutocompleteEvent
- type ReminderQuery
- type RestoreStatusStateEvent
- type RetryStatus
- type RolloverCompletedEvent
- type RunContainerOptions
- type SaveStatusStateEvent
- type ScheduledJob
- type SchedulerService
- type ScreenRegion
- type Screenshot
- type ScreenshotProvider
- type ScreenshotToolResult
- type ScrollDirection
- type ScrollRequestEvent
- type SessionCostStats
- type SessionID
- type SessionTokenStats
- type SetInputEvent
- type SetStatusEvent
- type SetupFileSelectionEvent
- type ShellCancelledEvent
- type ShellCompletedEvent
- type ShellDetachedEvent
- type ShellFailedEvent
- type ShellInfo
- type ShellState
- type ShellTracker
- type ShowErrorEvent
- type Skill
- type SkillLoadError
- type SkillScope
- type SkillsService
- type StartStreamingEvent
- type StateAction
- type StateContext
- type StateGuard
- type StateHandler
- type StatusProgress
- type StatusType
- type StreamCompletedEvent
- type StreamingContentEvent
- type SubagentApprovalFile
- type SubagentCompletedEvent
- type SubagentFailedEvent
- type SubagentResultFile
- type SubagentState
- type SubagentStatus
- type SubagentSubmittedEvent
- type SubagentTracker
- type SystemReminder
- type SystemReminderProvider
- type TaskCancelledEvent
- type TaskInfo
- type TaskPollingState
- type TaskRetainer
- type TaskRetentionService
- type TasksLoadedEvent
- type Theme
- type ThemeProvider
- func (tp *ThemeProvider) GetCurrentTheme() Theme
- func (tp *ThemeProvider) GetCurrentThemeName() string
- func (tp *ThemeProvider) GetTheme(name string) (Theme, error)
- func (tp *ThemeProvider) ListThemes() []string
- func (tp *ThemeProvider) SetCurrentTheme(name string) error
- func (tp *ThemeProvider) SetTheme(name string) error
- type ThemeSelectedEvent
- type ThemeService
- type TodoItem
- type TodoManager
- type TodoUpdateChatEvent
- type TodoUpdateEvent
- type TodoWriteToolResult
- type ToggleHelpBarEvent
- type ToggleTodoBoxEvent
- type TokenEstimator
- type TokenUsageRepository
- type TokyoNightTheme
- func (t *TokyoNightTheme) GetAccentColor() string
- func (t *TokyoNightTheme) GetAssistantColor() string
- func (t *TokyoNightTheme) GetBorderColor() string
- func (t *TokyoNightTheme) GetDiffAddColor() string
- func (t *TokyoNightTheme) GetDiffRemoveColor() string
- func (t *TokyoNightTheme) GetDimColor() string
- func (t *TokyoNightTheme) GetErrorColor() string
- func (t *TokyoNightTheme) GetStatusColor() string
- func (t *TokyoNightTheme) GetSuccessColor() string
- func (t *TokyoNightTheme) GetUserColor() string
- type Tool
- type ToolApprovalNotificationEvent
- type ToolApprovalRequestedEvent
- type ToolApprovalResponseEvent
- type ToolApprovalStatus
- type ToolCall
- type ToolCallPreviewEvent
- type ToolCallReadyEvent
- type ToolCallStatus
- type ToolCallStreamStatus
- type ToolCallUpdateEvent
- type ToolCancelledEvent
- type ToolExecutionCompletedEvent
- type ToolExecutionCoordinator
- type ToolExecutionManager
- type ToolExecutionProgressEvent
- type ToolExecutionResult
- type ToolExecutionSession
- type ToolExecutionStartedEvent
- type ToolExecutionStatus
- type ToolFormatter
- type ToolResultFormatter
- type ToolService
- type ToolsCompletedEvent
- type TrackedJob
- type TreeToolResult
- type TriggerGithubActionSetupEvent
- type TriggerHelpViewEvent
- type UINotifier
- type UpdateHistoryEvent
- type UpdateStatusEvent
- type UserInputEvent
- type UserQuestion
- type UserQuestionAnswer
- type UserQuestionBroker
- type UserQuestionOption
- type UserQuestionRequestedEvent
- type UserQuestionUIManager
- type UserQuestionUIState
- type VersionInfo
- type ViewManager
- type ViewState
- type WebFetchService
- type WebSearchResponse
- type WebSearchResult
- type WebSearchService
- type WindSignal
Constants ¶
const ( RoleUser = sdk.User RoleAssistant = sdk.Assistant RoleTool = sdk.Tool RoleSystem = sdk.System )
Common role constants
const ( SubagentModeHeadless = "headless" SubagentModeInteractive = "interactive" )
SubagentMode selects how a subagent is surfaced while it runs.
const EnvSubagentAgentMode = "INFER_SUBAGENT_AGENT_MODE"
EnvSubagentAgentMode names the environment variable the Agent tool sets to carry the parent chat's coding mode (the AgentMode.AllowedlistKey form - "standard"/"plan"/"auto") to a spawned subagent, so it starts in the same mode as its parent. It is absent for top-level `infer chat`/`infer agent` runs, which therefore stay Standard-by-default.
const EnvSubagentApprovalFile = "INFER_SUBAGENT_APPROVAL_FILE"
EnvSubagentApprovalFile names the environment variable the Agent tool sets on an interactive subagent's `infer chat` so it writes a SubagentApprovalFile JSON to that path whenever it blocks on a tool-approval prompt (and removes it when the prompt resolves). The parent watches this file to surface "subagent is awaiting approval" to the user and relay the decision (ApproveSubagent). Unset for normal `infer chat`, which writes nothing.
const EnvSubagentHistoryName = "INFER_SUBAGENT_HISTORY_NAME"
EnvSubagentHistoryName names the environment variable the Agent tool sets on an interactive subagent's `infer chat` so it uses its own history file (<configDir>/history/history-<name>) instead of the main agent's history. When unset or empty, the subagent falls back to the main history file; the reserved value SubagentHistoryMemoryOnly selects in-memory-only history.
const EnvSubagentResultFile = "INFER_SUBAGENT_RESULT_FILE"
EnvSubagentResultFile names the environment variable the Agent tool sets on an interactive subagent's `infer chat` so it writes its last assistant message (as a SubagentResultFile JSON) to that path on each completed turn. The parent reads it to deliver the subagent's real answer - not the tmux pane's chrome - when the subagent finishes. Unset for normal `infer chat`, which writes nothing.
const SubagentHistoryMemoryOnly = ":memory:"
SubagentHistoryMemoryOnly is the reserved EnvSubagentHistoryName value telling an interactive subagent to keep its input history in memory only (no file). The Agent tool sets it for subagents without a usable label so they don't create a new single-use history file per spawn. sanitizeSlug never yields this value (it contains ':'), so it can't collide with a real slug.
Variables ¶
var HookPoints = []HookPoint{ HookPreSession, HookPreStream, HookPostStream, HookPreTool, HookPostTool, HookPreQueueDrain, HookPostQueueDrain, HookPostSession, }
HookPoints is the canonical catalog, used for config validation. Order is the loop order (a run flows top to bottom, looping the middle phases).
Functions ¶
func AnyToolFailed ¶ added in v0.129.0
func AnyToolFailed(results []ConversationEntry) bool
AnyToolFailed reports whether any entry in a completed tool batch failed (executed with a non-success result). It backs the post_tool `on_failure` reminder trigger; callers set AgentContext.LastToolFailed from it when a batch completes.
func AnyToolRejected ¶ added in v0.138.0
func AnyToolRejected(results []ConversationEntry) bool
AnyToolRejected reports whether any entry in a completed tool batch was rejected by the user. A rejection ends the agent turn instead of feeding the results back for another LLM response.
func BashAllowModeKey ¶ added in v0.121.0
BashAllowModeKey returns the bash allow-list mode key for the agent mode in ctx, defaulting to "standard" when no mode is set. Convenience for the Bash tool and the approval policy so they resolve the same per-mode allow-list.
func CreateTitleFromMessage ¶ added in v0.46.0
CreateTitleFromMessage creates a short title from message content (fallback title)
func FormatChannelSessionID ¶ added in v0.142.2
FormatChannelSessionID builds the session ID the channels-manager uses for a channel/sender pair, the inverse of ParseChannelSessionID. ponytail: channel names must not contain '-' (they're a fixed enum today; sender IDs may contain dashes and are parsed back as the tail).
func FormatModelPricingLabel ¶ added in v0.118.0
func FormatModelPricingLabel(pricingService PricingService, model string) string
FormatModelPricingLabel builds a human-readable pricing/availability label for a model, combining the per-token price with a subscription marker. A subscription model has no per-token price ($0/$0 → "free"), which would be misleading, so the bare "free" token is replaced by "subscription". A model that is both priced and subscription-gated keeps its price and gains the marker. Returns "" when there is nothing to show (pricing disabled, no entry, and not subscription-gated).
func GetBashDetachChannel ¶ added in v0.97.0
GetBashDetachChannel retrieves the bash detach channel from context Returns nil if the key is not set or if the value is not a channel
func GetSessionID ¶ added in v0.97.0
GetSessionID retrieves the session ID from context Returns empty string if the key is not set or if the value is not a string
func GetToolCallID ¶ added in v0.147.0
GetToolCallID retrieves the tool call id from context
func GetTraceEnv ¶ added in v0.147.0
GetTraceEnv retrieves the subprocess trace environment from context
func HasBashDetachChannel ¶ added in v0.97.0
HasBashDetachChannel checks if a bash detach channel is set in the context
func HasBashOutputCallback ¶ added in v0.97.0
HasBashOutputCallback checks if a bash output callback is set in the context
func HasChatHandler ¶ added in v0.97.0
HasChatHandler checks if a ChatHandler is set in the context
func HasSessionID ¶ added in v0.97.0
HasSessionID checks if a session ID is set in the context
func HasUserQuestionBroker ¶ added in v0.124.0
HasUserQuestionBroker checks if a question broker is set in the context.
func IsDirectExecution ¶ added in v0.97.0
IsDirectExecution checks if the tool was invoked directly by the user Returns false if the key is not set or if the value is not a bool
func IsToolApproved ¶ added in v0.97.0
IsToolApproved checks if the tool was explicitly approved by the user Returns false if the key is not set or if the value is not a bool
func ParseChannelSessionID ¶ added in v0.104.0
ParseChannelSessionID extracts the channel name and recipient ID from a session ID created by the channels-manager. The channel manager builds session IDs as "channel-<name>-<sender_id>" (see channel_manager.go).
Returns ok=false when the session ID does not match this format (e.g. for chat-mode or generic agent sessions). Channel names cannot contain a '-'; recipient IDs may.
func WithAgentMode ¶ added in v0.121.0
WithAgentMode returns a new context carrying the agent mode in effect for a tool execution. The Bash tool reads it (via BashAllowModeKey) to pick the per-mode allow-list that governs the command.
func WithBashDetachChannel ¶ added in v0.97.0
WithBashDetachChannel returns a new context with a bash detach signal channel
func WithBashOutputCallback ¶ added in v0.97.0
func WithBashOutputCallback(ctx context.Context, callback BashOutputCallback) context.Context
WithBashOutputCallback returns a new context with a bash output streaming callback
func WithChatHandler ¶ added in v0.97.0
func WithChatHandler(ctx context.Context, handler BashDetachChannelHolder) context.Context
WithChatHandler returns a new context with a ChatHandler reference
func WithDirectExecution ¶ added in v0.97.0
WithDirectExecution returns a new context with DirectExecutionKey set to true
func WithModel ¶ added in v0.124.0
WithModel returns a new context carrying the model in effect for the current agent turn. The Agent tool reads it so subagents inherit the parent's model.
func WithSessionID ¶ added in v0.97.0
WithSessionID returns a new context with a session ID
func WithToolApproved ¶ added in v0.97.0
WithToolApproved returns a new context with ToolApprovedKey set to true
func WithToolCallID ¶ added in v0.147.0
WithToolCallID returns a new context with the LLM tool call id
func WithTraceEnv ¶ added in v0.147.0
WithTraceEnv returns a new context with the subprocess trace environment
func WithUserQuestionBroker ¶ added in v0.124.0
func WithUserQuestionBroker(ctx context.Context, broker UserQuestionBroker) context.Context
WithUserQuestionBroker returns a new context carrying the interactive question broker used by the AskUserQuestion tool. Injected only on the chat path so headless/no-TTY runs see a nil broker and degrade gracefully.
Types ¶
type A2AAgentService ¶ added in v0.49.0
type A2AAgentService interface {
GetAgentCards(ctx context.Context) ([]*CachedAgentCard, error)
GetConfiguredAgents() []string
}
A2AAgentService manages A2A agent operations
type A2AClearer ¶ added in v0.143.0
type A2AClearer interface {
ClearAllAgents()
}
A2AClearer is the one-method projection of the A2A tracker used by conversation clear/switch to discard the A2A context/task graph. The concrete *utils.A2ATaskTrackerImpl (and the BackgroundTaskRegistry that embeds it) satisfies it; consumers that only clear depend on this instead of the whole tracker.
type A2AStateProvider ¶ added in v0.128.0
type A2AStateProvider interface {
A2APollingState() TaskPollingState
}
A2AStateProvider is an optional BackgroundJob extension implemented by A2A task jobs so the supervisor can surface their live polling state (context/agent/task id and last known remote state) as the single source for the task view and status bar, without the generic JobMeta/TrackedJob carrying A2A-specific fields.
type A2ATaskCompletedEvent ¶ added in v0.49.0
type A2ATaskCompletedEvent struct {
RequestID string
Timestamp time.Time
TaskID string
Result ToolExecutionResult
}
A2ATaskCompletedEvent indicates an A2A task was completed successfully
func (A2ATaskCompletedEvent) GetRequestID ¶ added in v0.49.0
func (e A2ATaskCompletedEvent) GetRequestID() string
func (A2ATaskCompletedEvent) GetTimestamp ¶ added in v0.49.0
func (e A2ATaskCompletedEvent) GetTimestamp() time.Time
type A2ATaskCoordinator ¶ added in v0.112.3
type A2ATaskCoordinator interface {
HandleTaskSubmitted(msg A2ATaskSubmittedEvent) tea.Cmd
HandleTaskCompleted(msg A2ATaskCompletedEvent) tea.Cmd
HandleTaskFailed(msg A2ATaskFailedEvent) tea.Cmd
HandleTaskStatusUpdate(msg A2ATaskStatusUpdateEvent) tea.Cmd
HandleTaskInputRequired(msg A2ATaskInputRequiredEvent) tea.Cmd
HandleToolCallExecuted(msg A2AToolCallExecutedEvent) tea.Cmd
}
A2ATaskCoordinator owns the UI side of A2A (agent-to-agent) task lifecycle events. It translates the six A2A event types into status updates, streaming-content events, and conversation-history refreshes, and keeps the chat session listener pumping. Self-contained - depends only on the conversation repo, task retention, the chat state manager, and a chat event listener.
type A2ATaskFailedEvent ¶ added in v0.53.0
type A2ATaskFailedEvent struct {
RequestID string
Timestamp time.Time
TaskID string
Result ToolExecutionResult
Error string
}
A2ATaskFailedEvent indicates an A2A task failed
func (A2ATaskFailedEvent) GetRequestID ¶ added in v0.53.0
func (e A2ATaskFailedEvent) GetRequestID() string
func (A2ATaskFailedEvent) GetTimestamp ¶ added in v0.53.0
func (e A2ATaskFailedEvent) GetTimestamp() time.Time
type A2ATaskInputRequiredEvent ¶ added in v0.49.0
type A2ATaskInputRequiredEvent struct {
RequestID string
Timestamp time.Time
TaskID string
Message string
Required bool
}
A2ATaskInputRequiredEvent indicates an A2A task requires user input
func (A2ATaskInputRequiredEvent) GetRequestID ¶ added in v0.49.0
func (e A2ATaskInputRequiredEvent) GetRequestID() string
func (A2ATaskInputRequiredEvent) GetTimestamp ¶ added in v0.49.0
func (e A2ATaskInputRequiredEvent) GetTimestamp() time.Time
type A2ATaskStatusUpdateEvent ¶ added in v0.49.0
type A2ATaskStatusUpdateEvent struct {
RequestID string
Timestamp time.Time
TaskID string
AgentURL string
Status string
Progress float64
Message string
}
A2ATaskStatusUpdateEvent indicates an A2A task status update
func (A2ATaskStatusUpdateEvent) GetRequestID ¶ added in v0.49.0
func (e A2ATaskStatusUpdateEvent) GetRequestID() string
func (A2ATaskStatusUpdateEvent) GetTimestamp ¶ added in v0.49.0
func (e A2ATaskStatusUpdateEvent) GetTimestamp() time.Time
type A2ATaskSubmittedEvent ¶ added in v0.49.0
type A2ATaskSubmittedEvent struct {
RequestID string
Timestamp time.Time
TaskID string
AgentName string
AgentURL string
TaskType string
}
A2ATaskSubmittedEvent indicates an A2A task was submitted
func (A2ATaskSubmittedEvent) GetRequestID ¶ added in v0.49.0
func (e A2ATaskSubmittedEvent) GetRequestID() string
func (A2ATaskSubmittedEvent) GetTimestamp ¶ added in v0.49.0
func (e A2ATaskSubmittedEvent) GetTimestamp() time.Time
type A2ATaskTracker ¶ added in v0.101.0
type A2ATaskTracker interface {
// Context management (contexts are server-generated and tracked here).
// Multiple contexts per agent enable multi-tenant/multi-session support.
RegisterContext(agentURL, contextID string)
GetLatestContextForAgent(agentURL string) string
HasContext(contextID string) bool
// Task management (tasks are server-generated and scoped to contexts per A2A spec)
AddTask(contextID, taskID string)
GetLatestTaskForContext(contextID string) string
RemoveTask(taskID string)
// Agent management
ClearAllAgents()
// Polling state management (one polling state per task)
StartPolling(taskID string, state *TaskPollingState)
StopPolling(taskID string)
GetPollingState(taskID string) *TaskPollingState
GetAllPollingTasks() []string
}
A2ATaskTracker handles A2A task ID and context ID tracking within chat sessions. Following A2A spec: supports multi-tenant with multiple contexts per agent. This is one half of the BackgroundTaskRegistry; the other half is ShellTracker (defined in shell.go). Code that only needs the A2A surface can depend on this narrower interface.
type A2AToolCallExecutedEvent ¶ added in v0.48.0
type A2AToolCallExecutedEvent struct {
RequestID string
Timestamp time.Time
ToolCallID string
ToolName string
Arguments string
ExecutedOnGateway bool
TaskID string
}
A2AToolCallExecutedEvent indicates an A2A tool call was executed on the gateway
func (A2AToolCallExecutedEvent) GetRequestID ¶ added in v0.48.0
func (e A2AToolCallExecutedEvent) GetRequestID() string
func (A2AToolCallExecutedEvent) GetTimestamp ¶ added in v0.48.0
func (e A2AToolCallExecutedEvent) GetTimestamp() time.Time
type ActiveToolTracker ¶ added in v0.112.3
ActiveToolTracker tracks which tool call (if any) is currently shown in the UI's progress indicator. Lives behind an interface because both the (current) ChatHandler and the (extracted) ChatCompletionRunner need to touch it, and a future ToolExecutionCoordinator will own the implementation outright.
type AgentContext ¶ added in v0.99.2
type AgentContext struct {
RequestID string
Conversation *[]sdk.Message
MessageQueue MessageQueue
ConversationRepo ConversationRepository
ToolCalls []*sdk.ChatCompletionMessageToolCall
Turns int
MaxTurns int
HasToolResults bool
LastToolFailed bool
ApprovalPolicy ApprovalPolicy
Ctx context.Context
IsChatMode bool
}
AgentContext represents the execution context for the agent state machine
type AgentErrorMessage ¶ added in v0.106.3
type AgentErrorMessage struct {
Type string `json:"type"` // "agent_error"
Message string `json:"message"`
}
AgentErrorMessage is emitted by the agent on stdout when a fatal error occurs before exiting. The channel manager forwards this to the user-facing channel so users aren't left waiting in silence when the agent process fails.
type AgentEvent ¶ added in v0.99.2
type AgentEvent interface {
EventType() string
}
AgentEvent represents an event in the event-driven agent system
type AgentExecutionState ¶ added in v0.99.2
type AgentExecutionState int
AgentExecutionState represents the state of the agent execution loop This is a more granular state than ChatStatus and is used for the state machine
const ( // StateIdle indicates no active work StateIdle AgentExecutionState = iota // StateCheckingQueue indicates examining message queue StateCheckingQueue // StateStreamingLLM indicates waiting for LLM response StateStreamingLLM // StatePostStream indicates after stream, before tool evaluation StatePostStream // StateEvaluatingTools indicates categorizing tool calls StateEvaluatingTools // StateApprovingTools indicates waiting for user approvals (sequential) StateApprovingTools // StateBlockingTools indicates approval is required but no approver is // reachable (approval_behaviour resolves to block), so the gated tool calls // are rejected with a reason instead of being prompted or executed. StateBlockingTools // StateExecutingTools indicates running tools (parallel) StateExecutingTools // StatePostToolExecution indicates after all tools complete StatePostToolExecution // StateCompleting indicates finalizing loop StateCompleting // StateStopped indicates loop terminated StateStopped // StateCancelled indicates user cancelled StateCancelled // StateError indicates error occurred StateError )
func (AgentExecutionState) String ¶ added in v0.99.2
func (s AgentExecutionState) String() string
type AgentManager ¶ added in v0.54.0
type AgentManager interface {
// StartAgents starts all agents configured with run: true
StartAgents(ctx context.Context) error
// StopAgents stops all running agent containers
StopAgents(ctx context.Context) error
// StopAgent stops a specific agent container by name
StopAgent(ctx context.Context, agentName string) error
// IsRunning returns whether any agents are running
IsRunning() bool
// SetStatusCallback sets the callback function for agent status updates
SetStatusCallback(callback func(agentName string, state AgentState, message string, url string, image string))
// SetPullProgressCallback sets the callback function for image pull progress updates
SetPullProgressCallback(callback func(agentName string, done, total int))
}
AgentManager manages the lifecycle of A2A agent containers
type AgentMode ¶ added in v0.56.0
type AgentMode int
AgentMode represents the operational mode of the agent
const ( // AgentModeStandard is the default mode with all configured tools and approval checks AgentModeStandard AgentMode = iota // AgentModePlan is a read-only mode for planning without execution AgentModePlan // AgentModeAutoAccept bypasses all approval checks (YOLO mode) AgentModeAutoAccept // AgentModeReadOnly is an Explore-like capability for subagents: only // read/search tools are offered and approval is bypassed (the toolset is // read-only by construction). It is a subagent capability selected by the // Agent tool's `type` parameter, not a human shift+tab mode. AgentModeReadOnly )
func AgentModeFromContext ¶ added in v0.121.0
AgentModeFromContext returns the agent mode stored in ctx and whether it was present. When absent, callers should default to AgentModeStandard.
func ParseAgentMode ¶ added in v0.124.1
ParseAgentMode is the inverse of AllowedlistKey: it maps a mode key ("standard"/"plan"/"auto") back to an AgentMode. Matching is case-insensitive and tolerant of surrounding whitespace. ok is false for an empty or unrecognized key, in which case callers should keep AgentModeStandard.
func (AgentMode) AllowedlistKey ¶ added in v0.121.0
AllowedlistKey maps the agent mode to the bash allow-list mode key used in config (tools.bash.mode.<key>.allow): AutoAccept -> "auto", Plan -> "plan", Standard (and any unknown) -> "standard".
func (AgentMode) DisplayName ¶ added in v0.56.0
DisplayName returns a user-friendly display name for the mode
type AgentModeManager ¶ added in v0.125.0
type AgentModeManager interface {
GetAgentMode() AgentMode
SetAgentMode(mode AgentMode)
CycleAgentMode() AgentMode
}
AgentModeManager handles agent mode switching
type AgentReadinessManager ¶ added in v0.125.0
type AgentReadinessManager interface {
InitializeAgentReadiness(totalAgents int)
UpdateAgentStatus(name string, state AgentState, message string, url string, image string)
SetAgentError(name string, err error)
GetAgentReadiness() *AgentReadinessState
AreAllAgentsReady() bool
ClearAgentReadiness()
RemoveAgent(name string)
}
AgentReadinessManager handles A2A agent readiness tracking
type AgentReadinessState ¶ added in v0.67.0
type AgentReadinessState struct {
TotalAgents int `json:"total_agents"`
ReadyAgents int `json:"ready_agents"`
Agents map[string]*AgentStatus `json:"agents"`
StartTime time.Time `json:"start_time"`
}
AgentReadinessState represents the current state of A2A agents during startup
type AgentRequest ¶ added in v0.36.0
type AgentRequest struct {
RequestID string `json:"request_id"`
Model string `json:"model"`
Messages []sdk.Message `json:"messages"`
IsChatMode bool `json:"is_chat_mode"`
}
AgentRequest represents a request to the agent service
type AgentService ¶ added in v0.36.0
type AgentService interface {
// Run executes an agent task synchronously (for background/batch processing)
Run(ctx context.Context, req *AgentRequest) (*ChatSyncResponse, error)
// RunWithStream executes an agent task with streaming (for interactive chat)
RunWithStream(ctx context.Context, req *AgentRequest) (<-chan ChatEvent, error)
// CancelRequest cancels an active request
CancelRequest(requestID string) error
// GetMetrics returns metrics for a completed request
GetMetrics(requestID string) *ChatMetrics
// BuildSystemPrompt returns the static system prompt sent as message[0],
// byte-stable across turns; volatile context travels separately as a hidden
// per-request message (see `infer debug agent system_prompt`).
BuildSystemPrompt() string
// SetReasoningEffort updates the reasoning effort applied to subsequent
// requests. An empty string resets to the provider default.
SetReasoningEffort(effort string) error
// GetReasoningEffort returns the effort level currently applied to
// requests ("" = provider default).
GetReasoningEffort() string
}
AgentService handles agent operations with both sync and streaming modes
type AgentState ¶ added in v0.67.0
type AgentState int
AgentState represents the current state of an agent
const ( AgentStateUnknown AgentState = iota AgentStatePullingImage AgentStateStarting AgentStateWaitingReady AgentStateReady AgentStateFailed )
func (AgentState) DisplayName ¶ added in v0.67.0
func (a AgentState) DisplayName() string
DisplayName returns a user-friendly display name for the agent state
func (AgentState) String ¶ added in v0.67.0
func (a AgentState) String() string
type AgentStateMachine ¶ added in v0.99.2
type AgentStateMachine interface {
// Transition attempts to transition to the target state
Transition(ctx *AgentContext, targetState AgentExecutionState) error
// GetCurrentState returns the current state (thread-safe)
GetCurrentState() AgentExecutionState
// GetPreviousState returns the previous state (thread-safe)
GetPreviousState() AgentExecutionState
// CanTransition checks if a transition is valid without executing it
CanTransition(ctx *AgentContext, targetState AgentExecutionState) bool
// GetValidTransitions returns all valid transitions from current state
GetValidTransitions(ctx *AgentContext) []AgentExecutionState
// Reset resets the state machine to idle
Reset()
}
AgentStateMachine manages agent execution state transitions
type AgentStatus ¶ added in v0.67.0
type AgentStatus struct {
Name string `json:"name"`
URL string `json:"url"`
Image string `json:"image"`
State AgentState `json:"state"`
Message string `json:"message,omitempty"`
StartTime time.Time `json:"start_time"`
ReadyTime *time.Time `json:"ready_time,omitempty"`
Error string `json:"error,omitempty"`
LayersDone int `json:"layers_done,omitempty"`
LayersTotal int `json:"layers_total,omitempty"`
}
AgentStatus represents the status of an individual A2A agent
type AgentStatusUpdateEvent ¶ added in v0.67.0
type AgentStatusUpdateEvent struct {
AgentName string
State AgentState
Message string
URL string
Image string
}
AgentStatusUpdateEvent indicates an agent's status has changed
type AllToolsProcessedEvent ¶ added in v0.99.2
type AllToolsProcessedEvent struct{}
AllToolsProcessedEvent is triggered when all tools have been processed
func (AllToolsProcessedEvent) EventType ¶ added in v0.99.2
func (e AllToolsProcessedEvent) EventType() string
type ApplicationState ¶ added in v0.27.0
type ApplicationState struct {
// contains filtered or unexported fields
}
ApplicationState represents the overall application state with proper typing
func NewApplicationState ¶ added in v0.27.0
func NewApplicationState() *ApplicationState
NewApplicationState creates a new application state
func (*ApplicationState) AddQueuedMessage ¶ added in v0.53.0
func (s *ApplicationState) AddQueuedMessage(message sdk.Message, requestID string)
AddQueuedMessage adds a message to the input queue
func (*ApplicationState) AreAllAgentsReady ¶ added in v0.67.0
func (s *ApplicationState) AreAllAgentsReady() bool
AreAllAgentsReady returns true if all agents are ready
func (*ApplicationState) ClearAgentReadiness ¶ added in v0.67.0
func (s *ApplicationState) ClearAgentReadiness()
ClearAgentReadiness clears the agent readiness state
func (*ApplicationState) ClearApprovalUIState ¶ added in v0.27.0
func (s *ApplicationState) ClearApprovalUIState()
ClearApprovalUIState clears the approval UI state
func (*ApplicationState) ClearComputerUsePauseState ¶ added in v0.96.0
func (s *ApplicationState) ClearComputerUsePauseState()
ClearComputerUsePauseState clears the pause state
func (*ApplicationState) ClearFileSelectionState ¶ added in v0.27.0
func (s *ApplicationState) ClearFileSelectionState()
ClearFileSelectionState clears the file selection state
func (*ApplicationState) ClearLastClickCoordinates ¶ added in v0.96.0
func (s *ApplicationState) ClearLastClickCoordinates()
ClearLastClickCoordinates clears the stored click coordinates
func (*ApplicationState) ClearLastFocusedApp ¶ added in v0.96.0
func (s *ApplicationState) ClearLastFocusedApp()
ClearLastFocusedApp clears the stored focused app
func (*ApplicationState) ClearMessageEditState ¶ added in v0.92.0
func (s *ApplicationState) ClearMessageEditState()
ClearMessageEditState clears the message edit state
func (*ApplicationState) ClearPlanApprovalUIState ¶ added in v0.68.0
func (s *ApplicationState) ClearPlanApprovalUIState()
ClearPlanApprovalUIState clears the plan approval UI state
func (*ApplicationState) ClearQueuedMessages ¶ added in v0.53.0
func (s *ApplicationState) ClearQueuedMessages()
ClearQueuedMessages clears all queued messages
func (*ApplicationState) ClearUserQuestionUIState ¶ added in v0.124.0
func (s *ApplicationState) ClearUserQuestionUIState()
ClearUserQuestionUIState clears the AskUserQuestion form state and closes the response channel (without a prior send this signals cancellation to the blocked tool). Nil-safe and idempotent.
func (*ApplicationState) CompleteCurrentTool ¶ added in v0.27.0
func (s *ApplicationState) CompleteCurrentTool(result *ToolExecutionResult) error
CompleteCurrentTool marks the current tool as completed and moves to next
func (*ApplicationState) CycleAgentMode ¶ added in v0.56.0
func (s *ApplicationState) CycleAgentMode() AgentMode
CycleAgentMode cycles to the next agent mode. The human shift+tab cycle is deliberately three-way (Standard -> Plan -> AutoAccept); AgentModeReadOnly is a subagent-only capability set by the Agent tool's `type` parameter, not a mode a user can toggle their own chat into.
func (*ApplicationState) EndChatSession ¶ added in v0.27.0
func (s *ApplicationState) EndChatSession()
EndChatSession cleans up the chat session
func (*ApplicationState) EndToolExecution ¶ added in v0.27.0
func (s *ApplicationState) EndToolExecution()
EndToolExecution cleans up the tool execution session
func (*ApplicationState) FailCurrentTool ¶ added in v0.27.0
func (s *ApplicationState) FailCurrentTool(result *ToolExecutionResult) error
FailCurrentTool marks the current tool as failed and moves to next
func (*ApplicationState) GetAgentMode ¶ added in v0.56.0
func (s *ApplicationState) GetAgentMode() AgentMode
GetAgentMode returns the current agent mode
func (*ApplicationState) GetAgentReadiness ¶ added in v0.67.0
func (s *ApplicationState) GetAgentReadiness() *AgentReadinessState
GetAgentReadiness returns the current agent readiness state
func (*ApplicationState) GetApprovalUIState ¶ added in v0.27.0
func (s *ApplicationState) GetApprovalUIState() *ApprovalUIState
GetApprovalUIState returns the current approval UI state
func (*ApplicationState) GetChatSession ¶ added in v0.27.0
func (s *ApplicationState) GetChatSession() *ChatSession
GetChatSession returns the current chat session
func (*ApplicationState) GetCurrentView ¶ added in v0.27.0
func (s *ApplicationState) GetCurrentView() ViewState
GetCurrentView returns the current view state
func (*ApplicationState) GetDimensions ¶ added in v0.27.0
func (s *ApplicationState) GetDimensions() (int, int)
GetDimensions returns the current UI dimensions
func (*ApplicationState) GetFileSelectionState ¶ added in v0.27.0
func (s *ApplicationState) GetFileSelectionState() *FileSelectionState
GetFileSelectionState returns the current file selection state
func (*ApplicationState) GetLastClickCoordinates ¶ added in v0.96.0
func (s *ApplicationState) GetLastClickCoordinates() (x, y int)
GetLastClickCoordinates returns the coordinates of the last click
func (*ApplicationState) GetLastFocusedApp ¶ added in v0.96.0
func (s *ApplicationState) GetLastFocusedApp() string
GetLastFocusedApp returns the bundle ID of the last focused application
func (*ApplicationState) GetMessageEditState ¶ added in v0.92.0
func (s *ApplicationState) GetMessageEditState() *MessageEditState
GetMessageEditState returns the current message edit state
func (*ApplicationState) GetPausedRequestID ¶ added in v0.96.0
func (s *ApplicationState) GetPausedRequestID() string
GetPausedRequestID returns the request ID of the paused execution
func (*ApplicationState) GetPlanApprovalUIState ¶ added in v0.68.0
func (s *ApplicationState) GetPlanApprovalUIState() *PlanApprovalUIState
GetPlanApprovalUIState returns the current plan approval UI state
func (*ApplicationState) GetPreviousView ¶ added in v0.86.0
func (s *ApplicationState) GetPreviousView() ViewState
GetPreviousView returns the previous view state
func (*ApplicationState) GetQueuedMessages ¶ added in v0.53.0
func (s *ApplicationState) GetQueuedMessages() []QueuedMessage
GetQueuedMessages returns the current queued messages
func (*ApplicationState) GetRetryStatus ¶ added in v0.142.0
func (s *ApplicationState) GetRetryStatus() *RetryStatus
GetRetryStatus returns a copy of the current retry status, or nil when no retry is in progress. Returning a copy keeps callers from sharing the mutable pointer with the agent's streaming goroutine.
func (*ApplicationState) GetTodos ¶ added in v0.63.1
func (s *ApplicationState) GetTodos() []TodoItem
GetTodos returns the current todo list
func (*ApplicationState) GetToolExecution ¶ added in v0.27.0
func (s *ApplicationState) GetToolExecution() *ToolExecutionSession
GetToolExecution returns the current tool execution session
func (*ApplicationState) GetUserQuestionUIState ¶ added in v0.124.0
func (s *ApplicationState) GetUserQuestionUIState() *UserQuestionUIState
GetUserQuestionUIState returns the current AskUserQuestion form state, or nil.
func (*ApplicationState) InitializeAgentReadiness ¶ added in v0.67.0
func (s *ApplicationState) InitializeAgentReadiness(totalAgents int)
InitializeAgentReadiness initializes the agent readiness tracking
func (*ApplicationState) IsComputerUsePaused ¶ added in v0.96.0
func (s *ApplicationState) IsComputerUsePaused() bool
IsComputerUsePaused returns whether computer use is currently paused
func (*ApplicationState) IsDebugMode ¶ added in v0.27.0
func (s *ApplicationState) IsDebugMode() bool
IsDebugMode returns whether debug mode is enabled
func (*ApplicationState) IsEditingMessage ¶ added in v0.92.0
func (s *ApplicationState) IsEditingMessage() bool
IsEditingMessage returns true if currently editing a message
func (*ApplicationState) PopQueuedMessage ¶ added in v0.53.0
func (s *ApplicationState) PopQueuedMessage() *QueuedMessage
PopQueuedMessage removes and returns the first message from the queue (FIFO)
func (*ApplicationState) RemoveAgent ¶ added in v0.67.0
func (s *ApplicationState) RemoveAgent(name string)
RemoveAgent removes an agent from the readiness tracking
func (*ApplicationState) SetAgentError ¶ added in v0.67.0
func (s *ApplicationState) SetAgentError(name string, err error)
SetAgentError sets an error for a specific agent
func (*ApplicationState) SetAgentMode ¶ added in v0.56.0
func (s *ApplicationState) SetAgentMode(mode AgentMode)
SetAgentMode sets the agent mode
func (*ApplicationState) SetChatPending ¶ added in v0.63.1
func (s *ApplicationState) SetChatPending()
SetChatPending creates a minimal chat session to mark the agent as busy before the actual chat starts. This prevents race conditions.
func (*ApplicationState) SetComputerUsePaused ¶ added in v0.96.0
func (s *ApplicationState) SetComputerUsePaused(paused bool, requestID string)
SetComputerUsePaused sets the paused state for computer use
func (*ApplicationState) SetDebugMode ¶ added in v0.27.0
func (s *ApplicationState) SetDebugMode(enabled bool)
SetDebugMode enables or disables debug mode
func (*ApplicationState) SetDimensions ¶ added in v0.27.0
func (s *ApplicationState) SetDimensions(width, height int)
SetDimensions updates the UI dimensions
func (*ApplicationState) SetFileSelectedIndex ¶ added in v0.27.0
func (s *ApplicationState) SetFileSelectedIndex(index int)
SetFileSelectedIndex sets the selected file index
func (*ApplicationState) SetLastClickCoordinates ¶ added in v0.96.0
func (s *ApplicationState) SetLastClickCoordinates(x, y int)
SetLastClickCoordinates stores the coordinates of the last click
func (*ApplicationState) SetLastFocusedApp ¶ added in v0.96.0
func (s *ApplicationState) SetLastFocusedApp(appID string)
SetLastFocusedApp stores the bundle ID of the last focused application This is used to restore focus before keyboard operations
func (*ApplicationState) SetMessageEditState ¶ added in v0.92.0
func (s *ApplicationState) SetMessageEditState(state *MessageEditState)
SetMessageEditState sets the message edit state
func (*ApplicationState) SetPlanApprovalSelectedIndex ¶ added in v0.68.0
func (s *ApplicationState) SetPlanApprovalSelectedIndex(index int)
SetPlanApprovalSelectedIndex sets the plan approval selection index
func (*ApplicationState) SetRetryStatus ¶ added in v0.142.0
func (s *ApplicationState) SetRetryStatus(status *RetryStatus)
SetRetryStatus updates the retry status on the current chat session
func (*ApplicationState) SetTodos ¶ added in v0.63.1
func (s *ApplicationState) SetTodos(todos []TodoItem)
SetTodos sets the todo list
func (*ApplicationState) SetupApprovalUIState ¶ added in v0.56.0
func (s *ApplicationState) SetupApprovalUIState(toolCall *sdk.ChatCompletionMessageToolCall, responseChan chan ApprovalAction)
SetupApprovalUIState initializes approval UI state with the pending tool call
func (*ApplicationState) SetupFileSelection ¶ added in v0.27.0
func (s *ApplicationState) SetupFileSelection(files []string)
SetupFileSelection initializes file selection state
func (*ApplicationState) SetupPlanApprovalUIState ¶ added in v0.68.0
func (s *ApplicationState) SetupPlanApprovalUIState(planContent, planID string, responseChan chan PlanApprovalAction)
SetupPlanApprovalUIState initializes plan approval UI state
func (*ApplicationState) SetupUserQuestionUIState ¶ added in v0.124.0
func (s *ApplicationState) SetupUserQuestionUIState(questions []UserQuestion, responseChan chan []UserQuestionAnswer)
SetupUserQuestionUIState initializes the AskUserQuestion form state for the given questions.
func (*ApplicationState) StartChatSession ¶ added in v0.27.0
func (s *ApplicationState) StartChatSession(requestID, model string, eventChan <-chan ChatEvent)
StartChatSession initializes a new chat session
func (*ApplicationState) StartToolExecution ¶ added in v0.27.0
func (s *ApplicationState) StartToolExecution(tools []ToolCall)
StartToolExecution initializes a new tool execution session
func (*ApplicationState) TouchChatActivity ¶ added in v0.142.0
func (s *ApplicationState) TouchChatActivity()
TouchChatActivity records that the stream produced output: it bumps the session's LastActivity and clears any retry status, since receiving a chunk means the connection is healthy again.
func (*ApplicationState) TransitionToView ¶ added in v0.27.0
func (s *ApplicationState) TransitionToView(newView ViewState) error
TransitionToView changes the current view with validation
func (*ApplicationState) UpdateAgentPullProgress ¶ added in v0.149.0
func (s *ApplicationState) UpdateAgentPullProgress(name string, done, total int)
UpdateAgentPullProgress updates the image pull layer counts for a specific agent
func (*ApplicationState) UpdateAgentStatus ¶ added in v0.67.0
func (s *ApplicationState) UpdateAgentStatus(name string, state AgentState, message string, url string, image string)
UpdateAgentStatus updates the status of a specific agent
func (*ApplicationState) UpdateChatStatus ¶ added in v0.27.0
func (s *ApplicationState) UpdateChatStatus(status ChatStatus) error
UpdateChatStatus updates the chat session status
func (*ApplicationState) UpdateFileSearchQuery ¶ added in v0.27.0
func (s *ApplicationState) UpdateFileSearchQuery(query string)
UpdateFileSearchQuery updates the file search query
type ApprovalAction ¶
type ApprovalAction int
ApprovalAction represents the user's choice for tool approval
const ( ApprovalApprove ApprovalAction = iota ApprovalReject ApprovalAutoAccept )
func (ApprovalAction) String ¶ added in v0.27.0
func (a ApprovalAction) String() string
type ApprovalChannel ¶ added in v0.103.0
type ApprovalChannel interface {
SendApproval(ctx context.Context, recipientID string, req *ApprovalRequest) error
}
ApprovalChannel is an optional interface that channels can implement to provide rich approval UIs (e.g., inline keyboard buttons) instead of text-based prompts.
type ApprovalCoordinator ¶ added in v0.112.3
type ApprovalCoordinator interface {
HandlePlanApprovalRequested(msg PlanApprovalRequestedEvent) tea.Cmd
HandlePlanApprovalResponse(msg PlanApprovalResponseEvent) (cmd tea.Cmd, restart bool)
HandleUserQuestionRequested(msg UserQuestionRequestedEvent) tea.Cmd
HandleComputerUsePaused(msg ComputerUsePausedEvent) tea.Cmd
HandleComputerUseResumed(msg ComputerUseResumedEvent) (cmd tea.Cmd, restart bool)
}
ApprovalCoordinator owns the "pause the assistant turn pending external decision" family of events: plan approval (the agent stops, presents a plan, awaits user accept/reject) and computer-use pause/resume (the user hits a key to interrupt computer-use execution and later resumes).
Response handlers return a restart bool so the orchestrator can fire ChatCompletionRunner.Start() after the cmds without ApprovalCoordinator having to depend on the runner.
type ApprovalFailedEvent ¶ added in v0.99.2
type ApprovalFailedEvent struct {
Error error
}
ApprovalFailedEvent is triggered when approval fails
func (ApprovalFailedEvent) EventType ¶ added in v0.99.2
func (e ApprovalFailedEvent) EventType() string
type ApprovalPolicy ¶ added in v0.97.0
type ApprovalPolicy interface {
// ShouldRequireApproval returns true if the tool execution requires user approval
// ctx: context for the approval decision
// toolCall: the tool being invoked with its arguments
// isChatMode: whether execution is in interactive chat mode
ShouldRequireApproval(ctx context.Context, toolCall *sdk.ChatCompletionMessageToolCall, isChatMode bool) bool
}
ApprovalPolicy determines whether a tool execution requires user approval This interface allows for different approval strategies (standard, permissive, strict, etc.) Implementations define the business rules for when user approval is required before executing potentially dangerous or state-changing operations.
type ApprovalRequest ¶ added in v0.102.0
type ApprovalRequest struct {
Type string `json:"type"` // "approval_request"
ToolName string `json:"tool_name"`
ToolArgs string `json:"tool_args"`
ToolCallID string `json:"tool_call_id"`
}
ApprovalRequest is emitted by the agent on stdout when a tool needs user approval. The channel manager detects this JSON line, prompts the user, and writes an ApprovalResponse to stdin.
type ApprovalResponse ¶ added in v0.102.0
type ApprovalResponse struct {
Type string `json:"type"` // "approval_response"
ToolCallID string `json:"tool_call_id"`
Approved bool `json:"approved"`
}
ApprovalResponse is written to the agent's stdin by the channel manager after user decision.
type ApprovalUIManager ¶ added in v0.125.0
type ApprovalUIManager interface {
SetupApprovalUIState(toolCall *sdk.ChatCompletionMessageToolCall, responseChan chan ApprovalAction)
GetApprovalUIState() *ApprovalUIState
ClearApprovalUIState()
}
ApprovalUIManager handles tool approval UI state
type ApprovalUIState ¶ added in v0.27.0
type ApprovalUIState struct {
PendingToolCall *sdk.ChatCompletionMessageToolCall `json:"pending_tool_call"`
ResponseChan chan ApprovalAction `json:"-"`
}
ApprovalUIState represents the state of approval UI
type AutocompleteCompleteEvent ¶ added in v0.76.5
AutocompleteCompleteEvent is fired when a completion is selected
type AutocompleteHideEvent ¶ added in v0.76.5
type AutocompleteHideEvent struct{}
AutocompleteHideEvent is fired when autocomplete should be hidden
type AutocompleteUpdateEvent ¶ added in v0.76.5
AutocompleteUpdateEvent is fired when input text changes and autocomplete should update
type BackgroundJob ¶ added in v0.126.0
type BackgroundJob interface {
// Meta returns the job's identity/display snapshot.
Meta() JobMeta
// Run blocks until the job reaches a terminal state or ctx is cancelled,
// emitting intermediate JobSignals via emit, and returns the terminal result.
// It MUST return promptly once ctx is cancelled.
Run(ctx context.Context, emit func(JobSignal)) ToolExecutionResult
// Wind delivers a graceful wind-down (WindWrapUp) or hard stop (WindStop) to a
// RUNNING job. It must be safe to call from another goroutine while Run is in
// flight, be idempotent, and a no-op once the job has finished.
Wind(ctx context.Context, sig WindSignal) error
// Close tears down the resources the job owns (its per-kind tracker record, an
// interactive subagent's tmux pane and temp files, ...). The supervisor calls
// it exactly once when it reaps a finished job after the retention window. It
// must be idempotent and must not touch the running process (use Wind for that).
Close()
}
BackgroundJob is one unit of monitorable background work. The supervisor owns the single goroutine that calls Run plus all the lifecycle around it (events, queue notification, tracking, cleanup); a job only has to (a) block until it reaches a terminal state and return the outcome, and (b) honour wind-down/stop signals. This is the seam that lets A2A tasks, shells, and subagents share one fan-in implementation - each kind differs only in how it learns it is done.
type BackgroundShell ¶ added in v0.81.0
type BackgroundShell struct {
ShellID string
Command string
Cmd *exec.Cmd
StartedAt time.Time
CompletedAt *time.Time
State ShellState
ExitCode *int
OutputBuffer OutputRingBuffer
CancelFunc context.CancelFunc
ReadOffset int64
ReadersDone <-chan struct{}
}
BackgroundShell represents a command running in the background.
type BackgroundShellRequestEvent ¶ added in v0.81.0
type BackgroundShellRequestEvent struct{}
BackgroundShellRequestEvent requests that the current running Bash command be moved to background
type BackgroundShellService ¶ added in v0.81.0
type BackgroundShellService interface {
// DetachToBackground moves a running command to background. readersDone, when
// non-nil, is closed once the caller's pipe readers reach EOF; the supervisor
// waits on it before reaping so trailing output is not truncated.
DetachToBackground(ctx context.Context, cmd *exec.Cmd, command string, outputBuffer OutputRingBuffer, readersDone <-chan struct{}) (string, error)
// GetShellOutput retrieves output from a shell
GetShellOutput(shellID string, fromOffset int64) (string, int64, ShellState, error)
// GetShellOutputWithFilter retrieves filtered output from a shell
GetShellOutputWithFilter(shellID string, fromOffset int64, filterPattern string) (string, int64, ShellState, error)
// GetShell returns a specific shell by ID
GetShell(shellID string) *BackgroundShell
// GetAllShells returns all tracked shells
GetAllShells() []*BackgroundShell
// CancelShell cancels a running background shell
CancelShell(shellID string) error
// RemoveShell removes a shell from tracking
RemoveShell(shellID string) error
}
BackgroundShellService defines the interface for managing background shells
type BackgroundTaskRegistry ¶ added in v0.101.0
type BackgroundTaskRegistry interface {
A2ATaskTracker
ShellTracker
SubagentTracker
// HasPending reports whether *any* background work is still in flight,
// regardless of type. True when there is at least one A2A task being
// polled, one running background shell, OR one running HEADLESS subagent.
// It deliberately excludes interactive subagents so a one-shot `infer agent`
// does not hang at exit waiting on a user-driven tmux pane.
HasPending() bool
// Submit hands a background job to the supervisor, which spawns its monitor
// goroutine and folds its result back onto the conversation when it finishes.
// This is the single entry point every kind (A2A task, shell, subagent) uses
// instead of running its own poller.
Submit(job BackgroundJob)
// Snapshot returns the supervisor's view of all live and recently-finished
// jobs for the task view and status line.
Snapshot() []TrackedJob
// CountRunningJobs returns how many supervised jobs are running, optionally
// filtered to one kind (pass "" for all kinds).
CountRunningJobs(kind JobKind) int
// IsJobRunning reports whether the supervised job with the given id is still
// running. It is the per-id liveness query a tool uses (via the narrow
// JobLivenessReporter projection) to defer to the supervisor - the single
// source of truth - instead of racing it with a manual read.
IsJobRunning(id string) bool
// WindJob sends a graceful wind-down or hard stop to one supervised job.
WindJob(id string, sig WindSignal) error
}
BackgroundTaskRegistry is the single tracker that owns *all* in-flight background work an agent session can produce: A2A tasks (long-running work delegated to remote agents) and background bash shells (long-running commands the agent has detached from the foreground). Both are conceptually the same thing - async producers of results that need to land back on the conversation when they finish - so they live behind one type here.
The interface unifies what used to be two separate trackers (A2ATaskTracker and ShellTracker) via composition: depending on what a caller needs, it can use the narrower A2ATaskTracker or ShellTracker interface, or this full BackgroundTaskRegistry to access both plus the HasPending() aggregator method.
type BackgroundTaskService ¶ added in v0.53.3
type BackgroundTaskService interface {
// GetBackgroundTasks returns all current background polling tasks
GetBackgroundTasks() []TaskPollingState
// CancelBackgroundTask cancels a background task by task ID
CancelBackgroundTask(taskID string) error
}
BackgroundTaskService handles background A2A task operations Only enabled when A2A is enabled - provides task cancellation and retrieval
type BackgroundTasksChangedEvent ¶ added in v0.126.0
type BackgroundTasksChangedEvent struct{}
BackgroundTasksChangedEvent signals that a background job's status changed (submitted, signalled, completed, or failed). The supervisor pushes it so the /tasks view and the inline conversation rows refresh on real change instead of polling at render time.
type BaseChatEvent ¶ added in v0.49.0
BaseChatEvent provides common implementation for ChatEvent interface
func (BaseChatEvent) GetRequestID ¶ added in v0.49.0
func (e BaseChatEvent) GetRequestID() string
func (BaseChatEvent) GetTimestamp ¶ added in v0.49.0
func (e BaseChatEvent) GetTimestamp() time.Time
type BaseFormatter ¶ added in v0.33.4
type BaseFormatter struct {
// contains filtered or unexported fields
}
BaseFormatter provides common formatting functionality that tools can embed
func NewBaseFormatter ¶ added in v0.33.4
func NewBaseFormatter(toolName string) BaseFormatter
NewBaseFormatter creates a new base formatter for a tool
func (BaseFormatter) FormatAsJSON ¶ added in v0.33.4
func (f BaseFormatter) FormatAsJSON(data any) string
FormatAsJSON formats data as JSON if possible, falls back to string representation
func (BaseFormatter) FormatDuration ¶ added in v0.33.4
func (f BaseFormatter) FormatDuration(result *ToolExecutionResult) string
FormatDuration formats a duration for display in a human-friendly way
func (BaseFormatter) FormatExpanded ¶ added in v0.143.0
func (f BaseFormatter) FormatExpanded(result *ToolExecutionResult, dataContent string) string
FormatExpanded renders the full expanded result as a single native lipgloss/tree, replacing the hand-drawn ├─/└─ connectors that used to live across three methods. dataContent is the tool-specific result body (may be ""). Output is plain: the UI wraps and themes it (services.themeTreeLines); LLM / headless consume it as-is.
func (BaseFormatter) FormatStatus ¶ added in v0.33.4
func (f BaseFormatter) FormatStatus(success bool) string
FormatStatus returns a formatted status with icon
func (BaseFormatter) FormatStatusIcon ¶ added in v0.33.4
func (f BaseFormatter) FormatStatusIcon(success bool) string
FormatStatusIcon returns just the status icon
func (BaseFormatter) FormatToolCall ¶ added in v0.33.4
func (f BaseFormatter) FormatToolCall(args map[string]any, expanded bool) string
FormatToolCall formats a tool call for consistent display
func (BaseFormatter) GetDomainFromURL ¶ added in v0.33.4
func (f BaseFormatter) GetDomainFromURL(url string) string
GetDomainFromURL extracts domain from URL
func (BaseFormatter) GetFileName ¶ added in v0.33.4
func (f BaseFormatter) GetFileName(path string) string
GetFileName extracts filename from a path
func (BaseFormatter) ShouldCollapseArg ¶ added in v0.33.4
func (f BaseFormatter) ShouldCollapseArg(key string) bool
ShouldCollapseArg provides default collapse behavior (can be overridden by tools)
func (BaseFormatter) TruncateText ¶ added in v0.33.4
func (f BaseFormatter) TruncateText(text string, maxLength int) string
TruncateText truncates text to specified length with ellipsis
type BashCommandCompletedEvent ¶ added in v0.65.0
type BashCommandCompletedEvent struct {
History []ConversationEntry
Failed bool
UserInitiated bool
ErrorMessage string
}
BashCommandCompletedEvent indicates a direct bash command (! prefix) has completed
type BashDetachChannelHolder ¶ added in v0.81.0
type BashDetachChannelHolder interface {
SetBashDetachChan(chan<- struct{})
GetBashDetachChan() chan<- struct{}
ClearBashDetachChan()
}
BashDetachChannelHolder manages the bash detach channel for background shell operations
func GetChatHandler ¶ added in v0.97.0
func GetChatHandler(ctx context.Context) BashDetachChannelHolder
GetChatHandler retrieves the ChatHandler from context Returns nil if the key is not set or if the value is not a BashDetachChannelHolder
type BashOutputCallback ¶ added in v0.65.0
type BashOutputCallback func(output string)
BashOutputCallback receives streaming bash output. Output is coalesced before delivery, so a single invocation may carry several newline-joined lines (the argument never has a trailing newline). This keeps the number of callbacks bounded for high-volume commands; the full command output is captured separately by the tool and is unaffected.
func GetBashOutputCallback ¶ added in v0.97.0
func GetBashOutputCallback(ctx context.Context) BashOutputCallback
GetBashOutputCallback retrieves the bash output callback from context Returns nil if the key is not set or if the value is not a BashOutputCallback
type BashOutputChunkEvent ¶ added in v0.65.0
type BashOutputChunkEvent struct {
BaseChatEvent
ToolCallID string
Output string
IsComplete bool
}
BashOutputChunkEvent indicates a new chunk of bash output is available
type BashToolResult ¶ added in v0.13.1
type BashToolResult struct {
Command string `json:"command"`
Output string `json:"output"`
Error string `json:"error,omitempty"`
ExitCode int `json:"exit_code"`
Duration string `json:"duration"`
}
BashToolResult represents the result of a bash command execution
type BorderOverlayEvent ¶ added in v0.96.0
type BorderOverlayEvent struct {
BaseChatEvent
BorderAction string
}
BorderOverlayEvent indicates the screen border overlay should be shown or hidden
type CachedAgentCard ¶ added in v0.49.0
type CachedAgentCard struct {
Card *adk.AgentCard `json:"card"`
URL string `json:"url"`
FetchedAt time.Time `json:"fetched_at"`
}
CachedAgentCard represents a cached agent card with metadata
type Channel ¶ added in v0.101.0
type Channel interface {
// Name returns the channel identifier (e.g., "whatsapp", "telegram")
Name() string
// Start begins listening for inbound messages. Blocks until ctx is cancelled.
Start(ctx context.Context, inbox chan<- InboundMessage) error
// Send delivers an outbound message through this channel
Send(ctx context.Context, msg OutboundMessage) error
// Stop gracefully shuts down the channel
Stop() error
}
Channel represents a pluggable messaging transport (WhatsApp, Telegram, etc.)
type ChannelCommand ¶ added in v0.149.0
ChannelCommand describes a slash command a channel may advertise natively (e.g., Telegram's bot command menu).
type CharmTheme ¶ added in v0.118.0
type CharmTheme struct{}
CharmTheme is built on the official Charm palette (charmtone). It's the modern, on-brand option that uses the same semantic tokens Crush ships with - Sapphire as the primary blue, Cherry for errors, Julep for success, Smoke/Iron as neutrals over a Pepper base.
func NewCharmTheme ¶ added in v0.118.0
func NewCharmTheme() *CharmTheme
func (*CharmTheme) GetAccentColor ¶ added in v0.118.0
func (t *CharmTheme) GetAccentColor() string
func (*CharmTheme) GetAssistantColor ¶ added in v0.118.0
func (t *CharmTheme) GetAssistantColor() string
func (*CharmTheme) GetBorderColor ¶ added in v0.118.0
func (t *CharmTheme) GetBorderColor() string
func (*CharmTheme) GetDiffAddColor ¶ added in v0.118.0
func (t *CharmTheme) GetDiffAddColor() string
func (*CharmTheme) GetDiffRemoveColor ¶ added in v0.118.0
func (t *CharmTheme) GetDiffRemoveColor() string
func (*CharmTheme) GetDimColor ¶ added in v0.118.0
func (t *CharmTheme) GetDimColor() string
func (*CharmTheme) GetErrorColor ¶ added in v0.118.0
func (t *CharmTheme) GetErrorColor() string
func (*CharmTheme) GetStatusColor ¶ added in v0.118.0
func (t *CharmTheme) GetStatusColor() string
func (*CharmTheme) GetSuccessColor ¶ added in v0.118.0
func (t *CharmTheme) GetSuccessColor() string
func (*CharmTheme) GetUserColor ¶ added in v0.118.0
func (t *CharmTheme) GetUserColor() string
type ChatChunkEvent ¶
type ChatChunkEvent struct {
RequestID string
Timestamp time.Time
Content string
ReasoningContent string
ToolCalls []sdk.ChatCompletionMessageToolCallChunk
Delta bool
Usage *sdk.CompletionUsage
}
ChatChunkEvent represents a streaming chunk of chat response
func (ChatChunkEvent) GetRequestID ¶
func (e ChatChunkEvent) GetRequestID() string
func (ChatChunkEvent) GetTimestamp ¶
func (e ChatChunkEvent) GetTimestamp() time.Time
type ChatCompleteEvent ¶
type ChatCompleteEvent struct {
RequestID string
Timestamp time.Time
Message string
ReasoningContent string
ToolCalls []sdk.ChatCompletionMessageToolCall
Metrics *ChatMetrics
Cancelled bool
}
ChatCompleteEvent indicates chat completion. Cancelled is set when the completion is the result of a user-initiated cancel (Esc) rather than the model finishing on its own - the UI uses this to show "User interrupted" rather than "Response complete".
func (ChatCompleteEvent) GetRequestID ¶
func (e ChatCompleteEvent) GetRequestID() string
func (ChatCompleteEvent) GetTimestamp ¶
func (e ChatCompleteEvent) GetTimestamp() time.Time
type ChatCompletionRunner ¶ added in v0.112.3
type ChatCompletionRunner interface {
Start(holder BashDetachChannelHolder) tea.Cmd
HandleChatStart(msg ChatStartEvent) tea.Cmd
HandleChatChunk(msg ChatChunkEvent) tea.Cmd
HandleChatComplete(msg ChatCompleteEvent) tea.Cmd
HandleChatError(msg ChatErrorEvent) tea.Cmd
HandleOptimizationStatus(msg OptimizationStatusEvent) tea.Cmd
SetPendingRestoration(originalModel string)
}
ChatCompletionRunner owns the LLM streaming lifecycle - initiating streaming, translating chat-start / chat-chunk / chat-complete / chat-error events into UI state transitions, and handling the model-restoration side effect after a temporary /model switch.
Start takes a BashDetachChannelHolder because the agent core needs that narrow interface attached to its context when launching tools that may require backgrounding. In #529 commit 3 that holder is the orchestrator itself; in commit 4 it becomes the DirectExecutionService.
type ChatErrorEvent ¶
ChatErrorEvent represents an error during chat
func (ChatErrorEvent) GetRequestID ¶
func (e ChatErrorEvent) GetRequestID() string
func (ChatErrorEvent) GetTimestamp ¶
func (e ChatErrorEvent) GetTimestamp() time.Time
type ChatEventListener ¶ added in v0.112.3
type ChatEventListener interface {
ListenForChatEvents(eventChan <-chan ChatEvent) tea.Cmd
ListenForEvents(eventChan <-chan tea.Msg) tea.Cmd
}
ChatEventListener wraps the small "read one message off a channel as a tea.Cmd" pattern used throughout the handlers. Extracted so services can chain channel reads back into the Bubble Tea event loop without each one re-implementing the same closure.
type ChatHandler ¶ added in v0.97.0
type ChatHandler interface {
// Core event handling (to be deprecated as we move to component-based handling)
Handle(msg tea.Msg) tea.Cmd
// Specific event handlers
HandleUserInputEvent(msg UserInputEvent) tea.Cmd
HandleFileSelectionRequestEvent(msg FileSelectionRequestEvent) tea.Cmd
HandleConversationSelectedEvent(msg ConversationSelectedEvent) tea.Cmd
HandleToolApprovalRequestedEvent(msg ToolApprovalRequestedEvent) tea.Cmd
HandleToolApprovalResponseEvent(msg ToolApprovalResponseEvent) tea.Cmd
HandlePlanApprovalRequestedEvent(msg PlanApprovalRequestedEvent) tea.Cmd
HandlePlanApprovalResponseEvent(msg PlanApprovalResponseEvent) tea.Cmd
// Command handlers
HandleCommand(commandText string) tea.Cmd
HandleBashCommand(commandText string) tea.Cmd
HandleToolCommand(commandText string) tea.Cmd
HandleBackgroundShellRequest() tea.Cmd
// Event channel listeners
ListenForEvents(eventChan <-chan tea.Msg) tea.Cmd
ListenForChatEvents(eventChan <-chan ChatEvent) tea.Cmd
// State management
GetActiveToolCallID() string
SetActiveToolCallID(id string)
// Utility methods
ParseToolCall(input string) (string, map[string]any, error)
ParseArguments(argsStr string) (map[string]any, error)
SetBashDetachChan(chan<- struct{})
GetBashDetachChan() chan<- struct{}
ClearBashDetachChan()
}
ChatHandler defines the interface for the chat handler This interface enables testing handlers in isolation and provides a clear contract
type ChatMetrics ¶
type ChatMetrics struct {
Duration time.Duration
Usage *sdk.CompletionUsage
}
ChatMetrics holds performance and usage metrics
type ChatService ¶
type ChatService interface {
CancelRequest(requestID string) error
GetMetrics(requestID string) *ChatMetrics
}
ChatService handles chat completion operations
type ChatSession ¶ added in v0.27.0
type ChatSession struct {
RequestID string
Status ChatStatus
StartTime time.Time
Model string
EventChannel <-chan ChatEvent
IsFirstChunk bool
HasToolCalls bool
LastActivity time.Time
RetryStatus *RetryStatus
}
ChatSession represents an active chat session state
type ChatSessionManager ¶ added in v0.125.0
type ChatSessionManager interface {
SetChatPending()
StartChatSession(requestID, model string, eventChan <-chan ChatEvent) error
UpdateChatStatus(status ChatStatus) error
EndChatSession()
GetChatSession() *ChatSession
IsAgentBusy() bool
SetRetryStatus(status *RetryStatus)
GetRetryStatus() *RetryStatus
TouchChatActivity()
}
ChatSessionManager handles chat session lifecycle
type ChatStartEvent ¶
ChatStartEvent indicates a chat request has started
func (ChatStartEvent) GetRequestID ¶
func (e ChatStartEvent) GetRequestID() string
func (ChatStartEvent) GetTimestamp ¶
func (e ChatStartEvent) GetTimestamp() time.Time
type ChatStatus ¶ added in v0.27.0
type ChatStatus int
ChatStatus represents the current chat operation status
const ( ChatStatusIdle ChatStatus = iota ChatStatusStarting ChatStatusThinking ChatStatusGenerating ChatStatusReceivingTools ChatStatusWaitingTools ChatStatusCompleted ChatStatusError ChatStatusCancelled )
func (ChatStatus) String ¶ added in v0.27.0
func (c ChatStatus) String() string
type ChatSyncResponse ¶ added in v0.36.0
type ChatSyncResponse struct {
RequestID string `json:"request_id"`
Content string `json:"content"`
ReasoningContent string `json:"reasoning_content,omitempty"`
ToolCalls []sdk.ChatCompletionMessageToolCall `json:"tool_calls,omitempty"`
Usage *sdk.CompletionUsage `json:"usage,omitempty"`
Duration time.Duration `json:"duration"`
}
ChatSyncResponse represents a synchronous chat completion response
type ClearErrorEvent ¶ added in v0.45.0
type ClearErrorEvent struct{}
ClearErrorEvent clears any displayed error
type ClearInputEvent ¶ added in v0.45.0
type ClearInputEvent struct{}
ClearInputEvent clears the input field
type ClickIndicatorEvent ¶ added in v0.96.0
type ClickIndicatorEvent struct {
BaseChatEvent
X int `json:"X"`
Y int `json:"Y"`
ClickIndicator bool `json:"ClickIndicator"`
}
ClickIndicatorEvent indicates a visual click indicator should be shown at coordinates
type CompletionRequestedEvent ¶ added in v0.99.2
type CompletionRequestedEvent struct{}
CompletionRequestedEvent is triggered when the agent should complete
func (CompletionRequestedEvent) EventType ¶ added in v0.99.2
func (e CompletionRequestedEvent) EventType() string
type ComputerUsePauseManager ¶ added in v0.125.0
type ComputerUsePauseManager interface {
SetComputerUsePaused(paused bool, requestID string)
IsComputerUsePaused() bool
GetPausedRequestID() string
ClearComputerUsePauseState()
}
ComputerUsePauseManager handles computer use pause state
type ComputerUsePausedEvent ¶ added in v0.96.0
ComputerUsePausedEvent indicates computer-use execution has been paused
func (ComputerUsePausedEvent) GetRequestID ¶ added in v0.96.0
func (e ComputerUsePausedEvent) GetRequestID() string
func (ComputerUsePausedEvent) GetTimestamp ¶ added in v0.96.0
func (e ComputerUsePausedEvent) GetTimestamp() time.Time
type ComputerUseResumedEvent ¶ added in v0.96.0
ComputerUseResumedEvent indicates computer-use execution has resumed
func (ComputerUseResumedEvent) GetRequestID ¶ added in v0.96.0
func (e ComputerUseResumedEvent) GetRequestID() string
func (ComputerUseResumedEvent) GetTimestamp ¶ added in v0.96.0
func (e ComputerUseResumedEvent) GetTimestamp() time.Time
type ContainerInfo ¶ added in v0.82.0
ContainerInfo represents basic container information
type ContainerRuntime ¶ added in v0.82.0
type ContainerRuntime interface {
// Network operations
GetNetworkName() string
EnsureNetwork(ctx context.Context) error
CleanupNetwork(ctx context.Context) error
// Container lifecycle operations
ContainerExists(containerIDOrName string) bool
RunContainer(ctx context.Context, opts RunContainerOptions) (containerID string, err error)
StopContainer(ctx context.Context, containerIDOrName string) error
// Image operations. The optional progress callback receives layer counts
// as the pull advances.
PullImage(ctx context.Context, image string, progress func(done, total int)) error
// Container inspection
GetContainerHealth(ctx context.Context, containerIDOrName string) (HealthStatus, error)
ListRunningContainers(ctx context.Context, nameFilter string) ([]ContainerInfo, error)
}
ContainerRuntime defines the interface for container runtime operations This abstraction allows support for Docker, Podman, or any other container runtime
type ContextKey ¶ added in v0.56.0
type ContextKey string
ContextKey is the type used for context keys in the application
const AgentModeKey ContextKey = "agent_mode"
AgentModeKey is the context key for the agent mode in effect for a tool execution. The Bash tool reads it to resolve which per-mode allow-list (tools.bash.mode.<key>.allow) governs the command. When unset, callers treat it as standard mode.
const BashDetachChannelKey ContextKey = "bash_detach_channel"
BashDetachChannelKey is the context key for the bash detach signal channel When this key is set in the context, the bash tool can signal when a command should be detached to the background (e.g., via keyboard shortcut)
const BashOutputCallbackKey ContextKey = "bash_output_callback"
BashOutputCallbackKey is the context key for bash output streaming callback When this key is set in the context, the bash tool streams output to the callback as it runs instead of waiting for the command to complete
const ChatHandlerKey ContextKey = "chat_handler"
ChatHandlerKey is the context key for passing the ChatHandler reference This allows the agent service to access ChatHandler for setting up the detach channel
const DirectExecutionKey ContextKey = "direct_execution"
DirectExecutionKey is the context key for direct tool execution When this key is set to true in the context, it indicates that the tool was invoked directly by the user (e.g., via !! command) rather than by the LLM This allows tools to adjust behavior (e.g., skip coordinate scaling for mouse operations)
const ModelKey ContextKey = "model"
ModelKey is the context key for the model in effect for the current agent turn. The Agent tool reads it so spawned subagents inherit the parent's model by default (otherwise the subagent process would fail with "no model specified").
const SessionIDKey ContextKey = "session_id"
SessionIDKey is the context key for the current conversation session ID This allows shortcuts to access the session ID when they need it (e.g., /export)
const ToolApprovedKey ContextKey = "tool_approved"
ToolApprovedKey is the context key for user-approved tool executions When this key is set to true in the context, it indicates that the tool execution was explicitly approved by the user and should bypass allowed list validation
const ToolCallIDKey ContextKey = "tool_call_id"
ToolCallIDKey is the context key for the LLM tool call id of the current tool execution
const TraceEnvKey ContextKey = "trace_env"
TraceEnvKey is the context key for the W3C trace-context subprocess environment
const UserQuestionBrokerKey ContextKey = "user_question_broker"
UserQuestionBrokerKey is the context key for the interactive question broker. It is injected only on the chat path (where a TUI event loop exists), so the AskUserQuestion tool sees a nil broker on headless/no-TTY runs and degrades gracefully instead of blocking forever.
type ConversationEntry ¶
type ConversationEntry struct {
// Core message fields
Message Message `json:"message"`
Model string `json:"model,omitempty"`
Time time.Time `json:"time"`
Hidden bool `json:"hidden,omitempty"`
Images []ImageAttachment `json:"images,omitempty"`
ReasoningContent string `json:"reasoning_content,omitempty"`
// Tool-related fields
ToolExecution *ToolExecutionResult `json:"tool_execution,omitempty"`
PendingToolCall *sdk.ChatCompletionMessageToolCall `json:"pending_tool_call,omitempty"`
ToolApprovalStatus ToolApprovalStatus `json:"tool_approval_status,omitempty"`
// Plan mode fields
Rejected bool `json:"rejected,omitempty"`
IsPlan bool `json:"is_plan,omitempty"`
PlanApprovalStatus PlanApprovalStatus `json:"plan_approval_status,omitempty"`
}
ConversationEntry represents a message in the conversation with metadata
type ConversationExporter ¶ added in v0.125.0
type ConversationExporter interface {
Export(format ExportFormat) ([]byte, error)
}
ConversationExporter handles conversation export
type ConversationLifecycleManager ¶ added in v0.125.0
type ConversationLifecycleManager interface {
StartNewConversation(title string) error
LoadConversation(ctx context.Context, conversationID string) error
GetCurrentConversationTitle() string
GetCurrentConversationID() string
}
ConversationLifecycleManager handles conversation lifecycle operations
type ConversationMetadata ¶ added in v0.142.2
type ConversationMetadata struct {
ID string `json:"id"`
Title string `json:"title"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
MessageCount int `json:"message_count"`
TokenStats SessionTokenStats `json:"token_stats"`
CostStats SessionCostStats `json:"cost_stats,omitempty"`
Model string `json:"model,omitempty"`
Tags []string `json:"tags,omitempty"`
TitleGenerated bool `json:"title_generated,omitempty"`
TitleInvalidated bool `json:"title_invalidated,omitempty"`
TitleGenerationTime *time.Time `json:"title_generation_time,omitempty"`
ContextID string `json:"context_id,omitempty"`
}
ConversationMetadata contains metadata about a conversation
type ConversationOptimizer ¶ added in v0.99.0
type ConversationOptimizer interface {
OptimizeMessages(messages []sdk.Message, model string, force bool) []sdk.Message
}
ConversationOptimizer optimizes conversation history to reduce token usage
type ConversationRepository ¶
type ConversationRepository interface {
MessageRepository
TokenUsageRepository
ToolResultFormatter
PendingToolCallManager
ConversationLifecycleManager
ConversationExporter
}
ConversationRepository is the composed interface for all conversation storage and retrieval operations. New code should depend on the narrower sub-interfaces above.
type ConversationSelectedEvent ¶ added in v0.45.0
type ConversationSelectedEvent struct {
ConversationID string
}
ConversationSelectedEvent indicates conversation selection
type ConversationSummary ¶ added in v0.142.2
type ConversationSummary struct {
ID string `json:"id"`
Title string `json:"title"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
MessageCount int `json:"message_count"`
TokenStats SessionTokenStats `json:"token_stats"`
CostStats SessionCostStats `json:"cost_stats,omitempty"`
Model string `json:"model,omitempty"`
Tags []string `json:"tags,omitempty"`
Summary string `json:"summary,omitempty"`
TitleGenerated bool `json:"title_generated,omitempty"`
TitleInvalidated bool `json:"title_invalidated,omitempty"`
TitleGenerationTime *time.Time `json:"title_generation_time,omitempty"`
}
ConversationSummary contains summary information about a conversation
type ConversationsLoadedEvent ¶ added in v0.45.0
ConversationsLoadedEvent indicates conversations have been loaded
type CustomFormatter ¶ added in v0.33.4
type CustomFormatter struct {
BaseFormatter
// contains filtered or unexported fields
}
CustomFormatter extends BaseFormatter with customizable collapse behavior
func NewCustomFormatter ¶ added in v0.33.4
func NewCustomFormatter(toolName string, collapseFunc func(string) bool) CustomFormatter
NewCustomFormatter creates a formatter with custom collapse logic
func (CustomFormatter) FormatExpanded ¶ added in v0.143.0
func (f CustomFormatter) FormatExpanded(result *ToolExecutionResult, dataContent string) string
FormatExpanded renders the expanded tree using the custom collapse behavior.
func (CustomFormatter) FormatToolCall ¶ added in v0.33.4
func (f CustomFormatter) FormatToolCall(args map[string]any, expanded bool) string
FormatToolCall overrides BaseFormatter to use custom collapse logic
func (CustomFormatter) ShouldCollapseArg ¶ added in v0.33.4
func (f CustomFormatter) ShouldCollapseArg(key string) bool
ShouldCollapseArg uses the custom collapse function if provided
type DebugKeyEvent ¶ added in v0.45.0
DebugKeyEvent provides debug information about key presses
type DeleteToolResult ¶ added in v0.18.0
type DeleteToolResult struct {
Path string `json:"path"`
DeletedFiles []string `json:"deleted_files"`
DeletedDirs []string `json:"deleted_dirs"`
TotalFilesDeleted int `json:"total_files_deleted"`
TotalDirsDeleted int `json:"total_dirs_deleted"`
WildcardExpanded bool `json:"wildcard_expanded"`
Errors []string `json:"errors,omitempty"`
}
DeleteToolResult represents the result of a delete operation
type DimensionsManager ¶ added in v0.125.0
DimensionsManager handles UI dimensions
type DirectExecutionService ¶ added in v0.112.3
type DirectExecutionService interface {
BashDetachChannelHolder
HandleBashCommand(commandText string) tea.Cmd
HandleToolCommand(commandText string) tea.Cmd
HandleBackgroundShellRequest() tea.Cmd
HandleBashOutputChunk(msg BashOutputChunkEvent) tea.Cmd
HandleBashCommandCompleted(msg BashCommandCompletedEvent) tea.Cmd
ParseToolCall(input string) (string, map[string]any, error)
ParseArguments(argsStr string) (map[string]any, error)
PendingBashChannel() <-chan tea.Msg
PendingToolChannel() <-chan tea.Msg
}
DirectExecutionService owns user-typed `!command` (bash) and `!!Tool(...)` (tool) execution. It synthesizes the conversation entries, spawns the async goroutines, owns the per-call event/detach channels, and exposes the channels via PendingBashChannel / PendingToolChannel so the ToolExecutionCoordinator can keep pumping them.
Implements BashDetachChannelHolder so the agent core can find it on the request context (see WithChatHandler / GetChatHandler in context_helpers.go).
type DraculaTheme ¶ added in v0.47.0
type DraculaTheme struct{}
DraculaTheme provides the popular Dracula color scheme
func NewDraculaTheme ¶ added in v0.47.0
func NewDraculaTheme() *DraculaTheme
func (*DraculaTheme) GetAccentColor ¶ added in v0.47.0
func (t *DraculaTheme) GetAccentColor() string
func (*DraculaTheme) GetAssistantColor ¶ added in v0.47.0
func (t *DraculaTheme) GetAssistantColor() string
func (*DraculaTheme) GetBorderColor ¶ added in v0.47.0
func (t *DraculaTheme) GetBorderColor() string
func (*DraculaTheme) GetDiffAddColor ¶ added in v0.47.0
func (t *DraculaTheme) GetDiffAddColor() string
func (*DraculaTheme) GetDiffRemoveColor ¶ added in v0.47.0
func (t *DraculaTheme) GetDiffRemoveColor() string
func (*DraculaTheme) GetDimColor ¶ added in v0.47.0
func (t *DraculaTheme) GetDimColor() string
func (*DraculaTheme) GetErrorColor ¶ added in v0.47.0
func (t *DraculaTheme) GetErrorColor() string
func (*DraculaTheme) GetStatusColor ¶ added in v0.47.0
func (t *DraculaTheme) GetStatusColor() string
func (*DraculaTheme) GetSuccessColor ¶ added in v0.56.0
func (t *DraculaTheme) GetSuccessColor() string
func (*DraculaTheme) GetUserColor ¶ added in v0.47.0
func (t *DraculaTheme) GetUserColor() string
type DrainQueueEvent ¶ added in v0.126.0
type DrainQueueEvent struct{}
DrainQueueEvent asks the orchestrator to start a fresh agent turn when the agent is idle on the chat view and the shared message queue has content (background-job completion notes or user messages typed while busy). Unlike the old queue-drain tick it is not a clock: it is pushed exactly once per real trigger (a background job landing work, a turn completing with a non-empty queue, or re-entering the chat view), and HandleDrainQueueEvent is a pure gate that starts a turn (Idle -> CheckingQueue -> ... -> Completing -> Idle) or returns nil. There is no self-reschedule.
type DrainQueueRetryEvent ¶ added in v0.126.0
type DrainQueueRetryEvent struct{}
DrainQueueRetryEvent is the bounded retry behind DrainQueueEvent, and is NOT a clock. A DrainQueueEvent can land while the agent is momentarily busy (e.g. a background job finishes in the same instant the turn is still completing); the gate drops it, so without a retry the queue would strand. HandleDrainQueueEvent arms a single DrainQueueRetryEvent in that case, and the drainRetryArmed guard keeps it to exactly one outstanding timer no matter how many DrainQueueEvents arrived. When it fires, HandleDrainQueueRetryEvent re-runs the gate, which re-arms only while work is still stranded and stops the moment the queue drains.
type EditOperationResult ¶ added in v0.22.0
type EditOperationResult struct {
OldString string `json:"old_string"`
NewString string `json:"new_string"`
ReplaceAll bool `json:"replace_all"`
ReplacedCount int `json:"replaced_count"`
Success bool `json:"success"`
Error string `json:"error,omitempty"`
// WhitespaceNormalized is true when this edit matched via the indentation-tolerant fallback.
WhitespaceNormalized bool `json:"whitespace_normalized,omitempty"`
}
EditOperationResult represents the result of a single edit operation within MultiEdit
type EditToolResult ¶ added in v0.21.0
type EditToolResult struct {
FilePath string `json:"file_path"`
OldString string `json:"old_string"`
NewString string `json:"new_string"`
ReplacedCount int `json:"replaced_count"`
ReplaceAll bool `json:"replace_all"`
FileModified bool `json:"file_modified"`
OriginalSize int64 `json:"original_size"`
NewSize int64 `json:"new_size"`
BytesDifference int64 `json:"bytes_difference"`
OriginalLines int `json:"original_lines"`
NewLines int `json:"new_lines"`
LinesDifference int `json:"lines_difference"`
Diff string `json:"diff,omitempty"`
WhitespaceNormalized bool `json:"whitespace_normalized,omitempty"`
StartLine int `json:"start_line,omitempty"`
}
EditToolResult represents the result of an edit operation
type EventBridge ¶ added in v0.96.0
type EventBridge interface {
// Tap intercepts an event stream and multicasts it to all subscribers
// Returns a new channel that mirrors the input channel
Tap(input <-chan ChatEvent) <-chan ChatEvent
// Publish broadcasts an event to all subscribers
Publish(event ChatEvent)
// Subscribe creates a new event channel and returns it
Subscribe() chan ChatEvent
// Unsubscribe removes a subscriber and closes its channel
Unsubscribe(ch chan ChatEvent)
}
EventBridge multicasts chat events to multiple subscribers (e.g., terminal UI and floating window)
type EventBridgeManager ¶ added in v0.125.0
type EventBridgeManager interface {
SetEventBridge(bridge EventBridge)
GetEventBridge() EventBridge
BroadcastEvent(event ChatEvent)
}
EventBridgeManager handles event multicast for floating window
type ExportFormat ¶
type ExportFormat string
ExportFormat defines the format for exporting conversations
const ( ExportMarkdown ExportFormat = "markdown" ExportJSON ExportFormat = "json" ExportText ExportFormat = "text" )
type FetchResult ¶ added in v0.11.0
type FetchResult struct {
Content string `json:"content"`
URL string `json:"url"`
Status int `json:"status"`
Size int64 `json:"size"`
ContentType string `json:"content_type"`
Cached bool `json:"cached"`
SavedPath string `json:"saved_path,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
Warning string `json:"warning,omitempty"`
}
FetchResult represents the result of a fetch operation
type FileReadToolResult ¶ added in v0.13.1
type FileReadToolResult struct {
FilePath string `json:"file_path"`
Content string `json:"content"`
Size int64 `json:"size"`
StartLine int `json:"start_line,omitempty"`
EndLine int `json:"end_line,omitempty"`
Error string `json:"error,omitempty"`
}
FileReadToolResult represents the result of a file read operation
type FileSelectionManager ¶ added in v0.125.0
type FileSelectionManager interface {
SetupFileSelection(files []string)
GetFileSelectionState() *FileSelectionState
UpdateFileSearchQuery(query string)
SetFileSelectedIndex(index int)
ClearFileSelectionState()
}
FileSelectionManager handles file selection UI state
type FileSelectionRequestEvent ¶ added in v0.45.0
type FileSelectionRequestEvent struct{}
FileSelectionRequestEvent requests file selection UI
type FileSelectionState ¶ added in v0.27.0
type FileSelectionState struct {
Files []string `json:"files"`
SearchQuery string `json:"search_query"`
SelectedIndex int `json:"selected_index"`
}
FileSelectionState represents the state of file selection UI
type FileService ¶
type FileService interface {
ListProjectFiles() ([]string, error)
ReadFile(path string) (string, error)
ReadFileLines(path string, startLine, endLine int) (string, error)
ValidateFile(path string) error
GetFileInfo(path string) (FileInfo, error)
}
FileService handles file operations
type FileWriteToolResult ¶ added in v0.17.0
type FileWriteToolResult struct {
FilePath string `json:"file_path"`
BytesWritten int64 `json:"bytes_written"`
LinesWritten int `json:"lines_written"`
Created bool `json:"created"`
Overwritten bool `json:"overwritten"`
DirsCreated bool `json:"dirs_created"`
Appended bool `json:"appended"`
ChunkIndex int `json:"chunk_index,omitempty"`
TotalChunks int `json:"total_chunks,omitempty"`
IsComplete bool `json:"is_complete"`
Error string `json:"error,omitempty"`
}
FileWriteToolResult represents the result of a file write operation
type FocusManager ¶ added in v0.125.0
type FocusManager interface {
SetLastFocusedApp(appID string)
GetLastFocusedApp() string
ClearLastFocusedApp()
SetLastClickCoordinates(x, y int)
GetLastClickCoordinates() (x, y int)
ClearLastClickCoordinates()
}
FocusManager handles macOS computer-use focus tracking
type FocusStatusBarEvent ¶ added in v0.128.0
type FocusStatusBarEvent struct{}
FocusStatusBarEvent moves keyboard focus to the status-indicator row below the input, fired when arrow-down would otherwise be a no-op
type FormatterType ¶ added in v0.33.4
type FormatterType string
FormatterType defines the context for formatting tool results
const ( FormatterUI FormatterType = "ui" // Compact display for UI FormatterLLM FormatterType = "llm" // Formatted for LLM consumption FormatterShort FormatterType = "short" // Brief summary format )
type GatewayManager ¶ added in v0.54.0
type GatewayManager interface {
// Start starts the gateway container or binary if configured to run locally
Start(ctx context.Context) error
// Stop stops the gateway container or binary
Stop(ctx context.Context) error
// IsRunning returns whether the gateway is running
IsRunning() bool
// GetGatewayURL returns the actual gateway URL with the assigned port
GetGatewayURL() string
// EnsureStarted starts the gateway if configured and not already running
// This is a convenience method that checks config and running state before starting
EnsureStarted() error
}
GatewayManager manages the lifecycle of the gateway (container or binary)
type GitHubIssue ¶ added in v0.31.0
type GitHubIssue struct {
Number int
Title string
Body string
State string
URL string
UpdatedAt time.Time
Author string
Comments []GitHubIssueComment
}
GitHubIssue is a minimal projection of a GitHub issue, big enough for both the autocomplete dropdown (Number, Title, State) and inline expansion into a chat-message block (Body, URL, Comments, UpdatedAt). Comments is nil for the list variant and populated for the view variant.
type GitHubIssueComment ¶ added in v0.117.0
GitHubIssueComment is a single comment on a GitHub issue, sorted by CreatedAt ascending.
type GitHubIssueService ¶ added in v0.117.0
type GitHubIssueService interface {
// ListIssues returns recent open issues for the current repo, newest first.
// Results are cached for a short TTL so repeated autocomplete keystrokes
// don't shell out per character. Returns ([], nil) on environment failures.
ListIssues(ctx context.Context) ([]GitHubIssue, error)
// GetIssue fetches an issue with body and the most-recent comments (capped
// internally). Uncached. Returns (nil, err) on failure so the expansion
// path can leave the raw token in place.
GetIssue(ctx context.Context, number int) (*GitHubIssue, error)
// IsAvailable reports whether the service can serve requests in the
// current environment. Used by the autocomplete trigger to short-circuit
// a slow first shell-out when gh / repo / auth are missing.
IsAvailable() bool
}
GitHubIssueService provides cached access to the current repository's GitHub issues via the gh CLI. Implementations gracefully degrade (return empty/nil with no error) when not in a git repo, when gh is not installed, or when the remote/auth is not configured - the chat input's "#" autocomplete and "#N" inline expansion simply become no-ops in those environments.
type GitHubSetupService ¶ added in v0.143.0
type GitHubSetupService interface {
GetCurrentRepo() (string, error)
IsOrgRepo(repo string) (bool, error)
CheckOrgSecretsExist(orgName string) (bool, error)
SetOrgSecret(orgName, name, value string) error
PreparePRCreation(repo, workflowPath string) (string, error)
WriteWorkflowFile(path, content string) error
GenerateStandardWorkflowContent() string
GenerateGithubActionWorkflowContent() string
}
GitHubSetupService handles git/gh/CI operations for the GitHub Action CI setup flow triggered from the init-github-action wizard. Every shell invocation carries a context so a wedged subprocess cannot hang the UI.
type GitPRResolvedEvent ¶ added in v0.140.0
type GitPRResolvedEvent struct {
PR string
}
GitPRResolvedEvent carries the PR number for the current branch, resolved asynchronously by the input view's fetch command. An empty PR means no PR exists (or gh is unavailable). Defined here rather than as a component-local msg because the chat application only routes domain-prefixed messages to UI components.
type GithubLightTheme ¶ added in v0.47.0
type GithubLightTheme struct{}
GithubLightTheme provides a light theme similar to GitHub's interface
func NewGithubLightTheme ¶ added in v0.47.0
func NewGithubLightTheme() *GithubLightTheme
func (*GithubLightTheme) GetAccentColor ¶ added in v0.47.0
func (t *GithubLightTheme) GetAccentColor() string
func (*GithubLightTheme) GetAssistantColor ¶ added in v0.47.0
func (t *GithubLightTheme) GetAssistantColor() string
func (*GithubLightTheme) GetBorderColor ¶ added in v0.47.0
func (t *GithubLightTheme) GetBorderColor() string
func (*GithubLightTheme) GetDiffAddColor ¶ added in v0.47.0
func (t *GithubLightTheme) GetDiffAddColor() string
func (*GithubLightTheme) GetDiffRemoveColor ¶ added in v0.47.0
func (t *GithubLightTheme) GetDiffRemoveColor() string
func (*GithubLightTheme) GetDimColor ¶ added in v0.47.0
func (t *GithubLightTheme) GetDimColor() string
func (*GithubLightTheme) GetErrorColor ¶ added in v0.47.0
func (t *GithubLightTheme) GetErrorColor() string
func (*GithubLightTheme) GetStatusColor ¶ added in v0.47.0
func (t *GithubLightTheme) GetStatusColor() string
func (*GithubLightTheme) GetSuccessColor ¶ added in v0.56.0
func (t *GithubLightTheme) GetSuccessColor() string
func (*GithubLightTheme) GetUserColor ¶ added in v0.47.0
func (t *GithubLightTheme) GetUserColor() string
type HealthCheckConfig ¶ added in v0.82.0
type HealthCheckConfig struct {
Interval string // e.g., "10s"
Timeout string // e.g., "5s"
Retries int
StartPeriod string // e.g., "10s"
}
HealthCheckConfig defines container health check configuration
type HealthStatus ¶ added in v0.82.0
type HealthStatus string
HealthStatus represents the health status of a container
const ( HealthStatusHealthy HealthStatus = "healthy" HealthStatusUnhealthy HealthStatus = "unhealthy" HealthStatusStarting HealthStatus = "starting" HealthStatusNone HealthStatus = "none" )
type HideHelpBarEvent ¶ added in v0.45.0
type HideHelpBarEvent struct{}
HideHelpBarEvent hides the help bar when typing other characters
type HistoryCleaner ¶ added in v0.149.0
HistoryCleaner is an optional interface that channels can implement to delete the chat's message history on the remote platform (used by /new).
type HookCommand ¶ added in v0.125.0
HookCommand is a resolved command hook ready to run at a hook point: a named shell command with a wall-clock timeout. It is the command-action sibling of SystemReminder (the text-injection action). The agent - not the provider - runs it, through the same bash allow-list a model-proposed command faces.
type HookCommandProvider ¶ added in v0.125.0
type HookCommandProvider interface {
CommandsDue(hook HookPoint) []HookCommand
}
HookCommandProvider resolves which command hooks are due at a hook point. It is the command-action sibling of SystemReminderProvider, implemented by config from the user's hooks list. The provider only resolves the commands; the agent runs them through the existing bash allow-list, so config stays free of os/exec. The agent depends on this interface so the command set can be faked in tests.
type HookPoint ¶ added in v0.125.0
type HookPoint string
HookPoint is one of the pre-defined points in the agent loop where actions can attach. The catalog is fully symmetric: every loop phase exposes a pre_/post_ pair. System reminders attach a text-injection action here today; executable command hooks attach a command-execution action at the same points later, both flowing through the single dispatchHooks(point) seam.
const ( HookPreSession HookPoint = "pre_session" // run begins, before the first stream (turn 1) HookPostSession HookPoint = "post_session" // run finished ("agent finished generating") HookPreStream HookPoint = "pre_stream" // before each LLM streaming turn HookPostStream HookPoint = "post_stream" // after each LLM response, before tool evaluation HookPreTool HookPoint = "pre_tool" // before tool execution HookPostTool HookPoint = "post_tool" // after tool execution HookPreQueueDrain HookPoint = "pre_queue_drain" // before draining queued user messages HookPostQueueDrain HookPoint = "post_queue_drain" // after draining queued user messages )
type ImageAttachment ¶ added in v0.57.0
type ImageAttachment struct {
Data string `json:"data"`
MimeType string `json:"mime_type"`
Filename string `json:"filename,omitempty"`
DisplayName string `json:"display_name"`
SourcePath string `json:"-"`
}
ImageAttachment represents an image attachment in a message
type ImageService ¶ added in v0.57.0
type ImageService interface {
// ReadImageFromFile reads an image from a file path and returns it as a base64 attachment
ReadImageFromFile(filePath string) (*ImageAttachment, error)
// ReadImageFromBinary reads an image from binary data and returns it as a base64 attachment
ReadImageFromBinary(imageData []byte, filename string) (*ImageAttachment, error)
// ReadImageFromURL fetches an image from a URL and returns it as a base64 attachment
ReadImageFromURL(imageURL string) (*ImageAttachment, error)
// CreateDataURL creates a data URL from an image attachment
CreateDataURL(attachment *ImageAttachment) string
// IsImageFile checks if a file is a supported image format
IsImageFile(filePath string) bool
// IsImageURL checks if a string is a valid image URL
IsImageURL(urlStr string) bool
}
ImageService handles image operations including loading and encoding
type InboundMessage ¶ added in v0.101.0
type InboundMessage struct {
ChannelName string `json:"channel_name"`
SenderID string `json:"sender_id"`
Content string `json:"content"`
Images []ImageAttachment `json:"images,omitempty"`
Timestamp time.Time `json:"timestamp"`
Metadata map[string]string `json:"metadata,omitempty"`
}
InboundMessage represents a message received from an external channel
type JobKind ¶ added in v0.126.0
type JobKind string
JobKind identifies which background-work subsystem produced a job so one supervisor, one tracker, and one task view can treat A2A tasks, background shells, and subagents uniformly while still reporting per-kind counts.
type JobLivenessReporter ¶ added in v0.128.0
JobLivenessReporter reports whether a supervised background job is still running, by id. It is the narrow projection of BackgroundTaskRegistry a tool uses to tell whether the supervisor is still driving a job it launched - an A2A task being polled, a background shell, or a subagent - so a manual read defers to the supervisor (the single source of truth) instead of racing it.
type JobMeta ¶ added in v0.126.0
type JobMeta struct {
ID string
Kind JobKind
Label string
Description string
Detail string
StartedAt time.Time
Silent bool
// HoldsSession keeps a headless session alive until the job terminates (A2A
// tasks, shells, headless subagents). False for user-driven interactive
// subagent panes so a one-shot `infer agent` does not hang at exit.
HoldsSession bool
}
JobMeta is the identity/display snapshot a background job exposes. The supervisor reads it once at submit (and surfaces it in the task view); it is not on any hot path.
type JobNotifier ¶ added in v0.126.0
type JobNotifier interface {
Notification(result ToolExecutionResult) string
}
JobNotifier is an optional BackgroundJob extension. A job that implements it formats its own completion-notification body (the text enqueued for the agent to read when it finishes) - e.g. a shell reports its exit code and duration, which a generic tool-result formatter would not. Jobs that do not implement it get the default domain formatting of their ToolExecutionResult.
type JobOutputProvider ¶ added in v0.146.0
type JobOutputProvider interface {
Output() string
}
JobOutputProvider is an optional BackgroundJob extension. A job that implements it provides its output text for the /tasks detail panel - e.g. a shell's captured stdout/stderr or a subagent's final result. Jobs that do not implement it show no output section in the detail panel.
type JobSignal ¶ added in v0.126.0
type JobSignal struct {
// Note is a human-facing line surfaced to the UI and, when Enqueue is set,
// landed on the message queue so the agent reads it on its next turn.
Note string
// Enqueue lands Note on the message queue and wakes the agent loop; otherwise
// Note is a UI-only status update.
Enqueue bool
// State is an optional kind-specific status token (e.g. an A2A task state).
State string
}
JobSignal is an intermediate, non-terminal event a running job emits to the supervisor (an A2A status change, a subagent that became blocked on a tool approval). The terminal outcome is Run's return value, never a signal.
type JobStatus ¶ added in v0.126.0
type JobStatus string
JobStatus is the unified lifecycle state across every background-work kind.
func (JobStatus) IsTerminal ¶ added in v0.126.0
IsTerminal reports whether the job has finished (completed or failed).
type JobStopper ¶ added in v0.126.0
type JobStopper interface {
WindJob(id string, sig WindSignal) error
}
JobStopper ends a supervised background job by id. It is the narrow projection of BackgroundTaskRegistry that CloseSubagent uses to wind down the supervised monitor of the subagent it closes - cancelling the job's Run context so the status-line running-count drops immediately instead of lingering until the pane-watcher next polls (or never, if a killed pane is not observed as gone).
type JobSubmitter ¶ added in v0.126.0
type JobSubmitter interface {
Submit(job BackgroundJob)
}
JobSubmitter hands a background job to the supervisor. It is the narrow projection of BackgroundTaskRegistry that tools use to submit work without depending on the whole registry surface.
type KeyboardTypeToolResult ¶ added in v0.96.0
type KeyboardTypeToolResult struct {
Text string `json:"text,omitempty"`
KeyCombo string `json:"key_combo,omitempty"`
Display string `json:"display"`
Method string `json:"method"`
}
KeyboardTypeToolResult represents the result of a keyboard input operation
type MCPClient ¶ added in v0.79.0
type MCPClient interface {
// DiscoverTools discovers all tools from enabled MCP servers
DiscoverTools(ctx context.Context) (map[string][]MCPDiscoveredTool, error)
// CallTool executes a tool on an MCP server
CallTool(ctx context.Context, serverName, toolName string, args map[string]any) (any, error)
// PingServer sends a ping request to check if a specific server is alive
PingServer(ctx context.Context, serverName string) error
// Close cleans up MCP client resources
Close() error
}
MCPClient handles communication with MCP servers
type MCPDiscoveredTool ¶ added in v0.79.0
MCPDiscoveredTool represents a tool discovered from an MCP server
type MCPManager ¶ added in v0.79.0
type MCPManager interface {
// Returns a list of clients
GetClients() []MCPClient
// GetClient returns the client for a specific server by name, or nil if
// no client is registered for that name. This is the O(1) lookup variant
// of GetClients and should be preferred when the server name is known -
// it avoids re-running DiscoverTools across every client just to find
// the owning one.
GetClient(serverName string) MCPClient
// GetTotalServers returns the total number of configured MCP servers
GetTotalServers() int
// StartMonitoring begins background health monitoring, pushing every
// MCPServerStatusUpdateEvent through the UI notifier injected at
// construction. Idempotent; the initial status is emitted asynchronously.
StartMonitoring(ctx context.Context)
// UpdateToolCount updates the tool count for a specific server
UpdateToolCount(serverName string, count int)
// ClearToolCount removes the tool count for a specific server
ClearToolCount(serverName string)
// Container lifecycle management
// StartServers starts all MCP servers that have run=true (non-fatal)
StartServers(ctx context.Context) error
// StopServers stops all running MCP server containers
StopServers(ctx context.Context) error
// Close stops monitoring, stops containers, and cleans up resources
Close() error
}
MCPManager manages the lifecycle, health monitoring, and container orchestration of MCP servers
type MCPServerEntry ¶ added in v0.79.0
type MCPServerEntry struct {
Name string
URL string
Enabled bool
Timeout int
Description string
IncludeTools []string
ExcludeTools []string
}
MCPServerEntry represents an MCP server configuration entry
type MCPServerStatus ¶ added in v0.79.0
type MCPServerStatus struct {
TotalServers int `json:"total_servers"`
ConnectedServers int `json:"connected_servers"`
TotalTools int `json:"total_tools"`
}
MCPServerStatus represents the status of MCP server connections
type MCPServerStatusUpdateEvent ¶ added in v0.79.0
type MCPServerStatusUpdateEvent struct {
ServerName string
Connected bool
TotalServers int
ConnectedServers int
TotalTools int
Tools []MCPDiscoveredTool
}
MCPServerStatusUpdateEvent indicates MCP server status has changed
type MCPToolResult ¶ added in v0.79.0
type MCPToolResult struct {
ServerName string `json:"server_name"`
ToolName string `json:"tool_name"`
Content string `json:"content"`
Error string `json:"error,omitempty"`
}
MCPToolResult represents the result of an MCP tool execution
type MarkdownRenderer ¶ added in v0.61.0
type MarkdownRenderer interface {
// Render converts markdown text to styled terminal output
Render(content string) string
// SetWidth updates the renderer width for responsive rendering
SetWidth(width int)
}
MarkdownRenderer handles conversion of markdown text to styled terminal output
type MemoryBackend ¶ added in v0.127.0
type MemoryBackend interface {
SyncIn(ctx context.Context) error
SyncOut(ctx context.Context) error
}
MemoryBackend syncs the persistent memory directory with a remote. The local backend is a no-op; the git backend pulls on run start and commits + pushes when a fact changes. Both directions are best-effort: an error is returned for tests/telemetry but callers log and continue - a sync failure never aborts the agent run. SyncIn is idempotent and runs at most once per process.
type MessageButton ¶ added in v0.149.0
MessageButton is a tappable button attached to an outbound message. Data is delivered back as inbound message content when tapped (channels that have no button UI ignore buttons entirely).
type MessageEditManager ¶ added in v0.125.0
type MessageEditManager interface {
SetMessageEditState(state *MessageEditState)
GetMessageEditState() *MessageEditState
ClearMessageEditState()
IsEditingMessage() bool
}
MessageEditManager handles message editing state
type MessageEditState ¶ added in v0.92.0
type MessageEditState struct {
OriginalMessageIndex int `json:"original_message_index"`
OriginalContent string `json:"original_content"`
EditTimestamp time.Time `json:"edit_timestamp"`
}
MessageEditState represents the state when editing a message
type MessageEditSubmitEvent ¶ added in v0.92.0
type MessageEditSubmitEvent struct {
RequestID string
Timestamp time.Time
OriginalIndex int
EditedContent string
Images []ImageAttachment
}
MessageEditSubmitEvent is emitted when edited message is submitted
func (MessageEditSubmitEvent) GetRequestID ¶ added in v0.92.0
func (e MessageEditSubmitEvent) GetRequestID() string
func (MessageEditSubmitEvent) GetTimestamp ¶ added in v0.92.0
func (e MessageEditSubmitEvent) GetTimestamp() time.Time
type MessageHistoryEditEvent ¶ added in v0.92.0
type MessageHistoryEditEvent struct {
RequestID string
Timestamp time.Time
MessageIndex int
MessageContent string
MessageSnapshot MessageSnapshot
}
MessageHistoryEditEvent is emitted when user wants to edit a selected message
func (MessageHistoryEditEvent) GetRequestID ¶ added in v0.92.0
func (e MessageHistoryEditEvent) GetRequestID() string
func (MessageHistoryEditEvent) GetTimestamp ¶ added in v0.92.0
func (e MessageHistoryEditEvent) GetTimestamp() time.Time
type MessageHistoryEditReadyEvent ¶ added in v0.92.0
type MessageHistoryEditReadyEvent struct {
MessageIndex int
Content string
Snapshot MessageSnapshot
}
MessageHistoryEditReadyEvent indicates editing is ready to begin
type MessageHistoryReadyEvent ¶ added in v0.91.0
type MessageHistoryReadyEvent struct {
Messages []MessageSnapshot
}
MessageHistoryReadyEvent indicates message history has been loaded and is ready to display
type MessageHistoryRestoreEvent ¶ added in v0.91.0
MessageHistoryRestoreEvent is emitted when user selects a restore point in message history
func (MessageHistoryRestoreEvent) GetRequestID ¶ added in v0.91.0
func (e MessageHistoryRestoreEvent) GetRequestID() string
func (MessageHistoryRestoreEvent) GetTimestamp ¶ added in v0.91.0
func (e MessageHistoryRestoreEvent) GetTimestamp() time.Time
type MessageQueue ¶ added in v0.53.0
type MessageQueue interface {
// Enqueue adds a message to the queue
Enqueue(message Message, requestID string)
// Dequeue removes and returns the next message from the queue
// Returns nil if the queue is empty
Dequeue() *QueuedMessage
// Peek returns the next message without removing it
// Returns nil if the queue is empty
Peek() *QueuedMessage
// Size returns the number of messages in the queue
Size() int
// IsEmpty returns true if the queue has no messages
IsEmpty() bool
// Clear removes all messages from the queue
Clear()
// GetAll returns all messages in the queue without removing them
GetAll() []QueuedMessage
}
MessageQueue handles centralized message queuing for all components
type MessageQueuedEvent ¶ added in v0.53.0
MessageQueuedEvent indicates a message was received from the queue and stored
func (MessageQueuedEvent) GetRequestID ¶ added in v0.53.0
func (e MessageQueuedEvent) GetRequestID() string
func (MessageQueuedEvent) GetTimestamp ¶ added in v0.53.0
func (e MessageQueuedEvent) GetTimestamp() time.Time
type MessageReceivedEvent ¶ added in v0.99.2
MessageReceivedEvent is triggered when a new message arrives
func (MessageReceivedEvent) EventType ¶ added in v0.99.2
func (e MessageReceivedEvent) EventType() string
type MessageRepository ¶ added in v0.125.0
type MessageRepository interface {
AddMessage(msg ConversationEntry) error
GetMessages() []ConversationEntry
Clear() error
ClearExceptFirstUserMessage() error
GetMessageCount() int
UpdateLastMessage(content string) error
UpdateLastMessageToolCalls(toolCalls *[]sdk.ChatCompletionMessageToolCall) error
DeleteMessagesAfterIndex(index int) error
}
MessageRepository handles CRUD operations for conversation messages
type MessageSnapshot ¶ added in v0.91.0
type MessageSnapshot struct {
Index int `json:"index"`
Role sdk.MessageRole `json:"role"`
Content string `json:"content"`
Timestamp time.Time `json:"timestamp"`
TruncatedMsg string `json:"truncated_msg"`
}
MessageSnapshot represents a snapshot of a message for the history view
type ModelCostStats ¶ added in v0.86.0
type ModelCostStats struct {
Model string
InputTokens int
OutputTokens int
InputCost float64
OutputCost float64
TotalCost float64
RequestCount int
}
ModelCostStats tracks cost statistics for a specific model within a session. This allows detailed breakdown when multiple models are used in the same conversation.
type ModelSelectedEvent ¶ added in v0.45.0
type ModelSelectedEvent struct {
Model string
}
ModelSelectedEvent indicates model selection
type ModelService ¶
type ModelService interface {
ListModels(ctx context.Context) ([]string, error)
SelectModel(modelID string) error
GetCurrentModel() string
IsModelAvailable(modelID string) bool
ValidateModel(modelID string) error
}
ModelService handles model selection and information
type MouseClickToolResult ¶ added in v0.96.0
type MouseClickToolResult struct {
Button string `json:"button"`
Clicks int `json:"clicks"`
X int `json:"x"`
Y int `json:"y"`
Display string `json:"display"`
Method string `json:"method"`
}
MouseClickToolResult represents the result of a mouse click operation
type MouseMoveToolResult ¶ added in v0.96.0
type MouseMoveToolResult struct {
FromX int `json:"from_x"`
FromY int `json:"from_y"`
ToX int `json:"to_x"`
ToY int `json:"to_y"`
Display string `json:"display"`
Method string `json:"method"`
}
MouseMoveToolResult represents the result of a mouse move operation
type MoveIndicatorEvent ¶ added in v0.96.0
type MoveIndicatorEvent struct {
BaseChatEvent
FromX int `json:"FromX"`
FromY int `json:"FromY"`
ToX int `json:"ToX"`
ToY int `json:"ToY"`
MoveIndicator bool `json:"MoveIndicator"`
}
MoveIndicatorEvent indicates a visual move indicator should be shown at coordinates
type MultiEditToolResult ¶ added in v0.22.0
type MultiEditToolResult struct {
FilePath string `json:"file_path"`
Edits []EditOperationResult `json:"edits"`
TotalEdits int `json:"total_edits"`
SuccessfulEdits int `json:"successful_edits"`
FileModified bool `json:"file_modified"`
OriginalSize int64 `json:"original_size"`
NewSize int64 `json:"new_size"`
BytesDifference int64 `json:"bytes_difference"`
NormalizedEdits int `json:"normalized_edits,omitempty"`
}
MultiEditToolResult represents the result of a MultiEdit operation
type NavigateBackInTimeEvent ¶ added in v0.91.0
type NavigateBackInTimeEvent struct {
}
NavigateBackInTimeEvent triggers the message history selector view
func (NavigateBackInTimeEvent) GetRequestID ¶ added in v0.91.0
func (e NavigateBackInTimeEvent) GetRequestID() string
func (NavigateBackInTimeEvent) GetTimestamp ¶ added in v0.91.0
func (e NavigateBackInTimeEvent) GetTimestamp() time.Time
type NoopUINotifier ¶ added in v0.126.0
type NoopUINotifier struct{}
NoopUINotifier is the useful zero value: producers can always call Notify even before the program exists or after shutdown, with no nil checks. The container defaults to it until cmd/chat.go swaps in the real (program-backed) notifier.
func (NoopUINotifier) Notify ¶ added in v0.126.0
func (NoopUINotifier) Notify(any)
Notify discards the event.
type NotifierFunc ¶ added in v0.126.0
type NotifierFunc func(event any)
NotifierFunc adapts a plain function to UINotifier. Tests use it to record the events a producer pushes without a generated mock.
func (NotifierFunc) Notify ¶ added in v0.126.0
func (f NotifierFunc) Notify(event any)
Notify forwards to the wrapped function when non-nil.
type OptimizationStatusEvent ¶ added in v0.48.0
type OptimizationStatusEvent struct {
RequestID string
Timestamp time.Time
Message string
IsActive bool
OriginalCount int
OptimizedCount int
}
OptimizationStatusEvent indicates conversation optimization status
func (OptimizationStatusEvent) GetRequestID ¶ added in v0.48.0
func (e OptimizationStatusEvent) GetRequestID() string
func (OptimizationStatusEvent) GetTimestamp ¶ added in v0.48.0
func (e OptimizationStatusEvent) GetTimestamp() time.Time
type OutboundMessage ¶ added in v0.101.0
type OutboundMessage struct {
ChannelName string `json:"channel_name"`
RecipientID string `json:"recipient_id"`
Content string `json:"content"`
Buttons []MessageButton `json:"buttons,omitempty"`
Timestamp time.Time `json:"timestamp"`
Metadata map[string]string `json:"metadata,omitempty"`
}
OutboundMessage represents a response to send back through a channel
type OutputRingBuffer ¶ added in v0.81.0
type OutputRingBuffer interface {
Write(p []byte) (n int, err error)
ReadFrom(offset int64) (string, int64)
Recent(maxBytes int) string
TotalWritten() int64
Size() int
String() string
Clear()
}
OutputRingBuffer defines the interface for the circular output buffer.
type PaneObservation ¶ added in v0.126.0
type PaneObservation struct {
// Harvested is the subagent chat's real last assistant message (from its
// result file); "" until its turn completes. The ONLY content ever delivered -
// the pane is never scraped for content (its TUI chrome is noise).
Harvested string
// Screen is a snapshot of the pane's current tail, used by the poller to detect
// idleness by stability: while the subagent works the chat's elapsed-time
// spinner changes this every poll; at idle it is frozen. The input-box
// placeholder ("Type your message") is NOT a usable idle signal - it is drawn
// even mid-turn - so the stability of the whole tail is used instead.
Screen string
// Gone means the pane no longer exists (closed).
Gone bool
// Dead means the pane's process exited (the pane is kept open by remain-on-exit).
Dead bool
// AwaitingApproval means the subagent is blocked on a tool-approval prompt.
AwaitingApproval bool
// ApprovalSummary describes the pending tool call (name + args) when awaiting.
ApprovalSummary string
}
PaneObservation is one probe of an interactive subagent's tmux pane, produced by a pane inspector and consumed by the interactive subagent monitor (interactiveSubagentJob) to decide when a turn completed or an approval is pending.
type PendingToolCallManager ¶ added in v0.125.0
type PendingToolCallManager interface {
RemovePendingToolCallByID(toolCallID string)
}
PendingToolCallManager handles pending tool call tracking
type PlanApprovalAction ¶ added in v0.68.0
type PlanApprovalAction int
PlanApprovalAction represents the user's choice for plan approval
const ( PlanApprovalAccept PlanApprovalAction = iota PlanApprovalReject PlanApprovalAcceptStandard )
func (PlanApprovalAction) String ¶ added in v0.68.0
func (a PlanApprovalAction) String() string
type PlanApprovalRequestedEvent ¶ added in v0.68.0
type PlanApprovalRequestedEvent struct {
RequestID string
Timestamp time.Time
PlanContent string
PlanID string
ResponseChan chan PlanApprovalAction `json:"-"`
}
PlanApprovalRequestedEvent indicates plan mode completion requires user approval
func (PlanApprovalRequestedEvent) GetRequestID ¶ added in v0.68.0
func (e PlanApprovalRequestedEvent) GetRequestID() string
func (PlanApprovalRequestedEvent) GetTimestamp ¶ added in v0.68.0
func (e PlanApprovalRequestedEvent) GetTimestamp() time.Time
type PlanApprovalResponseEvent ¶ added in v0.68.0
type PlanApprovalResponseEvent struct {
Action PlanApprovalAction
}
PlanApprovalResponseEvent captures the user's plan approval decision
type PlanApprovalSelectionChangedEvent ¶ added in v0.105.0
type PlanApprovalSelectionChangedEvent struct {
NewIndex int
}
PlanApprovalSelectionChangedEvent signals that the plan-approval button selection has moved and the conversation viewport needs to re-render so the highlighted button reflects the new index.
type PlanApprovalStatus ¶ added in v0.68.0
type PlanApprovalStatus int
PlanApprovalStatus represents the approval status of a plan
const ( PlanApprovalPending PlanApprovalStatus = iota PlanApprovalAccepted PlanApprovalRejected )
type PlanApprovalUIManager ¶ added in v0.125.0
type PlanApprovalUIManager interface {
SetupPlanApprovalUIState(planContent, planID string, responseChan chan PlanApprovalAction)
GetPlanApprovalUIState() *PlanApprovalUIState
SetPlanApprovalSelectedIndex(index int)
ClearPlanApprovalUIState()
}
PlanApprovalUIManager handles plan approval UI state
type PlanApprovalUIState ¶ added in v0.68.0
type PlanApprovalUIState struct {
SelectedIndex int `json:"selected_index"`
PlanContent string `json:"plan_content"`
PlanID string `json:"plan_id"`
ResponseChan chan PlanApprovalAction `json:"-"`
}
PlanApprovalUIState represents the state of plan approval UI
type PricingService ¶ added in v0.86.0
type PricingService interface {
// IsEnabled returns whether pricing is enabled in the configuration.
IsEnabled() bool
// GetInputPrice retrieves the input price per million tokens for a specific model.
// Returns 0.0 for unknown models (e.g., Ollama, custom models).
GetInputPrice(model string) float64
// GetOutputPrice retrieves the output price per million tokens for a specific model.
// Returns 0.0 for unknown models (e.g., Ollama, custom models).
GetOutputPrice(model string) float64
// CalculateCost computes the total cost for a given number of input and
// output tokens. cachedTokens and cacheWriteTokens are the cache-read and
// cache-creation subsets of inputTokens, billed at the gateway's
// cache-read/cache-write rates when known (full input rate otherwise).
CalculateCost(model string, inputTokens, outputTokens, cachedTokens, cacheWriteTokens int) (inputCost, outputCost, totalCost float64)
// RequiresPro reports whether the model is gated behind a paid Pro
// subscription (e.g. some Ollama Cloud models). Resolves custom prices
// first, then defaults. Returns false when pricing is disabled or the
// model has no entry.
RequiresPro(model string) bool
// FormatModelPricing returns a formatted string describing the model's pricing.
// Returns empty string if pricing is disabled or the model has no pricing entry.
// Returns "free" only when an explicit pricing entry sets both prices to 0.0.
// Returns "$X.XX/$Y.YY per MTok" for paid models.
FormatModelPricing(model string) string
}
PricingService provides pricing information and cost calculation for different models. Note: This interface returns float64 for pricing to avoid import cycles. The actual ModelPricing struct is defined in the config package.
type QueuedMessage ¶ added in v0.53.0
QueuedMessage represents a message in the input queue
type RateLimiter ¶ added in v0.96.0
type RateLimiter interface {
// CheckAndRecord checks if the action is within rate limits and records it
CheckAndRecord(toolName string) error
// GetCurrentCount returns the number of actions in the current window
GetCurrentCount() int
// Reset clears all recorded actions
Reset()
}
RateLimiter defines the interface for rate limiting computer use actions
type RefreshAutocompleteEvent ¶ added in v0.76.2
type RefreshAutocompleteEvent struct{}
RefreshAutocompleteEvent is sent when autocomplete needs to refresh (e.g., after mode change)
type ReminderQuery ¶ added in v0.125.0
type ReminderQuery struct {
Hook HookPoint
Turn int
SessionTurn int
MaxTurns int
Fired map[string]bool
ToolFailed bool
ModeChanged bool
PrevMode AgentMode
Mode AgentMode
}
ReminderQuery carries the context a SystemReminderProvider needs to decide which reminders are due at a hook point.
Turn and SessionTurn differ deliberately. Turn is the agent-loop turn within the CURRENT run (one user message in chat), used by the turns_before_max trigger relative to MaxTurns. SessionTurn is the cumulative model-turn count across the whole chat session - it does NOT reset when a new user message starts a fresh run, so the `interval` trigger fires on every Nth conversational turn as users expect (per-request Turns would reset to 1 each message and an interval reminder would essentially never fire in chat). In headless `infer agent` a single invocation IS the session, so the two are equal.
Fired carries reminder names already emitted this session (consulted by the `once` trigger); the caller marks names fired after injecting.
ToolFailed reports whether the tool batch that just completed had any failed call. It is meaningful only at the post_tool hook (set right before that dispatch) and drives the `on_failure` trigger.
ModeChanged reports whether the agent mode differs from the previous streaming turn; PrevMode/Mode carry the transition. They are meaningful only at the pre_stream hook (set right before that dispatch) and drive the `on_mode_change` trigger.
type RestoreStatusStateEvent ¶ added in v0.99.2
type RestoreStatusStateEvent struct{}
RestoreStatusStateEvent restores a previously saved status state
type RetryStatus ¶ added in v0.142.0
RetryStatus tracks the current retry state for reconnection attempts. A nil *RetryStatus means no retry is in progress.
type RolloverCompletedEvent ¶ added in v0.114.0
type RolloverCompletedEvent struct {
Message sdk.Message
Images []ImageAttachment
}
RolloverCompletedEvent is dispatched when an asynchronous auto-rollover finishes in chat mode. It carries the already-built sdk.Message + images that were pending while the summary LLM call was in flight, so the post-rollover handler can resume the deferred AddMessage + start-chat completion flow without re-parsing user input.
type RunContainerOptions ¶ added in v0.82.0
type RunContainerOptions struct {
Name string
Image string
Network string
Ports []string // Format: "host:container" or "host:container/protocol"
Environment map[string]string
Volumes []string // Format: "host:container" or "host:container:mode"
Entrypoint []string
Command []string
Args []string
HealthCmd string
HealthConfig *HealthCheckConfig
RemoveOnExit bool
Detached bool
EnvFile string // Optional .env file path
}
RunContainerOptions contains all options for running a container
type SaveStatusStateEvent ¶ added in v0.99.2
type SaveStatusStateEvent struct{}
SaveStatusStateEvent saves the current status state for later restoration
type ScheduledJob ¶ added in v0.104.0
type ScheduledJob struct {
ID string `yaml:"id" json:"id"`
Name string `yaml:"name,omitempty" json:"name,omitempty"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
CronExpression string `yaml:"cron_expression" json:"cron_expression"`
Prompt string `yaml:"prompt" json:"prompt"`
Channel string `yaml:"channel" json:"channel"`
RecipientID string `yaml:"recipient_id" json:"recipient_id"`
Model string `yaml:"model,omitempty" json:"model,omitempty"`
RunOnce bool `yaml:"run_once,omitempty" json:"run_once,omitempty"`
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
UpdatedAt time.Time `yaml:"updated_at" json:"updated_at"`
LastRun *time.Time `yaml:"last_run,omitempty" json:"last_run,omitempty"`
LastError string `yaml:"last_error,omitempty" json:"last_error,omitempty"`
}
ScheduledJob describes a recurring task that the LLM has asked the system to run on a cron schedule. Jobs are persisted as YAML files and loaded by the SchedulerService running inside the channels-manager daemon.
Each fire spawns a fresh `infer agent` subprocess with a brand-new session ID - no context is carried between fires, matching the issue's requirement.
type SchedulerService ¶ added in v0.104.0
type SchedulerService interface {
Start(ctx context.Context) error
Stop(ctx context.Context) error
LoadJobs() error
}
SchedulerService manages the lifecycle of scheduled jobs. It is started by the channels-manager daemon and watches the schedule storage directory for changes so that jobs created by an agent process are picked up without a daemon restart.
type ScreenRegion ¶ added in v0.96.0
type ScreenRegion struct {
X int `json:"x"`
Y int `json:"y"`
Width int `json:"width"`
Height int `json:"height"`
}
ScreenRegion represents a rectangular region of the screen
type Screenshot ¶ added in v0.96.0
type Screenshot struct {
ID string `json:"id"`
Timestamp time.Time `json:"timestamp"`
Data string `json:"data"` // base64 encoded image
Width int `json:"width"` // Final image width (after scaling)
Height int `json:"height"` // Final image height (after scaling)
Format string `json:"format"` // "png" or "jpeg"
Method string `json:"method"` // "x11" or "wayland"
OriginalWidth int `json:"original_width"` // Screen width before scaling
OriginalHeight int `json:"original_height"` // Screen height before scaling
}
Screenshot represents a captured screenshot with metadata
type ScreenshotProvider ¶ added in v0.96.0
type ScreenshotProvider interface {
GetLatestScreenshot() (*Screenshot, error)
}
ScreenshotProvider defines the interface for getting screenshots from a buffer
type ScreenshotToolResult ¶ added in v0.96.0
type ScreenshotToolResult struct {
Display string `json:"display"`
Region *ScreenRegion `json:"region,omitempty"`
Width int `json:"width"`
Height int `json:"height"`
Format string `json:"format"`
Method string `json:"method"`
}
ScreenshotToolResult represents the result of a screenshot capture
type ScrollDirection ¶ added in v0.45.0
type ScrollDirection int
ScrollDirection defines scroll direction
const ( ScrollUp ScrollDirection = iota ScrollDown ScrollLeft ScrollRight ScrollToTop ScrollToBottom )
type ScrollRequestEvent ¶ added in v0.45.0
type ScrollRequestEvent struct {
ComponentID string
Direction ScrollDirection
Amount int
}
ScrollRequestEvent requests scrolling in a component
type SessionCostStats ¶ added in v0.86.0
type SessionCostStats struct {
TotalCost float64
TotalInputCost float64
TotalOutputCost float64
PerModelStats map[string]*ModelCostStats
Currency string
}
SessionCostStats aggregates cost information for an entire session. It provides both total costs and per-model breakdowns.
type SessionID ¶ added in v0.82.0
type SessionID string
SessionID represents a unique identifier for a chat session. Format: {unix-timestamp}-{8-char-random-hex} Example: 1733678400-a3f2bc8d
func GenerateSessionID ¶ added in v0.82.0
func GenerateSessionID() SessionID
GenerateSessionID creates a new unique session identifier. The ID combines a Unix timestamp (for temporal uniqueness) with random hex characters (for collision resistance).
func (SessionID) Age ¶ added in v0.82.0
Age returns the duration since the session was created. Returns 0 if the session ID format is invalid.
type SessionTokenStats ¶ added in v0.28.0
type SessionTokenStats struct {
TotalInputTokens int `json:"total_input_tokens"`
TotalOutputTokens int `json:"total_output_tokens"`
TotalTokens int `json:"total_tokens"`
RequestCount int `json:"request_count"`
LastInputTokens int `json:"last_input_tokens"`
TotalCachedTokens int `json:"total_cached_tokens"`
TotalCacheWriteTokens int `json:"total_cache_write_tokens"`
}
SessionTokenStats tracks accumulated token usage across a session
type SetInputEvent ¶ added in v0.45.0
type SetInputEvent struct {
Text string
}
SetInputEvent sets text in the input field
type SetStatusEvent ¶ added in v0.45.0
type SetStatusEvent struct {
Message string
Spinner bool
StatusType StatusType
Progress *StatusProgress
ToolName string
}
SetStatusEvent sets a status message
type SetupFileSelectionEvent ¶ added in v0.45.0
type SetupFileSelectionEvent struct {
Files []string
}
SetupFileSelectionEvent sets up file selection state with files
type ShellCancelledEvent ¶ added in v0.81.0
ShellCancelledEvent indicates a background shell was killed
func (ShellCancelledEvent) GetRequestID ¶ added in v0.81.0
func (e ShellCancelledEvent) GetRequestID() string
func (ShellCancelledEvent) GetTimestamp ¶ added in v0.81.0
func (e ShellCancelledEvent) GetTimestamp() time.Time
type ShellCompletedEvent ¶ added in v0.81.0
type ShellCompletedEvent struct {
RequestID string
Timestamp time.Time
ShellID string
ExitCode int
Duration time.Duration
}
ShellCompletedEvent indicates a background shell finished successfully
func (ShellCompletedEvent) GetRequestID ¶ added in v0.81.0
func (e ShellCompletedEvent) GetRequestID() string
func (ShellCompletedEvent) GetTimestamp ¶ added in v0.81.0
func (e ShellCompletedEvent) GetTimestamp() time.Time
type ShellDetachedEvent ¶ added in v0.81.0
type ShellDetachedEvent struct {
RequestID string
Timestamp time.Time
ShellID string
Command string
}
ShellDetachedEvent indicates a Bash command has been moved to background
func (ShellDetachedEvent) GetRequestID ¶ added in v0.81.0
func (e ShellDetachedEvent) GetRequestID() string
func (ShellDetachedEvent) GetTimestamp ¶ added in v0.81.0
func (e ShellDetachedEvent) GetTimestamp() time.Time
type ShellFailedEvent ¶ added in v0.81.0
type ShellFailedEvent struct {
RequestID string
Timestamp time.Time
ShellID string
Error string
ExitCode int
}
ShellFailedEvent indicates a background shell failed
func (ShellFailedEvent) GetRequestID ¶ added in v0.81.0
func (e ShellFailedEvent) GetRequestID() string
func (ShellFailedEvent) GetTimestamp ¶ added in v0.81.0
func (e ShellFailedEvent) GetTimestamp() time.Time
type ShellInfo ¶ added in v0.81.0
type ShellInfo struct {
ShellID string
Command string
State ShellState
StartedAt time.Time
CompletedAt *time.Time
ExitCode *int
OutputSize int64
Elapsed time.Duration
}
ShellInfo provides summary information about a shell for UI display.
func NewShellInfo ¶ added in v0.81.0
func NewShellInfo(shell *BackgroundShell) *ShellInfo
NewShellInfo creates a ShellInfo from a BackgroundShell.
type ShellState ¶ added in v0.81.0
type ShellState string
ShellState represents the state of a background shell.
const ( ShellStateRunning ShellState = "running" ShellStateCompleted ShellState = "completed" ShellStateFailed ShellState = "failed" ShellStateCancelled ShellState = "cancelled" )
func (ShellState) IsTerminal ¶ added in v0.81.0
func (s ShellState) IsTerminal() bool
IsTerminal returns true if the state is a terminal state (completed, failed, or cancelled).
func (ShellState) String ¶ added in v0.81.0
func (s ShellState) String() string
String returns the string representation of the shell state.
type ShellTracker ¶ added in v0.81.0
type ShellTracker interface {
// Add adds a new shell to the tracker.
// Returns an error if max concurrent limit is reached.
Add(shell *BackgroundShell) error
// Get retrieves a shell by ID.
// Returns nil if not found.
Get(shellID string) *BackgroundShell
// GetAll returns all tracked shells.
GetAll() []*BackgroundShell
// Remove removes a shell from the tracker.
Remove(shellID string) error
// CountRunning returns the number of shells in running state.
CountRunning() int
}
ShellTracker defines the interface for managing background shells.
type ShowErrorEvent ¶ added in v0.45.0
ShowErrorEvent displays an error message
type Skill ¶ added in v0.109.0
type Skill struct {
Name string
Description string
Path string
Scope SkillScope
PluginName string
}
Skill is the in-memory metadata for a discovered SKILL.md. The body of the file is intentionally not loaded at startup - only frontmatter - so the model reads it on demand via the existing Read tool (progressive disclosure, matching the contract).
func (Skill) DisplayName ¶ added in v0.142.0
DisplayName returns the qualified name for display. Plugin skills are shown as "pluginName:skillName" so the user/LLM can reference them unambiguously.
type SkillLoadError ¶ added in v0.109.0
SkillLoadError records a per-skill validation failure so `infer skills list` can surface why a directory was skipped without crashing startup.
type SkillScope ¶ added in v0.109.0
type SkillScope string
SkillScope identifies where a skill came from: the project (.infer/skills/), the open-standard location (.agents/skills/), the user-global location (~/.infer/skills/), an installed plugin (~/.infer/plugins/<name>/skills/), or the centralized catalog (dynamically discovered at runtime).
const ( SkillScopeProject SkillScope = "project" SkillScopeAgents SkillScope = "agents" SkillScopeUser SkillScope = "user" SkillScopePlugin SkillScope = "plugin" SkillScopeCatalog SkillScope = "catalog" )
type SkillsService ¶ added in v0.109.0
type SkillsService interface {
// Load scans the configured skill directories and populates the
// in-memory list. Safe to call once at startup; calling again rescans.
// Returns nil and does nothing when skills are disabled in config.
Load(ctx context.Context) error
// List returns the currently loaded skills. The slice is a defensive
// copy - callers may retain or mutate it freely.
List() []Skill
// Get returns the loaded skill with the given name and true, or a zero
// Skill and false when no such skill is loaded. Used by deterministic
// activation to resolve an explicitly invoked skill name to its metadata
// (description + path) for injection.
Get(name string) (Skill, bool)
// Errors returns validation failures encountered during the most recent
// Load. Cleared on each Load call.
Errors() []SkillLoadError
// Discover looks up a skill by name in the centralized catalog when
// progressive discovery is enabled and no local skill of that name
// exists. Returns the skill metadata (name, description, path) and
// true on success, or a zero Skill and false when the skill is not
// found in the catalog or discovery is disabled. The skill body is
// fetched only when the skill is actually activated (progressive).
// Local skills always take precedence - if a skill with the same name
// is already loaded, no catalog lookup is performed.
Discover(ctx context.Context, name string) (Skill, bool)
// CleanupDynamic removes dynamically downloaded skills from disk.
// When cleanup is enabled in config, this is called after the session
// ends to remove any skills that were fetched from the catalog.
CleanupDynamic(ctx context.Context) error
}
SkillsService discovers and exposes Agent Skills. Implementations must be safe for concurrent reads after Load returns.
type StartStreamingEvent ¶ added in v0.99.2
type StartStreamingEvent struct{}
StartStreamingEvent is triggered when the agent should start streaming
func (StartStreamingEvent) EventType ¶ added in v0.99.2
func (e StartStreamingEvent) EventType() string
type StateAction ¶ added in v0.99.2
type StateAction func(ctx *AgentContext) error
StateAction is a function executed on state transitions
type StateContext ¶ added in v0.99.2
type StateContext struct {
// Core dependencies
StateMachine AgentStateMachine
AgentCtx *AgentContext
// Event communication
Events chan AgentEvent
// Concurrency control
WaitGroup *sync.WaitGroup
CancelChan <-chan struct{}
Mutex *sync.Mutex
// Shared state data
CurrentMessage *sdk.Message
CurrentToolCalls *[]*sdk.ChatCompletionMessageToolCall
CurrentReasoning *string
AvailableTools *[]sdk.ChatCompletionTool
// Tool processing state
ToolsNeedingApproval *[]sdk.ChatCompletionMessageToolCall
CurrentToolIndex *int
ToolResults *[]ConversationEntry
// Request context
Request *AgentRequest
BackgroundTaskRegistry BackgroundTaskRegistry
Provider string
Model string
// MaxConcurrentTools bounds how many approved tools may execute concurrently
// while later tools are still being approved.
MaxConcurrentTools int
// Function callbacks
ToolExecutor *func()
StartStreaming func()
// Helper methods - these will be implemented as methods that delegate to internal service
GetMetrics func(requestID string) *ChatMetrics
ShouldRequireApproval func(toolCall *sdk.ChatCompletionMessageToolCall, isChatMode bool) bool
ApprovalDelivery func(toolCall *sdk.ChatCompletionMessageToolCall) string
AddMessage func(entry ConversationEntry) error
BatchDrainQueue func() int
RequestToolApproval func(toolCall sdk.ChatCompletionMessageToolCall) (bool, error)
ExecuteToolInternal func(toolCall sdk.ChatCompletionMessageToolCall, isApproved bool) ConversationEntry
GetAgentMode func() AgentMode
PublishChatEvent func(event ChatEvent)
PublishChatComplete func(reasoning string, toolCalls []sdk.ChatCompletionMessageToolCall, metrics *ChatMetrics)
PublishChatCancelled func(metrics *ChatMetrics)
// DispatchHooks runs the actions attached to a hook point. State executors call it
// at their loop point; the streaming path calls the service directly.
DispatchHooks func(hook HookPoint)
}
StateContext provides access to agent dependencies for state handlers
type StateGuard ¶ added in v0.99.2
type StateGuard func(ctx *AgentContext) bool
StateGuard is a function that determines if a state transition should occur
type StateHandler ¶ added in v0.99.2
type StateHandler interface {
Handle(event AgentEvent) error
Name() AgentExecutionState
}
StateHandler defines the interface for handling events in a specific state
type StatusProgress ¶ added in v0.45.0
StatusProgress represents progress information for status messages
type StatusType ¶ added in v0.45.0
type StatusType int
StatusType represents different types of status messages
const ( StatusDefault StatusType = iota StatusThinking StatusGenerating StatusWorking StatusProcessing StatusPreparing StatusError )
type StreamCompletedEvent ¶ added in v0.99.2
type StreamCompletedEvent struct {
Message sdk.Message
ToolCalls []*sdk.ChatCompletionMessageToolCall
Reasoning string
Usage *sdk.CompletionUsage
IterationStartTime time.Time
}
StreamCompletedEvent is triggered when LLM streaming completes
func (StreamCompletedEvent) EventType ¶ added in v0.99.2
func (e StreamCompletedEvent) EventType() string
type StreamingContentEvent ¶ added in v0.48.0
type StreamingContentEvent struct {
RequestID string
Content string
ReasoningContent string
Delta bool
Model string
}
StreamingContentEvent delivers live streaming content for immediate UI display
type SubagentApprovalFile ¶ added in v0.126.0
type SubagentApprovalFile struct {
Awaiting bool `json:"awaiting"`
Summary string `json:"summary,omitempty"`
}
SubagentApprovalFile is the JSON an interactive subagent's chat writes while it is blocked on a tool-approval prompt. It is an authoritative signal (written the moment the chat blocks, removed when it resolves) so the parent does not have to scrape the pane's TUI to detect a pending approval.
type SubagentCompletedEvent ¶ added in v0.124.0
type SubagentCompletedEvent struct {
RequestID string
Timestamp time.Time
SubagentID string
Label string
Result ToolExecutionResult
}
SubagentCompletedEvent indicates a local subagent completed successfully
func (SubagentCompletedEvent) GetRequestID ¶ added in v0.124.0
func (e SubagentCompletedEvent) GetRequestID() string
func (SubagentCompletedEvent) GetTimestamp ¶ added in v0.124.0
func (e SubagentCompletedEvent) GetTimestamp() time.Time
type SubagentFailedEvent ¶ added in v0.124.0
type SubagentFailedEvent struct {
RequestID string
Timestamp time.Time
SubagentID string
Label string
Result ToolExecutionResult
Error string
}
SubagentFailedEvent indicates a local subagent failed
func (SubagentFailedEvent) GetRequestID ¶ added in v0.124.0
func (e SubagentFailedEvent) GetRequestID() string
func (SubagentFailedEvent) GetTimestamp ¶ added in v0.124.0
func (e SubagentFailedEvent) GetTimestamp() time.Time
type SubagentResultFile ¶ added in v0.124.0
type SubagentResultFile struct {
FinalAssistant string `json:"final_assistant"`
Success bool `json:"success"`
Error string `json:"error,omitempty"`
SessionID string `json:"session_id,omitempty"`
}
SubagentResultFile is the JSON written by `infer agent --result-file` on exit and read back by the Agent tool to harvest a subagent's outcome from a detached (tmux) run whose stdout the parent does not own.
type SubagentState ¶ added in v0.124.0
type SubagentState struct {
ID string
Label string
Description string
Model string
Mode string // SubagentModeHeadless | SubagentModeInteractive
SessionID string
PaneID string
Status SubagentStatus
StartedAt time.Time
CancelFunc context.CancelFunc
Silent bool
}
SubagentState is the data record for one local subagent (an `infer agent` subprocess or tmux pane spawned by the Agent tool) that the subagent control tools (ListSubagents, CloseSubagent, ...) read. Monitoring is owned by the job supervisor (headlessSubagentJob / interactiveSubagentJob), not this struct.
type SubagentStatus ¶ added in v0.124.0
type SubagentStatus string
SubagentStatus represents the lifecycle state of a local subagent.
const ( SubagentRunning SubagentStatus = "running" SubagentCompleted SubagentStatus = "completed" SubagentFailed SubagentStatus = "failed" )
type SubagentSubmittedEvent ¶ added in v0.124.0
type SubagentSubmittedEvent struct {
RequestID string
Timestamp time.Time
SubagentID string
Label string
}
SubagentSubmittedEvent indicates a local subagent was dispatched
func (SubagentSubmittedEvent) GetRequestID ¶ added in v0.124.0
func (e SubagentSubmittedEvent) GetRequestID() string
func (SubagentSubmittedEvent) GetTimestamp ¶ added in v0.124.0
func (e SubagentSubmittedEvent) GetTimestamp() time.Time
type SubagentTracker ¶ added in v0.124.0
type SubagentTracker interface {
// AddSubagent registers a running subagent. Returns an error if the ID
// is already tracked.
AddSubagent(state *SubagentState) error
// GetSubagent returns a subagent by ID, or nil if not tracked.
GetSubagent(id string) *SubagentState
// GetAllSubagents returns all tracked subagents.
GetAllSubagents() []*SubagentState
// RemoveSubagent removes a subagent from tracking.
RemoveSubagent(id string) error
// CountRunningSubagents returns the number of subagents in the running state.
CountRunningSubagents() int
// SetSubagentStatus atomically updates a subagent's status under the
// tracker's lock. Returns an error if the ID is not tracked.
SetSubagentStatus(id string, status SubagentStatus) error
}
SubagentTracker tracks local subagents spawned by the Agent tool. It is the third projection of BackgroundTaskRegistry (alongside A2ATaskTracker and ShellTracker); methods are suffixed with "Subagent" to avoid colliding with the shell tracker's same-named surface when embedded together.
type SystemReminder ¶ added in v0.125.0
SystemReminder is a resolved reminder ready to inject into the conversation.
type SystemReminderProvider ¶ added in v0.125.0
type SystemReminderProvider interface {
RemindersDue(q ReminderQuery) []SystemReminder
}
SystemReminderProvider decides which system reminders are due for a given ReminderQuery (hook point, per-run turn, cumulative session turn, max turns, and the already-fired set). It is implemented by config from the user's reminders list; the agent depends on this interface so reminder policy can be faked in tests.
type TaskCancelledEvent ¶ added in v0.53.3
TaskCancelledEvent indicates a task has been cancelled
type TaskInfo ¶ added in v0.53.3
type TaskInfo struct {
// ADK Task contains: ID, ContextID, Status (with State), History, Artifacts, Metadata
Task adk.Task
// UI-specific fields
AgentURL string
StartedAt time.Time
CompletedAt time.Time
}
TaskInfo wraps ADK Task with UI-specific metadata for completed/terminal tasks Used for A2A task retention and display
type TaskPollingState ¶ added in v0.53.0
type TaskPollingState struct {
TaskID string
ContextID string
AgentURL string
TaskDescription string
IsPolling bool
StartedAt time.Time
LastKnownState string
}
TaskPollingState is the data record for one in-flight A2A task that the task view reads. Monitoring is owned by the job supervisor (a2aJob), which polls the remote agent and updates LastKnownState here.
type TaskRetainer ¶ added in v0.126.0
type TaskRetainer interface {
RetainedTask(result ToolExecutionResult) (TaskInfo, bool)
}
TaskRetainer is an optional BackgroundJob extension. A job that implements it contributes a TaskInfo to the A2A task-retention view when it reaches a terminal state, so a completed/failed/canceled task stays listed in the task view after its monitor goroutine exits (the supervisor drops it from the live "active" set on finish). ok=false opts out (e.g. a non-terminal-for-retention state such as input-required). Jobs that do not implement it are never retained.
type TaskRetentionService ¶ added in v0.53.3
type TaskRetentionService interface {
// AddTask adds a terminal task (completed, failed, canceled, etc.) to retention
AddTask(task TaskInfo)
// GetTasks returns all retained tasks
GetTasks() []TaskInfo
// Clear removes all retained tasks
Clear()
// SetMaxRetention updates the maximum retention count
SetMaxRetention(maxRetention int)
// GetMaxRetention returns the current maximum retention count
GetMaxRetention() int
}
TaskRetentionService manages in-memory retention of completed/terminal A2A tasks Only enabled when A2A is enabled - decouples task retention from StateManager
type TasksLoadedEvent ¶ added in v0.53.3
TasksLoadedEvent indicates tasks have been loaded
type Theme ¶ added in v0.47.0
type Theme interface {
GetUserColor() string
GetAssistantColor() string
GetErrorColor() string
GetSuccessColor() string
GetStatusColor() string
GetAccentColor() string
GetDimColor() string
GetBorderColor() string
GetDiffAddColor() string
GetDiffRemoveColor() string
}
Theme interface for theming support
type ThemeProvider ¶ added in v0.47.0
type ThemeProvider struct {
// contains filtered or unexported fields
}
ThemeProvider implements ThemeService and manages available themes
func NewThemeProvider ¶ added in v0.47.0
func NewThemeProvider() *ThemeProvider
NewThemeProvider creates a new theme provider with default themes
func (*ThemeProvider) GetCurrentTheme ¶ added in v0.47.0
func (tp *ThemeProvider) GetCurrentTheme() Theme
GetCurrentTheme returns the currently active theme (implements ThemeService interface)
func (*ThemeProvider) GetCurrentThemeName ¶ added in v0.47.0
func (tp *ThemeProvider) GetCurrentThemeName() string
GetCurrentThemeName returns the name of the currently active theme (implements ThemeService interface)
func (*ThemeProvider) GetTheme ¶ added in v0.47.0
func (tp *ThemeProvider) GetTheme(name string) (Theme, error)
GetTheme returns the theme by name, or the current theme if name is empty
func (*ThemeProvider) ListThemes ¶ added in v0.47.0
func (tp *ThemeProvider) ListThemes() []string
ListThemes returns all available theme names (implements ThemeService interface)
func (*ThemeProvider) SetCurrentTheme ¶ added in v0.47.0
func (tp *ThemeProvider) SetCurrentTheme(name string) error
SetCurrentTheme is an alias for SetTheme for backward compatibility
func (*ThemeProvider) SetTheme ¶ added in v0.47.0
func (tp *ThemeProvider) SetTheme(name string) error
SetTheme sets the current theme by name (implements ThemeService interface)
type ThemeSelectedEvent ¶ added in v0.47.0
type ThemeSelectedEvent struct {
Theme string
}
ThemeSelectedEvent indicates theme selection
type ThemeService ¶ added in v0.47.0
type ThemeService interface {
ListThemes() []string
GetCurrentTheme() Theme
GetCurrentThemeName() string
SetTheme(themeName string) error
}
ThemeService handles theme management
type TodoItem ¶ added in v0.20.0
type TodoItem struct {
ID string `json:"id"`
Content string `json:"content"`
Status string `json:"status"`
}
TodoItem represents a single todo item
type TodoManager ¶ added in v0.125.0
TodoManager handles todo list state
type TodoUpdateChatEvent ¶ added in v0.63.1
type TodoUpdateChatEvent struct {
BaseChatEvent
Todos []TodoItem
}
TodoUpdateChatEvent indicates the todo list has been updated (flows through chat event channel)
type TodoUpdateEvent ¶ added in v0.63.1
type TodoUpdateEvent struct {
Todos []TodoItem
}
TodoUpdateEvent indicates the todo list has been updated
type TodoWriteToolResult ¶ added in v0.20.0
type TodoWriteToolResult struct {
Todos []TodoItem `json:"todos"`
TotalTasks int `json:"total_tasks"`
CompletedTasks int `json:"completed_tasks"`
InProgressTask string `json:"in_progress_task,omitempty"`
ValidationOK bool `json:"validation_ok"`
}
TodoWriteToolResult represents the result of a TodoWrite operation
type ToggleHelpBarEvent ¶ added in v0.45.0
type ToggleHelpBarEvent struct{}
ToggleHelpBarEvent toggles the help bar visibility
type ToggleTodoBoxEvent ¶ added in v0.63.1
type ToggleTodoBoxEvent struct{}
ToggleTodoBoxEvent toggles the todo box expanded/collapsed state
type TokenEstimator ¶ added in v0.81.0
type TokenEstimator interface {
// GetToolStats returns token count and tool count for a given agent mode
GetToolStats(toolService ToolService, agentMode AgentMode) (tokens int, count int)
// EstimateMessagesTokens estimates the total tokens for a slice of messages
EstimateMessagesTokens(messages []sdk.Message) int
// EffectiveContextTokens estimates what the *next* request will carry: the
// larger of the gateway-reported last-request size and a fresh estimate of
// the current buffer. The max catches a single-turn tool-output spike that a
// stale lastInputTokens alone would miss.
EffectiveContextTokens(lastInputTokens int, messages []sdk.Message) int
}
TokenEstimator provides token count estimation for LLM content
type TokenUsageRepository ¶ added in v0.125.0
type TokenUsageRepository interface {
AddTokenUsage(model string, inputTokens, outputTokens, totalTokens, cachedTokens, cacheWriteTokens int) error
AddCachedTokens(tokens int)
GetSessionTokens() SessionTokenStats
GetSessionCostStats() SessionCostStats
}
TokenUsageRepository handles token usage tracking
type TokyoNightTheme ¶ added in v0.47.0
type TokyoNightTheme struct{}
TokyoNightTheme is the default theme (same as DefaultTheme)
func NewTokyoNightTheme ¶ added in v0.47.0
func NewTokyoNightTheme() *TokyoNightTheme
func (*TokyoNightTheme) GetAccentColor ¶ added in v0.47.0
func (t *TokyoNightTheme) GetAccentColor() string
func (*TokyoNightTheme) GetAssistantColor ¶ added in v0.47.0
func (t *TokyoNightTheme) GetAssistantColor() string
func (*TokyoNightTheme) GetBorderColor ¶ added in v0.47.0
func (t *TokyoNightTheme) GetBorderColor() string
func (*TokyoNightTheme) GetDiffAddColor ¶ added in v0.47.0
func (t *TokyoNightTheme) GetDiffAddColor() string
func (*TokyoNightTheme) GetDiffRemoveColor ¶ added in v0.47.0
func (t *TokyoNightTheme) GetDiffRemoveColor() string
func (*TokyoNightTheme) GetDimColor ¶ added in v0.47.0
func (t *TokyoNightTheme) GetDimColor() string
func (*TokyoNightTheme) GetErrorColor ¶ added in v0.47.0
func (t *TokyoNightTheme) GetErrorColor() string
func (*TokyoNightTheme) GetStatusColor ¶ added in v0.47.0
func (t *TokyoNightTheme) GetStatusColor() string
func (*TokyoNightTheme) GetSuccessColor ¶ added in v0.56.0
func (t *TokyoNightTheme) GetSuccessColor() string
func (*TokyoNightTheme) GetUserColor ¶ added in v0.47.0
func (t *TokyoNightTheme) GetUserColor() string
type Tool ¶ added in v0.14.1
type Tool interface {
// Definition returns the tool definition for the LLM
Definition() sdk.ChatCompletionTool
// Execute runs the tool with given arguments
Execute(ctx context.Context, args map[string]any) (*ToolExecutionResult, error)
// Validate checks if the tool arguments are valid
Validate(args map[string]any) error
// IsEnabled returns whether this tool is enabled
IsEnabled() bool
// FormatResult formats tool execution results for different contexts
FormatResult(result *ToolExecutionResult, formatType FormatterType) string
// FormatPreview returns a short preview of the result for UI display
FormatPreview(result *ToolExecutionResult) string
// ShouldCollapseArg determines if an argument should be collapsed in display
ShouldCollapseArg(key string) bool
// ShouldAlwaysExpand determines if tool results should always be expanded in UI
ShouldAlwaysExpand() bool
}
Tool represents a single tool with its definition, handler, and validator
type ToolApprovalNotificationEvent ¶ added in v0.96.0
type ToolApprovalNotificationEvent struct {
RequestID string
Timestamp time.Time
ToolName string
Message string
}
ToolApprovalNotificationEvent is sent to notify the Computer Use dialog when tool approval is required in TUI
func (ToolApprovalNotificationEvent) GetRequestID ¶ added in v0.96.0
func (e ToolApprovalNotificationEvent) GetRequestID() string
func (ToolApprovalNotificationEvent) GetTimestamp ¶ added in v0.96.0
func (e ToolApprovalNotificationEvent) GetTimestamp() time.Time
type ToolApprovalRequestedEvent ¶ added in v0.56.0
type ToolApprovalRequestedEvent struct {
RequestID string
Timestamp time.Time
ToolCall sdk.ChatCompletionMessageToolCall
ResponseChan chan ApprovalAction `json:"-"`
}
ToolApprovalRequestedEvent is used for standard tool approval workflow. Computer-use tools use a separate pause/resume mechanism.
func (ToolApprovalRequestedEvent) GetRequestID ¶ added in v0.56.0
func (e ToolApprovalRequestedEvent) GetRequestID() string
func (ToolApprovalRequestedEvent) GetTimestamp ¶ added in v0.56.0
func (e ToolApprovalRequestedEvent) GetTimestamp() time.Time
type ToolApprovalResponseEvent ¶ added in v0.45.0
type ToolApprovalResponseEvent struct {
Action ApprovalAction
ToolCall sdk.ChatCompletionMessageToolCall
}
ToolApprovalResponseEvent captures the user's approval decision
type ToolApprovalStatus ¶ added in v0.68.0
type ToolApprovalStatus int
ToolApprovalStatus represents the approval status of a tool
const ( ToolApprovalPending ToolApprovalStatus = iota ToolApprovalApproved ToolApprovalRejected )
type ToolCall ¶ added in v0.27.0
type ToolCall struct {
ID string `json:"id"`
Name string `json:"name"`
Arguments map[string]any `json:"arguments"`
Status ToolCallStatus `json:"status"`
Result *ToolExecutionResult `json:"result,omitempty"`
StartTime time.Time `json:"start_time"`
EndTime *time.Time `json:"end_time,omitempty"`
}
ToolCall represents a tool call with proper typing
type ToolCallPreviewEvent ¶ added in v0.48.0
type ToolCallPreviewEvent struct {
RequestID string
Timestamp time.Time
ToolCallID string
ToolName string
Arguments string
Status ToolCallStreamStatus
IsComplete bool
}
ToolCallPreviewEvent shows a tool call as it's being streamed (before execution)
func (ToolCallPreviewEvent) GetRequestID ¶ added in v0.48.0
func (e ToolCallPreviewEvent) GetRequestID() string
func (ToolCallPreviewEvent) GetTimestamp ¶ added in v0.48.0
func (e ToolCallPreviewEvent) GetTimestamp() time.Time
type ToolCallReadyEvent ¶ added in v0.48.0
type ToolCallReadyEvent struct {
RequestID string
Timestamp time.Time
ToolCalls []sdk.ChatCompletionMessageToolCall
}
ToolCallReadyEvent indicates all tool calls are ready for approval/execution
func (ToolCallReadyEvent) GetRequestID ¶ added in v0.48.0
func (e ToolCallReadyEvent) GetRequestID() string
func (ToolCallReadyEvent) GetTimestamp ¶ added in v0.48.0
func (e ToolCallReadyEvent) GetTimestamp() time.Time
type ToolCallStatus ¶ added in v0.27.0
type ToolCallStatus int
ToolCallStatus represents the status of an individual tool call
const ( ToolCallStatusPending ToolCallStatus = iota ToolCallStatusWaitingApproval ToolCallStatusExecuting ToolCallStatusCompleted ToolCallStatusFailed ToolCallStatusCancelled ToolCallStatusDenied )
func (ToolCallStatus) String ¶ added in v0.27.0
func (t ToolCallStatus) String() string
type ToolCallStreamStatus ¶ added in v0.48.0
type ToolCallStreamStatus string
ToolCallStreamStatus represents the status of a tool call during streaming
const ( ToolCallStreamStatusStreaming ToolCallStreamStatus = "streaming" ToolCallStreamStatusComplete ToolCallStreamStatus = "completed" ToolCallStreamStatusReady ToolCallStreamStatus = "ready" )
type ToolCallUpdateEvent ¶ added in v0.48.0
type ToolCallUpdateEvent struct {
RequestID string
Timestamp time.Time
ToolCallID string
ToolName string
Arguments string
Status ToolCallStreamStatus
}
ToolCallUpdateEvent updates a streaming tool call with new content
func (ToolCallUpdateEvent) GetRequestID ¶ added in v0.48.0
func (e ToolCallUpdateEvent) GetRequestID() string
func (ToolCallUpdateEvent) GetTimestamp ¶ added in v0.48.0
func (e ToolCallUpdateEvent) GetTimestamp() time.Time
type ToolCancelledEvent ¶ added in v0.110.1
type ToolCancelledEvent struct {
RequestID string
Timestamp time.Time
ToolCallID string
ToolName string
}
ToolCancelledEvent is published when the conversation validator synthesizes a Tool-role response for an assistant tool_call whose real execution never completed (typically because the user pressed Esc between the model emitting tool_calls and the tools running). The conversation view uses this to surface a "[cancelled]" entry so the user understands why a requested tool never produced output.
func (ToolCancelledEvent) GetRequestID ¶ added in v0.110.1
func (e ToolCancelledEvent) GetRequestID() string
func (ToolCancelledEvent) GetTimestamp ¶ added in v0.110.1
func (e ToolCancelledEvent) GetTimestamp() time.Time
type ToolExecutionCompletedEvent ¶ added in v0.45.0
type ToolExecutionCompletedEvent struct {
SessionID string
RequestID string
Timestamp time.Time
TotalExecuted int
SuccessCount int
FailureCount int
Results []*ToolExecutionResult
}
ToolExecutionCompletedEvent indicates tool execution is complete
func (ToolExecutionCompletedEvent) GetRequestID ¶ added in v0.99.1
func (e ToolExecutionCompletedEvent) GetRequestID() string
func (ToolExecutionCompletedEvent) GetTimestamp ¶ added in v0.99.1
func (e ToolExecutionCompletedEvent) GetTimestamp() time.Time
type ToolExecutionCoordinator ¶ added in v0.112.3
type ToolExecutionCoordinator interface {
ActiveToolTracker
HandleToolCallUpdate(msg ToolCallUpdateEvent) tea.Cmd
HandleToolCallReady(msg ToolCallReadyEvent) tea.Cmd
HandleToolApprovalRequested(msg ToolApprovalRequestedEvent) tea.Cmd
HandleToolApprovalResponse(msg ToolApprovalResponseEvent) tea.Cmd
HandleToolExecutionStarted(msg ToolExecutionStartedEvent) tea.Cmd
HandleToolExecutionProgress(msg ToolExecutionProgressEvent) tea.Cmd
HandleToolExecutionCompleted(msg ToolExecutionCompletedEvent) tea.Cmd
HandleToolCancelled(msg ToolCancelledEvent) tea.Cmd
}
ToolExecutionCoordinator owns the tool round-trip: streaming-status updates emitted while the model is producing a tool call, approval coordination (forwarding the user's decision back to the agent), and execution-progress events while the tool runs. Also owns the active-tool-call indicator the UI uses to render the in-flight tool name.
type ToolExecutionManager ¶ added in v0.125.0
type ToolExecutionManager interface {
StartToolExecution(toolCalls []sdk.ChatCompletionMessageToolCall) error
CompleteCurrentTool(result *ToolExecutionResult) error
FailCurrentTool(result *ToolExecutionResult) error
EndToolExecution()
GetToolExecution() *ToolExecutionSession
}
ToolExecutionManager handles tool execution sessions
type ToolExecutionProgressEvent ¶ added in v0.45.0
type ToolExecutionProgressEvent struct {
BaseChatEvent
ToolCallID string
ToolName string
Arguments string
Status string
Message string
Images []ImageAttachment
}
ToolExecutionProgressEvent indicates progress in tool execution
type ToolExecutionResult ¶ added in v0.13.1
type ToolExecutionResult struct {
ToolName string `json:"tool_name"`
Arguments map[string]any `json:"arguments"`
Success bool `json:"success"`
Duration time.Duration `json:"duration"`
Error string `json:"error,omitempty"`
Data any `json:"data,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
Diff string `json:"diff,omitempty"`
Rejected bool `json:"rejected,omitempty"`
Images []ImageAttachment `json:"images,omitempty"`
}
ToolExecutionResult represents the complete result of a tool execution
type ToolExecutionSession ¶ added in v0.27.0
type ToolExecutionSession struct {
CurrentTool *ToolCall
RemainingTools []ToolCall
TotalTools int
CompletedTools int
Status ToolExecutionStatus
StartTime time.Time
}
ToolExecutionSession represents an active tool execution session
type ToolExecutionStartedEvent ¶ added in v0.45.0
ToolExecutionStartedEvent indicates tool execution has started
type ToolExecutionStatus ¶ added in v0.27.0
type ToolExecutionStatus int
ToolExecutionStatus represents the overall tool execution session status
const ( ToolExecutionStatusIdle ToolExecutionStatus = iota ToolExecutionStatusProcessing ToolExecutionStatusExecuting ToolExecutionStatusCompleted ToolExecutionStatusFailed )
func (ToolExecutionStatus) String ¶ added in v0.27.0
func (t ToolExecutionStatus) String() string
type ToolFormatter ¶ added in v0.33.4
type ToolFormatter interface {
// FormatToolCall formats a tool call for consistent display
FormatToolCall(toolName string, args map[string]any) string
// RenderToolSummary renders the shared "<icon> Name(args) <trailing>" line used by
// the collapsed status line, live preview, approval summary and queue preview.
RenderToolSummary(icon, toolName string, args map[string]any, trailing string, terminalWidth int) string
// FormatToolResultForUI formats tool execution results for UI display
FormatToolResultForUI(result *ToolExecutionResult, terminalWidth int) string
// FormatToolResultExpanded formats expanded tool execution results
FormatToolResultExpanded(result *ToolExecutionResult, terminalWidth int) string
// FormatToolResultForLLM formats tool execution results for LLM consumption
FormatToolResultForLLM(result *ToolExecutionResult) string
// ShouldAlwaysExpandTool checks if a tool result should always be expanded
ShouldAlwaysExpandTool(toolName string) bool
}
ToolFormatter provides formatting capabilities for tool results
type ToolResultFormatter ¶ added in v0.125.0
type ToolResultFormatter interface {
FormatToolResultForLLM(result *ToolExecutionResult) string
FormatToolResultForUI(result *ToolExecutionResult, terminalWidth int) string
FormatToolResultExpanded(result *ToolExecutionResult, terminalWidth int) string
}
ToolResultFormatter handles formatting tool execution results
type ToolService ¶
type ToolService interface {
ListTools() []sdk.ChatCompletionTool
ListToolsForMode(mode AgentMode) []sdk.ChatCompletionTool
ListAvailableTools() []string
ExecuteTool(ctx context.Context, tool sdk.ChatCompletionMessageToolCallFunction) (*ToolExecutionResult, error)
ExecuteToolDirect(ctx context.Context, tool sdk.ChatCompletionMessageToolCallFunction) (*ToolExecutionResult, error)
IsToolEnabled(name string) bool
ValidateTool(name string, args map[string]any) error
GetA2ATaskTracker() A2ATaskTracker
GetTool(name string) (Tool, error)
}
ToolService handles tool execution
type ToolsCompletedEvent ¶ added in v0.99.2
type ToolsCompletedEvent struct {
Results []ConversationEntry
Stop bool
}
ToolsCompletedEvent is triggered when all tools finish executing. Stop is set when the results signal the loop should terminate (a rejected tool or a successful RequestPlanApproval); the ExecutingTools state then routes to the Stopped terminal instead of continuing to PostToolExecution.
func (ToolsCompletedEvent) EventType ¶ added in v0.99.2
func (e ToolsCompletedEvent) EventType() string
type TrackedJob ¶ added in v0.126.0
type TrackedJob struct {
Meta JobMeta
Status JobStatus
CompletedAt *time.Time
LastNote string
Output string
}
TrackedJob is a point-in-time snapshot of one supervised job for the task view and status line.
type TreeToolResult ¶ added in v0.16.0
type TreeToolResult struct {
Path string `json:"path"`
Output string `json:"output"`
TotalFiles int `json:"total_files"`
TotalDirs int `json:"total_dirs"`
MaxDepth int `json:"max_depth"`
MaxFiles int `json:"max_files"`
ShowHidden bool `json:"show_hidden"`
Format string `json:"format"`
UsingNativeTree bool `json:"using_native_tree"`
Truncated bool `json:"truncated"`
}
TreeToolResult represents the result of a tree operation
type TriggerGithubActionSetupEvent ¶ added in v0.87.0
type TriggerGithubActionSetupEvent struct{}
TriggerGithubActionSetupEvent triggers the GitHub App setup flow
type TriggerHelpViewEvent ¶ added in v0.118.0
type TriggerHelpViewEvent struct{}
TriggerHelpViewEvent opens the full-screen, scrollable help overlay that lists every slash command and keybinding in two tables.
type UINotifier ¶ added in v0.126.0
type UINotifier interface {
Notify(event any)
}
UINotifier delivers a background-originated event to the single Bubble Tea Update loop. It is the one ingress every background producer uses to push work or status changes into the UI, replacing the per-source self-rescheduling pollers. The only production implementation wraps (*tea.Program).Send and lives in cmd/chat.go; keeping this interface tea-free lets services depend on it without importing bubbletea. The event is an `any` (tea.Msg is itself `any`).
type UpdateHistoryEvent ¶ added in v0.45.0
type UpdateHistoryEvent struct {
History []ConversationEntry
}
UpdateHistoryEvent updates the conversation history display
type UpdateStatusEvent ¶ added in v0.45.0
type UpdateStatusEvent struct {
Message string
StatusType StatusType
ToolName string
}
UpdateStatusEvent updates an existing status message without resetting timer
type UserInputEvent ¶ added in v0.45.0
type UserInputEvent struct {
Content string
Images []ImageAttachment
}
UserInputEvent represents user input submission
type UserQuestion ¶ added in v0.124.0
type UserQuestion struct {
Header string `json:"header"`
Question string `json:"question"`
Options []UserQuestionOption `json:"options"`
MultiSelect bool `json:"multiSelect"`
}
UserQuestion is one clarifying question the agent asks the user via the AskUserQuestion tool. It mirrors the tool schema: a short header chip, the question text, 2-4 options, and whether multiple options may be selected.
type UserQuestionAnswer ¶ added in v0.124.0
type UserQuestionAnswer struct {
Header string `json:"header"`
Question string `json:"question"`
SelectedLabels []string `json:"selectedLabels"`
OtherText string `json:"otherText,omitempty"`
}
UserQuestionAnswer is the user's response to one UserQuestion. SelectedLabels holds the chosen option label(s); OtherText is non-empty when the user picked the synthesized "Other" free-text choice (it may coexist with selected labels in multi-select). Header and Question are echoed so the tool result is self-describing for the model.
type UserQuestionBroker ¶ added in v0.124.0
type UserQuestionBroker interface {
AskUserQuestions(ctx context.Context, questions []UserQuestion) (answers []UserQuestionAnswer, ok bool, err error)
}
UserQuestionBroker publishes an interactive clarifying-question request to the TUI and blocks until the user answers or the context is cancelled. It is injected into the AskUserQuestion tool's execution context only on the chat path (where a TTY/event loop exists). Returns ok=false when the user dismisses the form (the response channel is closed without a value) or on cancellation.
func GetUserQuestionBroker ¶ added in v0.124.0
func GetUserQuestionBroker(ctx context.Context) UserQuestionBroker
GetUserQuestionBroker retrieves the question broker from context. Returns nil if the key is not set or the value is not a UserQuestionBroker.
type UserQuestionOption ¶ added in v0.124.0
type UserQuestionOption struct {
Label string `json:"label"`
Description string `json:"description"`
}
UserQuestionOption is a single selectable choice within a UserQuestion.
type UserQuestionRequestedEvent ¶ added in v0.124.0
type UserQuestionRequestedEvent struct {
RequestID string
Timestamp time.Time
Questions []UserQuestion
ResponseChan chan []UserQuestionAnswer `json:"-"`
}
UserQuestionRequestedEvent is published when the AskUserQuestion tool asks the user one or more interactive clarifying questions. ResponseChan delivers the collected answers back to the blocked tool goroutine; closing it without a value signals cancellation.
func (UserQuestionRequestedEvent) GetRequestID ¶ added in v0.124.0
func (e UserQuestionRequestedEvent) GetRequestID() string
func (UserQuestionRequestedEvent) GetTimestamp ¶ added in v0.124.0
func (e UserQuestionRequestedEvent) GetTimestamp() time.Time
type UserQuestionUIManager ¶ added in v0.125.0
type UserQuestionUIManager interface {
SetupUserQuestionUIState(questions []UserQuestion, responseChan chan []UserQuestionAnswer)
GetUserQuestionUIState() *UserQuestionUIState
ClearUserQuestionUIState()
}
UserQuestionUIManager handles AskUserQuestion form state
type UserQuestionUIState ¶ added in v0.124.0
type UserQuestionUIState struct {
Questions []UserQuestion `json:"questions"`
ResponseChan chan []UserQuestionAnswer `json:"-"`
}
UserQuestionUIState drives the interactive AskUserQuestion form. The agent loop is blocked in the tool goroutine while the form is up; the answer-in-progress state lives in the QuestionFormView's huh form. ResponseChan delivers the final answers slice back to the blocked tool; closing it without a send signals cancellation.
type VersionInfo ¶ added in v0.85.0
type VersionInfo struct {
Version string
}
VersionInfo contains build-time version information
type ViewManager ¶ added in v0.125.0
type ViewManager interface {
GetCurrentView() ViewState
GetPreviousView() ViewState
TransitionToView(newView ViewState) error
}
ViewManager handles view state transitions
type ViewState ¶ added in v0.27.0
type ViewState int
ViewState represents the current view with proper state management
const ( ViewStateModelSelection ViewState = iota ViewStateChat ViewStateFileSelection ViewStateConversationSelection ViewStateThemeSelection ViewStateA2ATaskManagement ViewStatePlanApproval ViewStateGithubActionSetup ViewStateDiffViewer ViewStateExplorer ViewStateHelp ViewStateToolsList ViewStateA2AAgents )
type WebFetchService ¶ added in v0.29.2
type WebFetchService interface {
ValidateURL(url string) error
FetchContent(ctx context.Context, target string) (*FetchResult, error)
ClearCache()
GetCacheStats() map[string]any
}
WebFetchService handles content fetching operations
type WebSearchResponse ¶ added in v0.13.0
type WebSearchResponse struct {
Query string `json:"query"`
Engine string `json:"engine"`
Results []WebSearchResult `json:"results"`
Total int `json:"total"`
Time time.Duration `json:"time"`
Error string `json:"error,omitempty"`
}
WebSearchResponse represents the complete search response
type WebSearchResult ¶ added in v0.13.0
type WebSearchResult struct {
Title string `json:"title"`
URL string `json:"url"`
Snippet string `json:"snippet"`
}
WebSearchResult represents a single search result
type WebSearchService ¶ added in v0.13.0
type WebSearchService interface {
SearchGoogle(ctx context.Context, query string, maxResults int) (*WebSearchResponse, error)
SearchDuckDuckGo(ctx context.Context, query string, maxResults int) (*WebSearchResponse, error)
IsEnabled() bool
SetEnabled(enabled bool)
}
WebSearchService handles web search operations
type WindSignal ¶ added in v0.126.0
type WindSignal int
WindSignal is the one-directional graceful control signal the supervisor pushes into a running job. WindWrapUp asks it to start finishing (inject a wind-down prompt, SIGTERM, or cancel the remote task); WindStop terminates it now (kill pane, SIGKILL, cancel). Graceful shutdown sends WindWrapUp to all jobs, waits a grace window, then WindStop. The supervisor also uses WindStop as the teardown when it reaps a finished job.
const ( WindWrapUp WindSignal = iota WindStop )
func (WindSignal) String ¶ added in v0.126.0
func (w WindSignal) String() string
String renders the signal for logs.
Source Files
¶
- agent.go
- agent_events.go
- approval_policy.go
- background_job.go
- chat_events.go
- container_runtime.go
- context.go
- context_helpers.go
- conversation.go
- events.go
- formatter.go
- hooks.go
- interfaces.go
- ipc.go
- pricing.go
- scheduler.go
- session.go
- shell.go
- skills.go
- state.go
- subagent.go
- theme_provider.go
- token_estimator.go
- tools.go
- ui_events.go
- ui_notifier.go
- user_question.go
- version.go