Documentation
¶
Index ¶
- Variables
- func AnnotationText(a *ImageAnnotation) string
- func BashAllowModeKey(ctx context.Context) 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 ImageFileRef(path string, supportsVision bool) string
- func ImagePathNote(img ImageAttachment) string
- func IsDirectExecution(ctx context.Context) bool
- func IsToolApproved(ctx context.Context) bool
- func SandboxApprovalAvailable(ctx context.Context) 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 WithSandboxApprovalAvailable(ctx context.Context, available bool) 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 A2ATaskCompletedEvent
- type A2ATaskFailedEvent
- type A2ATaskInputRequiredEvent
- type A2ATaskStatusUpdateEvent
- type A2ATaskSubmittedEvent
- type A2ATaskTracker
- type A2AToolCallExecutedEvent
- type AgentManager
- type AgentMode
- type AgentModeManager
- type AgentRequest
- type AgentService
- type AgentState
- type AnnotateOptions
- type AnnotatedElement
- type ApprovalAction
- type ApprovalPolicy
- type ApprovalUIManager
- type ApprovalUIState
- type BackgroundShellRequestEvent
- type BackgroundTasksChangedEvent
- type BaseChatEvent
- type BashDetachChannelHolder
- type BashOutputCallback
- type BashOutputChunkEvent
- type BashToolResult
- type ChatChunkEvent
- type ChatCompleteEvent
- type ChatErrorEvent
- type ChatEvent
- type ChatMetrics
- type ChatSession
- type ChatSessionManager
- type ChatStartEvent
- type ChatStatus
- type ChatSyncResponse
- type ComputerUsePauseManager
- type ComputerUsePausedEvent
- type ComputerUseResumedEvent
- type ContextKey
- type DeleteToolResult
- type DrainQueueEvent
- type EditOperationResult
- type EditToolResult
- type EventBridge
- type EventBridgeManager
- type FetchResult
- type FileInfo
- type FileReadToolResult
- type FileService
- type FileWriteToolResult
- type FormatterType
- type Frame
- type FrameSource
- type FrameToolResult
- type GitHubIssue
- type GitHubIssueComment
- type GitHubIssueService
- type GitHubSetupService
- type HookCommand
- type HookCommandProvider
- type HookPoint
- type ImageAnnotation
- type ImageAnnotator
- type ImageAttachment
- type ImageService
- type MCPClient
- type MCPDiscoveredTool
- type MCPManager
- type MCPServerEntry
- type MCPServerStatus
- type MCPServerStatusUpdateEvent
- type MCPToolResult
- type MessageEditSubmitEvent
- type MessageHistoryRestoreEvent
- type MessageQueuedEvent
- type MultiEditToolResult
- type NavigateBackInTimeEvent
- type NoopUINotifier
- type OptimizationStatusEvent
- type PlanApprovalAction
- type PlanApprovalRequestedEvent
- type PlanApprovalUIManager
- type PlanApprovalUIState
- type RefreshAutocompleteEvent
- type ReminderQuery
- type RetryStatus
- type ScreenRegion
- type ShellCancelledEvent
- type ShellCompletedEvent
- type ShellDetachedEvent
- type ShellFailedEvent
- type Skill
- type SkillLoadError
- type SkillScope
- type SkillSummary
- type SkillsService
- type SubagentCompletedEvent
- type SubagentFailedEvent
- type SubagentSubmittedEvent
- type SystemReminder
- type SystemReminderProvider
- type TaskPollingState
- type TodoItem
- type TodoManager
- type TodoUpdateChatEvent
- type TodoWriteToolResult
- type Tool
- type ToolApprovalNotificationEvent
- type ToolApprovalRequestedEvent
- type ToolApprovalResolvedEvent
- type ToolApprovalResponseEvent
- type ToolCall
- type ToolCallPreviewEvent
- type ToolCallReadyEvent
- type ToolCallStatus
- type ToolCallStreamStatus
- type ToolCallUpdateEvent
- type ToolCancelledEvent
- type ToolExecutionCompletedEvent
- type ToolExecutionManager
- type ToolExecutionProgressEvent
- type ToolExecutionResult
- type ToolExecutionSession
- type ToolExecutionStatus
- type ToolFormatter
- type ToolService
- type TreeToolResult
- type UINotifier
- type UserInputEvent
- type UserQuestion
- type UserQuestionAnswer
- type UserQuestionBroker
- type UserQuestionOption
- type UserQuestionRequestedEvent
- type UserQuestionUIManager
- type UserQuestionUIState
- type WebSearchResponse
- type WebSearchResult
Constants ¶
This section is empty.
Variables ¶
var ErrMaxTurnsReached = errors.New("max_turns_reached")
ErrMaxTurnsReached is returned when the agent reaches its maximum turn limit without completing the task. Callers should use errors.Is to check for it.
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 AnnotationText ¶
func AnnotationText(a *ImageAnnotation) string
AnnotationText renders an ImageAnnotation as the canonical LLM-facing text: a one-line summary followed by the numbered element list with centers and bounding boxes. Every consumer (tools, chat, headless) uses this one shape.
func BashAllowModeKey ¶
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 GetBashDetachChannel ¶
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 ¶
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 ¶
GetToolCallID retrieves the tool call id from context
func GetTraceEnv ¶
GetTraceEnv retrieves the subprocess trace environment from context
func HasBashDetachChannel ¶
HasBashDetachChannel checks if a bash detach channel is set in the context
func HasBashOutputCallback ¶
HasBashOutputCallback checks if a bash output callback is set in the context
func HasChatHandler ¶
HasChatHandler checks if a ChatHandler is set in the context
func HasSessionID ¶
HasSessionID checks if a session ID is set in the context
func HasUserQuestionBroker ¶
HasUserQuestionBroker checks if a question broker is set in the context.
func ImageFileRef ¶
ImageFileRef returns the inline text substituted for an image file reference (chat "@path" or headless --files): images are never sent as raw base64 — the model reaches them through image tools instead. Non-vision models are additionally pointed at ImageDecode for a text description.
func ImagePathNote ¶
func ImagePathNote(img ImageAttachment) string
ImagePathNote returns a text note pointing at an attached image's on-disk source, so models without vision can inspect it via ImageDecode. Returns "" when the image has no source path.
func IsDirectExecution ¶
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 ¶
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 SandboxApprovalAvailable ¶ added in v0.180.0
SandboxApprovalAvailable reports whether a sandbox-extension prompt can be answered by a user in this run. Defaults to false when unset.
func WithAgentMode ¶
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 ¶
WithBashDetachChannel returns a new context with a bash detach signal channel
func WithBashOutputCallback ¶
func WithBashOutputCallback(ctx context.Context, callback BashOutputCallback) context.Context
WithBashOutputCallback returns a new context with a bash output streaming callback
func WithChatHandler ¶
func WithChatHandler(ctx context.Context, handler BashDetachChannelHolder) context.Context
WithChatHandler returns a new context with a ChatHandler reference
func WithDirectExecution ¶
WithDirectExecution returns a new context with DirectExecutionKey set to true
func WithModel ¶
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 WithSandboxApprovalAvailable ¶ added in v0.180.0
WithSandboxApprovalAvailable marks whether a user can answer a sandbox-extension prompt in this run.
func WithSessionID ¶
WithSessionID returns a new context with a session ID
func WithToolApproved ¶
WithToolApproved returns a new context with ToolApprovedKey set to true
func WithToolCallID ¶
WithToolCallID returns a new context with the LLM tool call id
func WithTraceEnv ¶
WithTraceEnv returns a new context with the subprocess trace environment
func WithUserQuestionBroker ¶
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 A2ATaskCompletedEvent ¶
type A2ATaskCompletedEvent struct {
RequestID string
Timestamp time.Time
TaskID string
Result ToolExecutionResult
}
A2ATaskCompletedEvent indicates an A2A task was completed successfully
func (A2ATaskCompletedEvent) GetRequestID ¶
func (e A2ATaskCompletedEvent) GetRequestID() string
func (A2ATaskCompletedEvent) GetTimestamp ¶
func (e A2ATaskCompletedEvent) GetTimestamp() time.Time
type A2ATaskFailedEvent ¶
type A2ATaskFailedEvent struct {
RequestID string
Timestamp time.Time
TaskID string
Result ToolExecutionResult
Error string
}
A2ATaskFailedEvent indicates an A2A task failed
func (A2ATaskFailedEvent) GetRequestID ¶
func (e A2ATaskFailedEvent) GetRequestID() string
func (A2ATaskFailedEvent) GetTimestamp ¶
func (e A2ATaskFailedEvent) GetTimestamp() time.Time
type A2ATaskInputRequiredEvent ¶
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 ¶
func (e A2ATaskInputRequiredEvent) GetRequestID() string
func (A2ATaskInputRequiredEvent) GetTimestamp ¶
func (e A2ATaskInputRequiredEvent) GetTimestamp() time.Time
type A2ATaskStatusUpdateEvent ¶
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 ¶
func (e A2ATaskStatusUpdateEvent) GetRequestID() string
func (A2ATaskStatusUpdateEvent) GetTimestamp ¶
func (e A2ATaskStatusUpdateEvent) GetTimestamp() time.Time
type A2ATaskSubmittedEvent ¶
type A2ATaskSubmittedEvent struct {
RequestID string
Timestamp time.Time
TaskID string
AgentName string
AgentURL string
}
A2ATaskSubmittedEvent indicates an A2A task was submitted
func (A2ATaskSubmittedEvent) GetRequestID ¶
func (e A2ATaskSubmittedEvent) GetRequestID() string
func (A2ATaskSubmittedEvent) GetTimestamp ¶
func (e A2ATaskSubmittedEvent) GetTimestamp() time.Time
type A2ATaskTracker ¶
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 ¶
type A2AToolCallExecutedEvent struct {
RequestID string
Timestamp time.Time
ToolCallID string
ToolName string
Arguments string
TaskID string
}
A2AToolCallExecutedEvent indicates an A2A tool call was executed on the gateway
func (A2AToolCallExecutedEvent) GetRequestID ¶
func (e A2AToolCallExecutedEvent) GetRequestID() string
func (A2AToolCallExecutedEvent) GetTimestamp ¶
func (e A2AToolCallExecutedEvent) GetTimestamp() time.Time
type AgentManager ¶
type AgentManager interface {
// StartAgents starts all agents configured with run: true
StartAgents(ctx context.Context) error
// WaitForAgentsReady blocks until every run:true agent started by
// StartAgents has settled (ready or failed), or ctx is done
WaitForAgentsReady(ctx context.Context)
// 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 ¶
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 ¶
AgentModeFromContext returns the agent mode stored in ctx and whether it was present. When absent, callers should default to AgentModeStandard.
func ParseAgentMode ¶
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 ¶
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 ¶
DisplayName returns a user-friendly display name for the mode
type AgentModeManager ¶
type AgentModeManager interface {
GetAgentMode() AgentMode
SetAgentMode(mode AgentMode)
CycleAgentMode() AgentMode
}
AgentModeManager handles agent mode switching
type AgentRequest ¶
type AgentRequest struct {
RequestID string `json:"request_id"`
Model string `json:"model"`
Messages []sdk.Message `json:"messages"`
IsChatMode bool `json:"is_chat_mode"`
ApprovalBrokerAttached bool `json:"approval_broker_attached"`
GroupKey string `json:"group_key,omitempty"`
}
AgentRequest represents a request to the agent service
type AgentService ¶
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)
// RunStreaming executes a single model turn with streaming, invoking onDelta
// for each content/reasoning/tool-call delta, and returns the assembled
// response like Run. For callers that own their own agentic loop (the
// headless AG-UI agent) but want token-level output. onDelta may be nil.
RunStreaming(ctx context.Context, req *AgentRequest, onDelta func(content, reasoning string, toolCalls []sdk.ChatCompletionMessageToolCallChunk)) (*ChatSyncResponse, 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 ¶
type AgentState int
AgentState represents the current state of an agent
const ( AgentStateUnknown AgentState = iota AgentStatePullingImage AgentStateStarting AgentStateWaitingReady AgentStateReady AgentStateFailed )
func (AgentState) DisplayName ¶
func (a AgentState) DisplayName() string
DisplayName returns a user-friendly display name for the agent state
func (AgentState) String ¶
func (a AgentState) String() string
type AnnotateOptions ¶
type AnnotateOptions struct {
Prompt string // task instruction (UI-element detection, scene description, or a user question); "" -> annotator default
Width int // image width in pixels, stated in the prompt and used to rescale normalized coordinates
Height int // image height in pixels
}
AnnotateOptions carries per-call annotation parameters.
type AnnotatedElement ¶
type AnnotatedElement struct {
Index int `json:"index"`
Label string `json:"label"`
Text string `json:"text,omitempty"`
BBox [4]int `json:"bbox"` // [x1, y1, x2, y2] in the image's pixel space
}
AnnotatedElement is one detected element of an annotated image.
type ApprovalAction ¶
type ApprovalAction int
ApprovalAction represents the user's choice for tool approval
const ( ApprovalApprove ApprovalAction = iota ApprovalReject ApprovalAutoAccept )
func (ApprovalAction) String ¶
func (a ApprovalAction) String() string
type ApprovalPolicy ¶
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 ApprovalUIManager ¶
type ApprovalUIManager interface {
SetupApprovalUIState(toolCall *sdk.ChatCompletionMessageToolCall, responseChan chan ApprovalAction)
GetApprovalUIState() *ApprovalUIState
ClearApprovalUIState()
}
ApprovalUIManager handles tool approval UI state
type ApprovalUIState ¶
type ApprovalUIState struct {
PendingToolCall *sdk.ChatCompletionMessageToolCall `json:"pending_tool_call"`
ResponseChan chan ApprovalAction `json:"-"`
}
ApprovalUIState represents the state of approval UI
type BackgroundShellRequestEvent ¶
type BackgroundShellRequestEvent struct{}
BackgroundShellRequestEvent requests that the current running Bash command be moved to background
type BackgroundTasksChangedEvent ¶
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 ¶
BaseChatEvent provides common implementation for ChatEvent interface
func (BaseChatEvent) GetRequestID ¶
func (e BaseChatEvent) GetRequestID() string
func (BaseChatEvent) GetTimestamp ¶
func (e BaseChatEvent) GetTimestamp() time.Time
type BashDetachChannelHolder ¶
type BashDetachChannelHolder interface {
SetBashDetachChan(chan<- struct{})
GetBashDetachChan() chan<- struct{}
ClearBashDetachChan()
}
BashDetachChannelHolder manages the bash detach channel for background shell operations
func GetChatHandler ¶
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 ¶
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 ¶
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 ¶
type BashOutputChunkEvent struct {
BaseChatEvent
ToolCallID string
Output string
IsComplete bool
}
BashOutputChunkEvent indicates a new chunk of bash output is available
type BashToolResult ¶
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 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
// MaxTurnsReached marks a completion forced by the turn limit rather than
// the task finishing; headless renderers map it to ErrMaxTurnsReached.
MaxTurnsReached 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 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 ChatMetrics ¶
type ChatMetrics struct {
Duration time.Duration
Usage *sdk.CompletionUsage
}
ChatMetrics holds performance and usage metrics
type ChatSession ¶
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 ¶
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 ¶
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 ¶
func (c ChatStatus) String() string
type ChatSyncResponse ¶
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"`
FinishReason string `json:"finish_reason,omitempty"`
}
ChatSyncResponse represents a synchronous chat completion response
type ComputerUsePauseManager ¶
type ComputerUsePauseManager interface {
SetComputerUsePaused(paused bool, requestID string)
IsComputerUsePaused() bool
GetPausedRequestID() string
ClearComputerUsePauseState()
}
ComputerUsePauseManager handles computer use pause state
type ComputerUsePausedEvent ¶
ComputerUsePausedEvent indicates computer-use execution has been paused
func (ComputerUsePausedEvent) GetRequestID ¶
func (e ComputerUsePausedEvent) GetRequestID() string
func (ComputerUsePausedEvent) GetTimestamp ¶
func (e ComputerUsePausedEvent) GetTimestamp() time.Time
type ComputerUseResumedEvent ¶
ComputerUseResumedEvent indicates computer-use execution has resumed
func (ComputerUseResumedEvent) GetRequestID ¶
func (e ComputerUseResumedEvent) GetRequestID() string
func (ComputerUseResumedEvent) GetTimestamp ¶
func (e ComputerUseResumedEvent) GetTimestamp() time.Time
type ContextKey ¶
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 SandboxApprovalKey ContextKey = "sandbox_approval"
SandboxApprovalKey is the context key marking that a user can answer a sandbox-extension prompt in this run (chat TUI, or headless with an IPC approval broker attached). When unset, sandbox denials fail as before.
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 DeleteToolResult ¶
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 DrainQueueEvent ¶
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 EditOperationResult ¶
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 ¶
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 ¶
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
// SubscribeFuture is Subscribe without the ring-buffer replay, for
// subscribers that backfill history another way.
SubscribeFuture() 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 the opentask extension bridge)
type EventBridgeManager ¶
type EventBridgeManager interface {
SetEventBridge(bridge EventBridge)
GetEventBridge() EventBridge
BroadcastEvent(event ChatEvent)
}
EventBridgeManager handles event multicast for external event consumers
type FetchResult ¶
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 ¶
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 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 ¶
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"`
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 FormatterType ¶
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 Frame ¶
type Frame struct {
ID string `json:"id"`
Timestamp time.Time `json:"timestamp"`
Data string `json:"data"` // base64 encoded image
Path string `json:"-"` // on-disk path when the frame exists as a file
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"` // capture method, e.g. "x11", "wayland", "directory"
}
Frame represents a captured image frame (screenshot, camera frame, ...) with metadata
type FrameSource ¶
FrameSource provides the most recent frame of a named frame source (the screen ring buffer, a camera directory, ...).
type FrameToolResult ¶
type FrameToolResult struct {
Source string `json:"source,omitempty"`
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"`
Annotated bool `json:"annotated,omitempty"`
Annotation *ImageAnnotation `json:"annotation,omitempty"`
Note string `json:"note,omitempty"` // degrade note, e.g. "annotation unavailable: ..."
}
FrameToolResult represents the result of a frame retrieval
type GitHubIssue ¶
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 ¶
GitHubIssueComment is a single comment on a GitHub issue, sorted by CreatedAt ascending.
type GitHubIssueService ¶
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 ¶
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 HookCommand ¶
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 ¶
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 ¶
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 ImageAnnotation ¶
type ImageAnnotation struct {
Summary string `json:"summary"`
Elements []AnnotatedElement `json:"elements,omitempty"`
}
ImageAnnotation is the structured result of annotating an image: a short scene summary plus a numbered element list. Elements may be empty when the annotator degraded to a plain-text summary.
type ImageAnnotator ¶
type ImageAnnotator interface {
AnnotateImage(ctx context.Context, img ImageAttachment, opts AnnotateOptions) (*ImageAnnotation, error)
}
ImageAnnotator turns an image into text (summary + element list) via a vision model, so text-only session models can understand frames and images.
type ImageAttachment ¶
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 ¶
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
// IsImageModel reports whether the model generates images rather than text
IsImageModel(model string) bool
// GenerateImage generates an image from prompt using model ("provider/name")
// and returns the path of the saved file. A blank quality or size leaves the
// provider's own default
GenerateImage(ctx context.Context, model, prompt, quality, size string) (string, error)
// EditImage edits the image at imagePath using prompt and model
// ("provider/name") and returns the path of the saved file. A blank quality
// or size leaves the provider's own default. A non-empty maskPath points to
// a PNG whose transparent (alpha=0) areas mark the editable region; all
// other pixels are preserved exactly.
EditImage(ctx context.Context, model, prompt, imagePath, quality, size, maskPath string) (string, error)
// CreateImageVariation creates a variation of the image at imagePath using
// model ("provider/name") and returns the path of the saved file. A blank
// size leaves the provider's own default
CreateImageVariation(ctx context.Context, model, imagePath, size string) (string, error)
}
ImageService handles image operations including loading and encoding
type MCPClient ¶
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 ¶
MCPDiscoveredTool represents a tool discovered from an MCP server
type MCPManager ¶
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 ¶
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.178.1
type MCPServerStatus struct {
TotalServers int `json:"total_servers"`
ConnectedServers int `json:"connected_servers"`
TotalTools int `json:"total_tools"`
}
MCPServerStatus is the aggregate connection status the MCP manager reports for the whole server set.
type MCPServerStatusUpdateEvent ¶ added in v0.178.1
type MCPServerStatusUpdateEvent struct {
ServerName string
Connected bool
TotalServers int
ConnectedServers int
TotalTools int
Tools []MCPDiscoveredTool
}
MCPServerStatusUpdateEvent is pushed through the UI notifier whenever a server connects, disconnects, or changes its tool count.
type MCPToolResult ¶
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 MessageEditSubmitEvent ¶
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 ¶
func (e MessageEditSubmitEvent) GetRequestID() string
func (MessageEditSubmitEvent) GetTimestamp ¶
func (e MessageEditSubmitEvent) GetTimestamp() time.Time
type MessageHistoryRestoreEvent ¶
MessageHistoryRestoreEvent is emitted when user selects a restore point in message history
func (MessageHistoryRestoreEvent) GetRequestID ¶
func (e MessageHistoryRestoreEvent) GetRequestID() string
func (MessageHistoryRestoreEvent) GetTimestamp ¶
func (e MessageHistoryRestoreEvent) GetTimestamp() time.Time
type MessageQueuedEvent ¶
MessageQueuedEvent indicates a message was received from the queue and stored
func (MessageQueuedEvent) GetRequestID ¶
func (e MessageQueuedEvent) GetRequestID() string
func (MessageQueuedEvent) GetTimestamp ¶
func (e MessageQueuedEvent) GetTimestamp() time.Time
type MultiEditToolResult ¶
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 ¶
type NavigateBackInTimeEvent struct {
}
NavigateBackInTimeEvent triggers the message history selector view
func (NavigateBackInTimeEvent) GetRequestID ¶
func (e NavigateBackInTimeEvent) GetRequestID() string
func (NavigateBackInTimeEvent) GetTimestamp ¶
func (e NavigateBackInTimeEvent) GetTimestamp() time.Time
type NoopUINotifier ¶
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.
type OptimizationStatusEvent ¶
type OptimizationStatusEvent struct {
RequestID string
Timestamp time.Time
Message string
IsActive bool
OriginalCount int
OptimizedCount int
}
OptimizationStatusEvent indicates conversation optimization status
func (OptimizationStatusEvent) GetRequestID ¶
func (e OptimizationStatusEvent) GetRequestID() string
func (OptimizationStatusEvent) GetTimestamp ¶
func (e OptimizationStatusEvent) GetTimestamp() time.Time
type PlanApprovalAction ¶
type PlanApprovalAction int
PlanApprovalAction represents the user's choice for plan approval
const ( PlanApprovalAccept PlanApprovalAction = iota PlanApprovalReject PlanApprovalAcceptStandard )
func (PlanApprovalAction) String ¶
func (a PlanApprovalAction) String() string
type PlanApprovalRequestedEvent ¶
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 ¶
func (e PlanApprovalRequestedEvent) GetRequestID() string
func (PlanApprovalRequestedEvent) GetTimestamp ¶
func (e PlanApprovalRequestedEvent) GetTimestamp() time.Time
type PlanApprovalUIManager ¶
type PlanApprovalUIManager interface {
SetupPlanApprovalUIState(planContent, planID string, responseChan chan PlanApprovalAction)
GetPlanApprovalUIState() *PlanApprovalUIState
SetPlanApprovalSelectedIndex(index int)
ClearPlanApprovalUIState()
}
PlanApprovalUIManager handles plan approval UI state
type PlanApprovalUIState ¶
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 RefreshAutocompleteEvent ¶
type RefreshAutocompleteEvent struct{}
RefreshAutocompleteEvent is sent when autocomplete needs to refresh (e.g., after mode change)
type ReminderQuery ¶
type ReminderQuery struct {
Hook HookPoint
Turn int
SessionTurn int
MaxTurns int
Fired map[string]bool
ToolFailed bool
RepeatedFailures int
FailedTool string
FinishReason string
IncompleteTodos []TodoItem
StalledStrikes int
TodoCount int
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 headless` 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.
RepeatedFailures and FailedTool are set at the post_tool hook when the same tool call has failed threshold+ consecutive times; they drive the `on_repeated_failure` trigger. FailedTool is the function name, for templating.
FinishReason carries the LLM response's finish_reason string. It drives the `on_truncation` trigger at the post_stream hook (firing when the value is "length").
IncompleteTodos carries the remaining open todo items from the model's TodoWrite list; it drives the `on_stalled_todos` trigger at the post_stream hook (firing when non-empty and the response had no tool calls). StalledStrikes is the count of consecutive no-tool-call responses, gating that trigger's strike cap (threshold).
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 RetryStatus ¶
RetryStatus tracks the current retry state for reconnection attempts. A nil *RetryStatus means no retry is in progress.
type ScreenRegion ¶
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 ShellCancelledEvent ¶
ShellCancelledEvent indicates a background shell was killed
func (ShellCancelledEvent) GetRequestID ¶
func (e ShellCancelledEvent) GetRequestID() string
func (ShellCancelledEvent) GetTimestamp ¶
func (e ShellCancelledEvent) GetTimestamp() time.Time
type ShellCompletedEvent ¶
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 ¶
func (e ShellCompletedEvent) GetRequestID() string
func (ShellCompletedEvent) GetTimestamp ¶
func (e ShellCompletedEvent) GetTimestamp() time.Time
type ShellDetachedEvent ¶
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 ¶
func (e ShellDetachedEvent) GetRequestID() string
func (ShellDetachedEvent) GetTimestamp ¶
func (e ShellDetachedEvent) GetTimestamp() time.Time
type ShellFailedEvent ¶
type ShellFailedEvent struct {
RequestID string
Timestamp time.Time
ShellID string
Error string
ExitCode int
}
ShellFailedEvent indicates a background shell failed
func (ShellFailedEvent) GetRequestID ¶
func (e ShellFailedEvent) GetRequestID() string
func (ShellFailedEvent) GetTimestamp ¶
func (e ShellFailedEvent) GetTimestamp() time.Time
type Skill ¶
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 ¶
DisplayName returns the qualified name for display. Plugin skills are shown as "pluginName:skillName" so the user/LLM can reference them unambiguously.
func (Skill) Summary ¶
func (s Skill) Summary() SkillSummary
Summary returns the wire-serializable projection of the skill.
type SkillLoadError ¶
SkillLoadError records a per-skill validation failure so `infer skills list` can surface why a directory was skipped without crashing startup.
type SkillScope ¶
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 SkillSummary ¶
type SkillSummary struct {
Name string `json:"name"`
Description string `json:"description"`
Scope string `json:"scope"`
}
SkillSummary is the serializable projection of a Skill (qualified name, description, scope) used wherever skills cross a wire boundary.
type SkillsService ¶
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 SubagentCompletedEvent ¶
type SubagentCompletedEvent struct {
RequestID string
Timestamp time.Time
SubagentID string
Label string
Result ToolExecutionResult
}
SubagentCompletedEvent indicates a local subagent completed successfully
func (SubagentCompletedEvent) GetRequestID ¶
func (e SubagentCompletedEvent) GetRequestID() string
func (SubagentCompletedEvent) GetTimestamp ¶
func (e SubagentCompletedEvent) GetTimestamp() time.Time
type SubagentFailedEvent ¶
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 ¶
func (e SubagentFailedEvent) GetRequestID() string
func (SubagentFailedEvent) GetTimestamp ¶
func (e SubagentFailedEvent) GetTimestamp() time.Time
type SubagentSubmittedEvent ¶
type SubagentSubmittedEvent struct {
RequestID string
Timestamp time.Time
SubagentID string
Label string
}
SubagentSubmittedEvent indicates a local subagent was dispatched
func (SubagentSubmittedEvent) GetRequestID ¶
func (e SubagentSubmittedEvent) GetRequestID() string
func (SubagentSubmittedEvent) GetTimestamp ¶
func (e SubagentSubmittedEvent) GetTimestamp() time.Time
type SystemReminder ¶
SystemReminder is a resolved reminder ready to inject into the conversation. When AppendToToolResult is true, the Text is appended to the last tool-role message content (for tool_call/tool pairing) instead of inserted as a standalone user message. Set by the provider for on_repeated_failure reminders.
type SystemReminderProvider ¶
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 TaskPollingState ¶
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 TodoItem ¶
type TodoItem struct {
ID string `json:"id"`
Content string `json:"content"`
Status string `json:"status"`
}
TodoItem represents a single todo item
type TodoManager ¶
TodoManager handles todo list state
type TodoUpdateChatEvent ¶
type TodoUpdateChatEvent struct {
BaseChatEvent
Todos []TodoItem
}
TodoUpdateChatEvent indicates the todo list has been updated (flows through chat event channel)
type TodoWriteToolResult ¶
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 Tool ¶
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 ¶
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 ¶
func (e ToolApprovalNotificationEvent) GetRequestID() string
func (ToolApprovalNotificationEvent) GetTimestamp ¶
func (e ToolApprovalNotificationEvent) GetTimestamp() time.Time
type ToolApprovalRequestedEvent ¶
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 ¶
func (e ToolApprovalRequestedEvent) GetRequestID() string
func (ToolApprovalRequestedEvent) GetTimestamp ¶
func (e ToolApprovalRequestedEvent) GetTimestamp() time.Time
type ToolApprovalResolvedEvent ¶
ToolApprovalResolvedEvent signals that a tool approval was answered (terminal or panel), so bus subscribers like the extension bridge clear their card. It is the reliable "answered" signal, replacing the racy next-event heuristic.
func (ToolApprovalResolvedEvent) GetRequestID ¶
func (e ToolApprovalResolvedEvent) GetRequestID() string
func (ToolApprovalResolvedEvent) GetTimestamp ¶
func (e ToolApprovalResolvedEvent) GetTimestamp() time.Time
type ToolApprovalResponseEvent ¶
type ToolApprovalResponseEvent struct {
Action ApprovalAction
ToolCall sdk.ChatCompletionMessageToolCall
}
ToolApprovalResponseEvent captures the user's approval decision
type ToolCall ¶
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 ¶
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 ¶
func (e ToolCallPreviewEvent) GetRequestID() string
func (ToolCallPreviewEvent) GetTimestamp ¶
func (e ToolCallPreviewEvent) GetTimestamp() time.Time
type ToolCallReadyEvent ¶
type ToolCallReadyEvent struct {
RequestID string
Timestamp time.Time
ToolCalls []sdk.ChatCompletionMessageToolCall
}
ToolCallReadyEvent indicates all tool calls are ready for approval/execution
func (ToolCallReadyEvent) GetRequestID ¶
func (e ToolCallReadyEvent) GetRequestID() string
func (ToolCallReadyEvent) GetTimestamp ¶
func (e ToolCallReadyEvent) GetTimestamp() time.Time
type ToolCallStatus ¶
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 ¶
func (t ToolCallStatus) String() string
type ToolCallStreamStatus ¶
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 ¶
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 ¶
func (e ToolCallUpdateEvent) GetRequestID() string
func (ToolCallUpdateEvent) GetTimestamp ¶
func (e ToolCallUpdateEvent) GetTimestamp() time.Time
type ToolCancelledEvent ¶
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 ¶
func (e ToolCancelledEvent) GetRequestID() string
func (ToolCancelledEvent) GetTimestamp ¶
func (e ToolCancelledEvent) GetTimestamp() time.Time
type ToolExecutionCompletedEvent ¶
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 ¶
func (e ToolExecutionCompletedEvent) GetRequestID() string
func (ToolExecutionCompletedEvent) GetTimestamp ¶
func (e ToolExecutionCompletedEvent) GetTimestamp() time.Time
type ToolExecutionManager ¶
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 ¶
type ToolExecutionProgressEvent struct {
BaseChatEvent
ToolCallID string
ToolName string
Arguments string
Status string
Message string
Images []ImageAttachment
}
ToolExecutionProgressEvent indicates progress in tool execution
type ToolExecutionResult ¶
type ToolExecutionResult struct {
ToolName string `json:"tool_name"`
ToolCallID string `json:"tool_call_id,omitempty"`
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 ¶
type ToolExecutionSession struct {
CurrentTool *ToolCall
RemainingTools []ToolCall
TotalTools int
CompletedTools int
Status ToolExecutionStatus
StartTime time.Time
}
ToolExecutionSession represents an active tool execution session
type ToolExecutionStatus ¶
type ToolExecutionStatus int
ToolExecutionStatus represents the overall tool execution session status
const ( ToolExecutionStatusIdle ToolExecutionStatus = iota ToolExecutionStatusProcessing ToolExecutionStatusExecuting ToolExecutionStatusCompleted ToolExecutionStatusFailed )
func (ToolExecutionStatus) String ¶
func (t ToolExecutionStatus) String() string
type ToolFormatter ¶
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 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 TreeToolResult ¶
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 UINotifier ¶
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 UserInputEvent ¶
type UserInputEvent struct {
Content string
Images []ImageAttachment
}
UserInputEvent represents user input submission
type UserQuestion ¶
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 ¶
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 ¶
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 ¶
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 ¶
type UserQuestionOption struct {
Label string `json:"label"`
Description string `json:"description"`
}
UserQuestionOption is a single selectable choice within a UserQuestion.
type UserQuestionRequestedEvent ¶
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 ¶
func (e UserQuestionRequestedEvent) GetRequestID() string
func (UserQuestionRequestedEvent) GetTimestamp ¶
func (e UserQuestionRequestedEvent) GetTimestamp() time.Time
type UserQuestionUIManager ¶
type UserQuestionUIManager interface {
SetupUserQuestionUIState(questions []UserQuestion, responseChan chan []UserQuestionAnswer)
GetUserQuestionUIState() *UserQuestionUIState
ClearUserQuestionUIState()
}
UserQuestionUIManager handles AskUserQuestion form state
type UserQuestionUIState ¶
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 WebSearchResponse ¶
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 ¶
type WebSearchResult struct {
Title string `json:"title"`
URL string `json:"url"`
Snippet string `json:"snippet"`
}
WebSearchResult represents a single search result