Documentation
¶
Index ¶
- Constants
- Variables
- func AddProviderToModel(provider, model string) string
- func CheckModelAvailable(model string) bool
- func CheckProviderReady(provider string) error
- func DeleteSession(path string) error
- func EvaluateModelConditional(currentModel, condition string) bool
- func ExtractModelFromPath(model string) string
- func ExtractProviderFromPath(model string) string
- func FormatSkillsForPrompt(s []*Skill) string
- func GetAnthropicAPIKey() string
- func GetCurrentModelID(model string) string
- func GetCurrentProvider(model string) string
- func GetLLMProviders() []string
- func GetModelCapabilities(model string) (extensions.ModelCapabilities, string)
- func GetModelsForProvider(provider string) (map[string]ModelInfo, error)
- func GetOpenAIAPIKey() string
- func GetSupportedProviders() []string
- func HasAnthropicCredentials() bool
- func HasOpenAICredentials() bool
- func InitConfig(configFile string, debug bool) error
- func InitTreeSession(opts *Options) (*session.TreeManager, error)
- func IsBareModelID(model string) bool
- func JoinModel(provider, modelID string) string
- func LoadConfigWithEnvSubstitution(configPath string) error
- func LoadSystemPrompt(pathOrContent string) (string, error)
- func MatchModelGlob(model, pattern string) bool
- func ParseArguments(input string, pattern extensions.ArgumentPattern) extensions.ParseResult
- func ParseModelString(model string) (provider, modelID string, err error)
- func ParseTemplate(name, content string) extensions.PromptTemplate
- func RefreshModelRegistry()
- func RemoveProviderFromModel(model string) string
- func RenderTemplate(tpl extensions.PromptTemplate, vars map[string]string) string
- func RenderWithModelConditionals(content, currentModel string) string
- func ResolveModelChain(preferences []string) extensions.ModelResolutionResult
- func SimpleParseArguments(input string, count int) []string
- func SuggestModels(provider, invalidModel string) []string
- func ToolCallIDFromContext(ctx context.Context) string
- func ValidateEnvironment(provider string, apiKey string) error
- type AfterToolResultHook
- type AfterToolResultResult
- type AfterTurnHook
- type AfterTurnResult
- type AgentConfig
- type AnthropicCredentials
- type BeforeCompactHook
- type BeforeCompactResult
- type BeforeToolCallHook
- type BeforeToolCallResult
- type BeforeTurnHook
- type BeforeTurnResult
- type BranchEntry
- type CLIMCPAuthHandler
- type CLIOptions
- type CompactionEntry
- type CompactionEvent
- type CompactionOptions
- type CompactionResult
- type Config
- type ContentPart
- type ContextFile
- type ContextPrepareHook
- type ContextPrepareResult
- type ContextStats
- type CredentialManager
- type CredentialStore
- type DefaultMCPAuthHandler
- type DiffBlock
- type EntryType
- type ErrorEvent
- type Event
- type EventListener
- type EventType
- type ExtensionAPI
- type ExtensionDataEntry
- type FileDiffInfo
- type Finish
- type HookPriority
- type Kit
- func (m *Kit) AddInProcessMCPServer(ctx context.Context, name string, srv *MCPServer) (int, error)
- func (m *Kit) AddMCPServer(ctx context.Context, name string, cfg MCPServerConfig) (int, error)
- func (m *Kit) Branch(entryID string) error
- func (m *Kit) CancelMCPTask(ctx context.Context, serverName, taskID string) (MCPTask, error)
- func (m *Kit) ClearSession()
- func (m *Kit) ClearSkillCache()
- func (m *Kit) Close() error
- func (m *Kit) CollapseBranch(fromID, toID, summary string) error
- func (m *Kit) Compact(ctx context.Context, opts *CompactionOptions, customInstructions string) (*CompactionResult, error)
- func (m *Kit) DiscoverSkillsForExtension() []extensions.Skill
- func (m *Kit) DrainSteer() []agent.SteerMessage
- func (m *Kit) EstimateContextTokens() int
- func (m *Kit) ExecuteCompletion(ctx context.Context, req extensions.CompleteRequest) (extensions.CompleteResponse, error)
- func (m *Kit) Extensions() ExtensionAPI
- func (m *Kit) FollowUp(ctx context.Context, text string) (string, error)
- func (m *Kit) GetAvailableModels() []extensions.ModelInfoEntry
- func (m *Kit) GetBufferedDebugMessages() []string
- func (m *Kit) GetChildren(parentID string) []string
- func (m *Kit) GetContextFiles() []*ContextFile
- func (m *Kit) GetContextStats() ContextStats
- func (m *Kit) GetCurrentBranch() []TreeNode
- func (m *Kit) GetExtensionToolCount() int
- func (m *Kit) GetLoadedServerNames() []string
- func (m *Kit) GetLoadingMessage() string
- func (m *Kit) GetMCPPrompt(ctx context.Context, serverName, promptName string, args map[string]string) (*MCPPromptResult, error)
- func (m *Kit) GetMCPTask(ctx context.Context, serverName, taskID string) (MCPTask, error)
- func (m *Kit) GetMCPToolCount() int
- func (m *Kit) GetModelInfo() *ModelInfo
- func (m *Kit) GetModelString() string
- func (m *Kit) GetSessionID() string
- func (m *Kit) GetSessionManager() SessionManager
- func (m *Kit) GetSessionPath() string
- func (m *Kit) GetSkills() []*Skill
- func (m *Kit) GetStructuredMessages() []StructuredMessage
- func (m *Kit) GetThinkingLevel() string
- func (m *Kit) GetToolNames() []string
- func (m *Kit) GetTools() []Tool
- func (m *Kit) GetTreeNode(entryID string) *TreeNode
- func (m *Kit) GetTreeSession() *TreeManager
- func (m *Kit) InjectSteer(message string)
- func (m *Kit) InjectSteerWithFiles(message string, files []LLMFilePart)
- func (m *Kit) IsGenerating() bool
- func (m *Kit) IsReasoningModel() bool
- func (m *Kit) ListMCPPrompts() []MCPPrompt
- func (m *Kit) ListMCPResources() []MCPResource
- func (m *Kit) ListMCPServers() []MCPServerStatus
- func (m *Kit) ListMCPTasks(ctx context.Context, serverName string) ([]MCPTask, error)
- func (m *Kit) LoadSkillForExtension(path string) (*extensions.Skill, string)
- func (m *Kit) LoadSkillsFromDirForExtension(dir string) extensions.SkillLoadResult
- func (m *Kit) MCPToolsReady() bool
- func (m *Kit) MaxOutputLimit() int
- func (m *Kit) MaxTokens() int
- func (m *Kit) NavigateTo(entryID string) error
- func (m *Kit) OnAfterToolResult(p HookPriority, h func(AfterToolResultHook) *AfterToolResultResult) func()
- func (m *Kit) OnAfterTurn(p HookPriority, h func(AfterTurnHook)) func()
- func (m *Kit) OnBeforeCompact(p HookPriority, h func(BeforeCompactHook) *BeforeCompactResult) func()
- func (m *Kit) OnBeforeToolCall(p HookPriority, h func(BeforeToolCallHook) *BeforeToolCallResult) func()
- func (m *Kit) OnBeforeTurn(p HookPriority, h func(BeforeTurnHook) *BeforeTurnResult) func()
- func (m *Kit) OnCompaction(handler func(CompactionEvent)) func()
- func (m *Kit) OnContextPrepare(p HookPriority, h func(ContextPrepareHook) *ContextPrepareResult) func()
- func (m *Kit) OnError(handler func(ErrorEvent)) func()
- func (m *Kit) OnMessageEnd(handler func(MessageEndEvent)) func()
- func (m *Kit) OnMessageStart(handler func(MessageStartEvent)) func()
- func (m *Kit) OnMessageUpdate(handler func(MessageUpdateEvent)) func()
- func (m *Kit) OnPrepareStep(p HookPriority, h func(PrepareStepHook) *PrepareStepResult) func()
- func (m *Kit) OnReasoningComplete(handler func(ReasoningCompleteEvent)) func()
- func (m *Kit) OnReasoningDelta(handler func(ReasoningDeltaEvent)) func()
- func (m *Kit) OnReasoningStart(handler func(ReasoningStartEvent)) func()
- func (m *Kit) OnResponse(handler func(ResponseEvent)) func()
- func (m *Kit) OnRetry(handler func(RetryEvent)) func()
- func (m *Kit) OnSource(handler func(SourceEvent)) func()
- func (m *Kit) OnSteerConsumed(handler func(SteerConsumedEvent)) func()
- func (m *Kit) OnStepFinish(handler func(StepFinishEvent)) func()
- func (m *Kit) OnStepStart(handler func(StepStartEvent)) func()
- func (m *Kit) OnStepUsage(handler func(StepUsageEvent)) func()
- func (m *Kit) OnStreamFinish(handler func(StreamFinishEvent)) func()
- func (m *Kit) OnStreaming(handler func(MessageUpdateEvent)) func()deprecated
- func (m *Kit) OnTextEnd(handler func(TextEndEvent)) func()
- func (m *Kit) OnTextStart(handler func(TextStartEvent)) func()
- func (m *Kit) OnToolCall(handler func(ToolCallEvent)) func()
- func (m *Kit) OnToolCallContent(handler func(ToolCallContentEvent)) func()
- func (m *Kit) OnToolCallDelta(handler func(ToolCallDeltaEvent)) func()
- func (m *Kit) OnToolCallEnd(handler func(ToolCallEndEvent)) func()
- func (m *Kit) OnToolCallStart(handler func(ToolCallStartEvent)) func()
- func (m *Kit) OnToolExecutionEnd(handler func(ToolExecutionEndEvent)) func()
- func (m *Kit) OnToolExecutionStart(handler func(ToolExecutionStartEvent)) func()
- func (m *Kit) OnToolOutput(handler func(ToolOutputEvent)) func()
- func (m *Kit) OnToolResult(handler func(ToolResultEvent)) func()
- func (m *Kit) OnTurnEnd(handler func(TurnEndEvent)) func()
- func (m *Kit) OnTurnStart(handler func(TurnStartEvent)) func()
- func (m *Kit) OnWarnings(handler func(WarningsEvent)) func()
- func (m *Kit) Prompt(ctx context.Context, message string) (string, error)
- func (m *Kit) PromptResult(ctx context.Context, message string) (*TurnResult, error)
- func (m *Kit) PromptResultWithFiles(ctx context.Context, message string, files []LLMFilePart) (*TurnResult, error)
- func (m *Kit) PromptResultWithMessages(ctx context.Context, messages []string) (*TurnResult, error)
- func (m *Kit) PromptWithOptions(ctx context.Context, msg string, opts PromptOptions) (string, error)
- func (m *Kit) ReadMCPResource(ctx context.Context, serverName, uri string) (*MCPResourceContent, error)
- func (m *Kit) ReloadExtensions() error
- func (m *Kit) ReloadSkills() error
- func (m *Kit) RemoveMCPServer(name string) error
- func (m *Kit) SetModel(ctx context.Context, modelString string) error
- func (m *Kit) SetSessionManager(sm SessionManager)
- func (m *Kit) SetSessionName(name string) error
- func (m *Kit) SetThinkingLevel(ctx context.Context, level string) error
- func (m *Kit) SetTreeSession(ts *TreeManager)
- func (m *Kit) ShouldCompact() bool
- func (m *Kit) Steer(ctx context.Context, instruction string) (string, error)
- func (m *Kit) Subagent(ctx context.Context, cfg SubagentConfig) (*SubagentResult, error)
- func (m *Kit) Subscribe(listener EventListener) func()
- func (m *Kit) SubscribeMCPResource(ctx context.Context, serverName, uri string) error
- func (m *Kit) SubscribeSubagent(toolCallID string, listener EventListener) func()
- func (m *Kit) SummarizeBranch(fromID, toID string) (string, error)
- func (m *Kit) UnsubscribeMCPResource(ctx context.Context, serverName, uri string) error
- func (m *Kit) WaitForMCPTools() error
- type LLMFilePart
- type LLMFinishReason
- type LLMMessage
- type LLMMessagePart
- type LLMMessageRole
- type LLMPrompt
- type LLMProviderMetadata
- type LLMProviderOptions
- type LLMReasoningPart
- type LLMResponse
- type LLMTextPart
- type LLMToolCall
- type LLMToolCallPart
- type LLMToolInfo
- type LLMToolResponse
- type LLMToolResultContentType
- type LLMToolResultOutputContent
- type LLMToolResultOutputContentError
- type LLMToolResultOutputContentMedia
- type LLMToolResultOutputContentText
- type LLMToolResultPart
- type LLMUsage
- type MCPAuthHandler
- type MCPPrompt
- type MCPPromptArgument
- type MCPPromptMessage
- type MCPPromptResult
- type MCPResource
- type MCPResourceContent
- type MCPServer
- type MCPServerConfig
- type MCPServerStatus
- type MCPTask
- type MCPTaskMode
- type MCPTaskProgress
- type MCPTaskProgressHandler
- type MCPTaskStatus
- type MCPToken
- type MCPTokenStore
- type MCPTokenStoreFactory
- type Message
- type MessageEndEvent
- type MessageEntry
- type MessageRole
- type MessageStartEvent
- type MessageUpdateEvent
- type ModelCost
- type ModelInfo
- type ModelLimit
- type ModelsRegistry
- type OpenAICredentials
- type Options
- type PasswordPromptEvent
- type PasswordPromptResponse
- type PrepareStepHook
- type PrepareStepResult
- type PromptBuilder
- type PromptOptions
- type PromptTemplate
- type ProviderConfig
- type ProviderInfo
- type ProviderResult
- type ReasoningCompleteEvent
- type ReasoningContent
- type ReasoningDeltaEvent
- type ReasoningStartEvent
- type ResponseEvent
- type ResponseHandler
- type RetryEvent
- type SessionHeader
- type SessionInfo
- type SessionManager
- type Skill
- type SourceEvent
- type SpinnerFunc
- type SteerConsumedEvent
- type StepFinishEvent
- type StepStartEvent
- type StepUsageEvent
- type StreamFinishEvent
- type StreamingResponseHandler
- type StructuredMessage
- type SubagentConfig
- type SubagentResult
- type TextContent
- type TextEndEvent
- type TextStartEvent
- type Tool
- func AllTools(opts ...ToolOption) []Tool
- func CodingTools(opts ...ToolOption) []Tool
- func NewBashTool(opts ...ToolOption) Tool
- func NewEditTool(opts ...ToolOption) Tool
- func NewFindTool(opts ...ToolOption) Tool
- func NewGrepTool(opts ...ToolOption) Tool
- func NewLsTool(opts ...ToolOption) Tool
- func NewParallelTool[TInput any](name, description string, ...) Tool
- func NewReadTool(opts ...ToolOption) Tool
- func NewTool[TInput any](name, description string, ...) Tool
- func NewWriteTool(opts ...ToolOption) Tool
- func ReadOnlyTools(opts ...ToolOption) []Tool
- func SubagentTools(opts ...ToolOption) []Tool
- type ToolCall
- type ToolCallContentEvent
- type ToolCallContentHandler
- type ToolCallDeltaEvent
- type ToolCallEndEvent
- type ToolCallEvent
- type ToolCallHandler
- type ToolCallStartEvent
- type ToolExecutionEndEvent
- type ToolExecutionHandler
- type ToolExecutionStartEvent
- type ToolOption
- type ToolOutput
- type ToolOutputEvent
- type ToolResult
- type ToolResultEvent
- type ToolResultHandler
- type ToolResultMetadata
- type TreeManager
- type TreeNode
- type TurnEndEvent
- type TurnResult
- type TurnStartEvent
- type WarningsEvent
Constants ¶
const ( ToolKindExecute = "execute" // Shell execution (bash) ToolKindEdit = "edit" // File modification (edit, write) ToolKindRead = "read" // File reading (read, ls) ToolKindSearch = "search" // Content/file search (grep, find) ToolKindSubagent = "agent" // Subagent spawning (subagent) )
ToolKind constants classify what a tool does, enabling UIs to render appropriate visualizations (e.g. diff view for edit tools, command+output for execute tools) and file trackers to identify which results contain modifications.
const ( // FinishReasonStop: the model produced a natural stop (e.g. stop sequence // or end-of-turn signal). FinishReasonStop = "stop" // FinishReasonLength: the model hit the configured max_output_tokens // budget. The response is truncated. Surface this to the user and // consider raising --max-tokens / KIT_MAX_TOKENS / modelSettings[...] // .maxTokens. FinishReasonLength = "length" // FinishReasonToolCalls: the model stopped to emit tool calls (normal // mid-turn state during agentic loops). FinishReasonToolCalls = "tool-calls" // FinishReasonContentFilter: the provider's safety filter stopped // generation. FinishReasonContentFilter = "content-filter" // FinishReasonError: the model stopped because of an error. FinishReasonError = "error" // FinishReasonOther: provider-specific reason that doesn't map to any of // the above. FinishReasonOther = "other" // FinishReasonUnknown: the provider didn't report a finish reason. FinishReasonUnknown = "unknown" )
Finish reasons reported by the LLM provider on a completed turn. These mirror the underlying provider's finish reason string values so comparisons against TurnEndEvent.StopReason / TurnResult.StopReason are stable across providers.
const ( RoleUser = message.RoleUser RoleAssistant = message.RoleAssistant RoleTool = message.RoleTool RoleSystem = message.RoleSystem )
const ( // LLMToolResultContentTypeText represents text output. LLMToolResultContentTypeText = fantasy.ToolResultContentTypeText // LLMToolResultContentTypeError represents error text output. LLMToolResultContentTypeError = fantasy.ToolResultContentTypeError // LLMToolResultContentTypeMedia represents media (binary) output. LLMToolResultContentTypeMedia = fantasy.ToolResultContentTypeMedia )
Tool result content type constants.
const ( // LLMRoleUser identifies a user message. LLMRoleUser = fantasy.MessageRoleUser // LLMRoleAssistant identifies an assistant message. LLMRoleAssistant = fantasy.MessageRoleAssistant // LLMRoleSystem identifies a system message. LLMRoleSystem = fantasy.MessageRoleSystem // LLMRoleTool identifies a tool result message. LLMRoleTool = fantasy.MessageRoleTool )
LLM role constants mirror the provider's role values under clean LLM-prefixed names.
Variables ¶
var ErrMCPNoToken = transport.ErrNoToken
ErrMCPNoToken is the sentinel error that MCPTokenStore implementations should return from GetToken when no token is stored for the server. Callers can check for this with errors.Is.
var NewLLMSystemMessage = fantasy.NewSystemMessage
NewLLMSystemMessage constructs a system-role LLMMessage from one or more prompt strings.
var NewLLMUserMessage = fantasy.NewUserMessage
NewLLMUserMessage constructs a user-role LLMMessage with optional file attachments.
var WithWorkDir = core.WithWorkDir
WithWorkDir sets the working directory for file-based tools. If empty, os.Getwd() is used at execution time.
Functions ¶
func AddProviderToModel ¶ added in v0.28.0
AddProviderToModel adds a provider prefix to a bare model ID.
func CheckModelAvailable ¶ added in v0.28.0
CheckModelAvailable verifies if a model string is valid and provider exists.
func CheckProviderReady ¶
CheckProviderReady validates that a provider is properly configured by checking that it exists in the registry and has required environment variables set.
func DeleteSession ¶
DeleteSession removes a session file from disk.
func EvaluateModelConditional ¶ added in v0.28.0
EvaluateModelConditional checks if condition matches current model. Condition supports wildcards: * matches any, ? matches single char.
func ExtractModelFromPath ¶ added in v0.28.0
ExtractModelFromPath extracts model ID from a path-like model string.
func ExtractProviderFromPath ¶ added in v0.28.0
ExtractProviderFromPath extracts provider from a path-like model string.
func FormatSkillsForPrompt ¶
FormatSkillsForPrompt formats skills for inclusion in a system prompt. Each skill is rendered as a named section with its content.
func GetAnthropicAPIKey ¶
func GetAnthropicAPIKey() string
GetAnthropicAPIKey resolves the Anthropic API key using the standard resolution order: stored credentials -> ANTHROPIC_API_KEY env var. Returns an empty string if no key is found.
func GetCurrentModelID ¶ added in v0.28.0
GetCurrentModelID extracts model ID from model string.
func GetCurrentProvider ¶ added in v0.28.0
GetCurrentProvider extracts provider from model string.
func GetLLMProviders ¶ added in v0.30.0
func GetLLMProviders() []string
GetLLMProviders returns provider IDs that have LLM support, either through a native provider or via openaicompat auto-routing.
func GetModelCapabilities ¶ added in v0.28.0
func GetModelCapabilities(model string) (extensions.ModelCapabilities, string)
GetModelCapabilities returns capabilities for a specific model. If model is empty, returns zero capabilities.
func GetModelsForProvider ¶
GetModelsForProvider returns all known models for a provider.
func GetOpenAIAPIKey ¶ added in v0.25.0
func GetOpenAIAPIKey() string
GetOpenAIAPIKey resolves the OpenAI API key using the standard resolution order: stored credentials -> OPENAI_API_KEY env var. Returns an empty string if no key is found.
func GetSupportedProviders ¶
func GetSupportedProviders() []string
GetSupportedProviders returns all known provider names in the registry.
func HasAnthropicCredentials ¶
func HasAnthropicCredentials() bool
HasAnthropicCredentials checks if valid Anthropic credentials are stored (either OAuth token or API key).
func HasOpenAICredentials ¶ added in v0.25.0
func HasOpenAICredentials() bool
HasOpenAICredentials checks if valid OpenAI credentials are stored (either OAuth token or API key).
func InitConfig ¶
InitConfig initializes the viper configuration system. It searches for config files in standard locations and loads them with environment variable substitution.
configFile: explicit config file path (empty = search defaults). debug: if true, print warnings about missing configs to stderr.
func InitTreeSession ¶
func InitTreeSession(opts *Options) (*session.TreeManager, error)
InitTreeSession creates or opens a tree session based on the given options. Both kit.New() and the CLI use this function so session initialisation logic lives in one place.
Behaviour based on Options:
- NoSession: in-memory tree session (no persistence)
- Continue: resume most recent session for SessionDir (or cwd)
- SessionPath: open a specific JSONL session file
- default: create a new tree session for SessionDir (or cwd)
func IsBareModelID ¶ added in v0.28.0
IsBareModelID checks if a string is a bare model ID (no provider).
func LoadConfigWithEnvSubstitution ¶
LoadConfigWithEnvSubstitution loads a config file with ${ENV_VAR} expansion.
func LoadSystemPrompt ¶
LoadSystemPrompt loads a system prompt from a file path, or returns the string directly if it is not a valid file path.
func MatchModelGlob ¶ added in v0.28.0
MatchModelGlob matches a model against a glob pattern. Pattern can contain * (match any) and ? (match single).
func ParseArguments ¶ added in v0.28.0
func ParseArguments(input string, pattern extensions.ArgumentPattern) extensions.ParseResult
ParseArguments parses command-line style arguments.
func ParseModelString ¶
ParseModelString parses a model string in "provider/model" format. Returns provider, modelID, and an error if the format is invalid.
func ParseTemplate ¶ added in v0.28.0
func ParseTemplate(name, content string) extensions.PromptTemplate
ParseTemplate extracts {{variables}} from template content.
func RefreshModelRegistry ¶
func RefreshModelRegistry()
RefreshModelRegistry reloads the global model database from the current data sources (cache -> embedded). Call after updating the cache.
func RemoveProviderFromModel ¶ added in v0.28.0
RemoveProviderFromModel removes the provider prefix from a model string.
func RenderTemplate ¶ added in v0.28.0
func RenderTemplate(tpl extensions.PromptTemplate, vars map[string]string) string
RenderTemplate substitutes variables into template content. Handles {{name}} and {{ name }} (any whitespace) placeholders.
func RenderWithModelConditionals ¶ added in v0.28.0
RenderWithModelConditionals processes <if-model> blocks in content.
func ResolveModelChain ¶ added in v0.28.0
func ResolveModelChain(preferences []string) extensions.ModelResolutionResult
ResolveModelChain attempts each model in order until one is available.
func SimpleParseArguments ¶ added in v0.28.0
SimpleParseArguments parses $1, $2, $@ style arguments. Returns slice where [0]=full input, [1]=$1, [2]=$2, ... [n]=$@
func SuggestModels ¶
SuggestModels returns model names similar to an invalid model string.
func ToolCallIDFromContext ¶ added in v0.43.0
ToolCallIDFromContext extracts the tool call ID from the context. The call ID is set automatically by NewTool and NewParallelTool before invoking the handler. Returns an empty string if no ID is present.
func ValidateEnvironment ¶
ValidateEnvironment checks if required API keys are set for a provider. Returns nil for providers not in the registry (unknown providers are assumed to handle auth themselves or via --provider-api-key).
Types ¶
type AfterToolResultHook ¶
type AfterToolResultHook struct {
ToolCallID string
ToolName string
ToolArgs string
Result string
IsError bool
}
AfterToolResultHook is the input for hooks that fire after a tool executes.
type AfterToolResultResult ¶
type AfterToolResultResult struct {
Result *string // non-nil overrides the result text
IsError *bool // non-nil overrides the error flag
}
AfterToolResultResult can modify the tool's output before it reaches the LLM.
type AfterTurnHook ¶
AfterTurnHook is the input for hooks that fire after a prompt turn completes.
type AfterTurnResult ¶
type AfterTurnResult struct{}
AfterTurnResult is a placeholder — after-turn hooks are observation-only.
type AgentConfig ¶
type AgentConfig = agent.AgentConfig
AgentConfig holds configuration options for creating a new Agent.
type AnthropicCredentials ¶
type AnthropicCredentials = auth.AnthropicCredentials
AnthropicCredentials holds Anthropic API credentials supporting both OAuth and API key authentication methods.
type BeforeCompactHook ¶ added in v0.3.0
type BeforeCompactHook struct {
// EstimatedTokens is the estimated token count of the conversation.
EstimatedTokens int
// ContextLimit is the model's context window size in tokens.
ContextLimit int
// UsagePercent is the fraction of context used (0.0–1.0).
UsagePercent float64
// MessageCount is the number of messages in the conversation.
MessageCount int
// IsAutomatic is true when compaction was triggered automatically.
IsAutomatic bool
}
BeforeCompactHook is the input for hooks that fire before compaction runs.
type BeforeCompactResult ¶ added in v0.3.0
type BeforeCompactResult struct {
// Cancel, when true, prevents compaction from proceeding.
Cancel bool
// Reason is a human-readable explanation when Cancel is true.
Reason string
// Summary, when non-empty, replaces the default LLM-generated summary.
// The extension is responsible for generating a useful summary.
// Ignored when Cancel is true.
Summary string
}
BeforeCompactResult controls whether compaction proceeds. Extensions can cancel compaction or provide a custom summary that replaces the default LLM-generated one.
type BeforeToolCallHook ¶
BeforeToolCallHook is the input for hooks that fire before a tool executes.
type BeforeToolCallResult ¶
type BeforeToolCallResult struct {
Block bool // true prevents the tool from running
Reason string // human-readable reason for blocking
}
BeforeToolCallResult controls whether the tool call proceeds.
type BeforeTurnHook ¶
type BeforeTurnHook struct {
Prompt string
}
BeforeTurnHook is the input for hooks that fire before a prompt turn.
type BeforeTurnResult ¶
type BeforeTurnResult struct {
Prompt *string // override prompt text in the user message
SystemPrompt *string // prepend a system message
InjectText *string // prepend a user context message
}
BeforeTurnResult can modify the prompt, inject system messages, or add context.
type BranchEntry ¶ added in v0.42.0
type BranchEntry struct {
ID string
ParentID string
Type EntryType // "message", "branch_summary", "model_change", "compaction", "extension_data"
Role string // for messages: "user", "assistant", "system", "tool"
Content string // text content or summary
Model string // model used (for messages and model_change)
Provider string // provider used
Timestamp time.Time
Children []string // child entry IDs (for tree display)
// RawParts contains the full typed content parts for structured access.
// Only populated for message entries.
RawParts []ContentPart
}
BranchEntry represents a single node in the conversation tree. This is a SDK-friendly struct (not the internal entry types).
type CLIMCPAuthHandler ¶ added in v0.39.0
type CLIMCPAuthHandler struct {
// NotifyFunc, when set, is called with status messages instead of
// writing to the writer. This allows the TUI to display system
// messages in the chat stream. If nil, messages are written to w.
NotifyFunc func(serverName, message string)
// contains filtered or unexported fields
}
CLIMCPAuthHandler is the MCP OAuth handler for CLI/TUI consumers. It wraps a DefaultMCPAuthHandler and layers standard CLI behavior on top of the underlying transport mechanics:
- Opens the authorization URL in the system browser
- Prints status messages (or routes them to a TUI via [NotifyFunc])
Non-CLI consumers (web apps, daemons, custom TUIs) should not use this handler; implement MCPAuthHandler directly or configure a DefaultMCPAuthHandler with a custom OnAuthURL instead.
func NewCLIMCPAuthHandler ¶ added in v0.39.0
func NewCLIMCPAuthHandler() (*CLIMCPAuthHandler, error)
NewCLIMCPAuthHandler creates a CLI auth handler that prints status messages to stderr, opens the authorization URL in the system browser, and delegates the callback-server mechanics to a DefaultMCPAuthHandler.
func (*CLIMCPAuthHandler) Close ¶ added in v0.39.0
func (h *CLIMCPAuthHandler) Close() error
Close releases the inner handler's resources.
func (*CLIMCPAuthHandler) HandleAuth ¶ added in v0.39.0
func (h *CLIMCPAuthHandler) HandleAuth(ctx context.Context, serverName string, authURL string) (string, error)
HandleAuth delegates to the inner handler (which invokes OnAuthURL, runs the callback server, and returns the full callback URL) and emits a final success or failure notification.
func (*CLIMCPAuthHandler) RedirectURI ¶ added in v0.39.0
func (h *CLIMCPAuthHandler) RedirectURI() string
RedirectURI returns the OAuth redirect URI from the inner handler.
type CLIOptions ¶ added in v0.2.0
type CLIOptions struct {
// MCPConfig is a pre-loaded MCP config. When set, LoadAndValidateConfig
// is skipped during Kit creation.
MCPConfig *config.Config
// ShowSpinner shows a loading spinner for Ollama models.
ShowSpinner bool
// SpinnerFunc provides the spinner implementation (nil = no spinner).
SpinnerFunc SpinnerFunc
// UseBufferedLogger buffers debug messages for later display.
UseBufferedLogger bool
// ProgressReaderFunc wraps an io.Reader with a progress display for
// long-running operations such as Ollama model pulls. The returned
// io.ReadCloser must be closed when done. When nil, progress is not
// displayed.
ProgressReaderFunc func(io.Reader) io.ReadCloser
}
CLIOptions holds fields only relevant to the CLI binary. SDK users should not need these; they are separated to keep the main Options struct clean.
type CompactionEntry ¶ added in v0.42.0
type CompactionEntry struct {
ID string
Summary string
FirstKeptEntryID string
TokensBefore int
TokensAfter int
MessagesRemoved int
ReadFiles []string
ModifiedFiles []string
Timestamp time.Time
}
CompactionEntry represents a context compaction/summarization event.
type CompactionEvent ¶
type CompactionEvent struct {
Summary string
OriginalTokens int
CompactedTokens int
MessagesRemoved int
ReadFiles []string
ModifiedFiles []string
}
CompactionEvent fires after a successful compaction.
func (CompactionEvent) EventType ¶
func (e CompactionEvent) EventType() EventType
EventType implements Event.
type CompactionOptions ¶
type CompactionOptions = compaction.CompactionOptions
CompactionOptions configures compaction behaviour.
type CompactionResult ¶
type CompactionResult = compaction.CompactionResult
CompactionResult contains statistics from a compaction operation.
type Config ¶
Config represents the complete application configuration including MCP servers, model settings, UI preferences, and API credentials.
type ContentPart ¶
type ContentPart = message.ContentPart
ContentPart is the marker interface for all message content block types.
type ContextFile ¶
type ContextFile struct {
Path string // Absolute filesystem path.
Content string // Full file content.
}
ContextFile represents a project context file (e.g. AGENTS.md) that was loaded during initialization and injected into the system prompt.
type ContextPrepareHook ¶ added in v0.3.0
type ContextPrepareHook struct {
// Messages is the current context as LLM message objects.
Messages []LLMMessage
}
ContextPrepareHook is the input for hooks that fire after the context window is assembled from the session tree (including compaction) and before the messages are sent to the LLM. Hooks can filter, reorder, or inject messages.
type ContextPrepareResult ¶ added in v0.3.0
type ContextPrepareResult struct {
// Messages replaces the entire context window. If nil, the original
// messages are used.
Messages []LLMMessage
}
ContextPrepareResult can replace the context window.
type ContextStats ¶
type ContextStats struct {
EstimatedTokens int // Estimated token count of the current conversation
ContextLimit int // Model's context window size (tokens), 0 if unknown
UsagePercent float64 // Fraction of context used (0.0–1.0), 0 if limit unknown
MessageCount int // Number of messages in the conversation
}
ContextStats contains current context usage information.
type CredentialManager ¶
type CredentialManager = auth.CredentialManager
CredentialManager manages API keys and OAuth credentials.
func NewCredentialManager ¶
func NewCredentialManager() (*CredentialManager, error)
NewCredentialManager creates a credential manager for secure storage and retrieval of authentication credentials.
type CredentialStore ¶
type CredentialStore = auth.CredentialStore
CredentialStore holds all stored credentials for various providers.
type DefaultMCPAuthHandler ¶ added in v0.39.0
type DefaultMCPAuthHandler struct {
// OnAuthURL, if set, is invoked exactly once per [HandleAuth] call with
// the authorization URL the user must visit. This is where consumers
// plug in their UX: open a browser, print to stderr, post to a TUI
// stream, render a QR code, etc. The handler performs no I/O on the
// URL itself; if OnAuthURL is nil the URL is silently dropped and the
// user has no way to complete the flow.
//
// OnAuthURL is called synchronously before the handler blocks on the
// callback. It must not block indefinitely — long-running work should
// be dispatched to a goroutine.
OnAuthURL func(serverName, authURL string)
// contains filtered or unexported fields
}
DefaultMCPAuthHandler provides the transport mechanics of an OAuth flow — reserving a local TCP port and running a one-shot HTTP callback server — without making any user-experience decisions. It performs no browser opens, no printing, no TUI calls; consumers attach presentation by setting [DefaultMCPAuthHandler.OnAuthURL] or by wrapping the handler.
The handler eagerly reserves a TCP port on construction so [RedirectURI] is stable for the lifetime of the handler. Create instances with NewDefaultMCPAuthHandler (random port) or NewDefaultMCPAuthHandlerWithPort (explicit port). Always call DefaultMCPAuthHandler.Close when done to release the port.
func NewDefaultMCPAuthHandler ¶ added in v0.39.0
func NewDefaultMCPAuthHandler() (*DefaultMCPAuthHandler, error)
NewDefaultMCPAuthHandler creates a handler that listens on a random available port on localhost. The port is reserved immediately so [RedirectURI] returns a stable value. Call DefaultMCPAuthHandler.Close when the handler is no longer needed to release the port.
The returned handler has no OnAuthURL hook configured and will therefore appear to hang on HandleAuth until the context deadline fires. Set OnAuthURL before using the handler, or use a higher-level wrapper such as CLIMCPAuthHandler.
func NewDefaultMCPAuthHandlerWithPort ¶ added in v0.39.0
func NewDefaultMCPAuthHandlerWithPort(port int) (*DefaultMCPAuthHandler, error)
NewDefaultMCPAuthHandlerWithPort creates a handler that listens on the specified port on localhost. The port is reserved immediately. Pass 0 to let the OS pick a free port (equivalent to NewDefaultMCPAuthHandler). Call DefaultMCPAuthHandler.Close when the handler is no longer needed.
func (*DefaultMCPAuthHandler) Close ¶ added in v0.39.0
func (h *DefaultMCPAuthHandler) Close() error
Close releases the reserved port and shuts down the handler. After Close, HandleAuth will return an error. Close is safe to call multiple times.
func (*DefaultMCPAuthHandler) HandleAuth ¶ added in v0.39.0
func (h *DefaultMCPAuthHandler) HandleAuth(ctx context.Context, serverName string, authURL string) (string, error)
HandleAuth invokes [OnAuthURL] with the authorization URL (if configured) and waits for the OAuth callback on the local server. It returns the full callback URL including query parameters (code, state, etc.).
If the context has no deadline, a default 2-minute timeout is applied. The callback server is started for each HandleAuth call and shut down before returning.
func (*DefaultMCPAuthHandler) Port ¶ added in v0.39.0
func (h *DefaultMCPAuthHandler) Port() int
Port returns the TCP port the callback server is bound to.
func (*DefaultMCPAuthHandler) RedirectURI ¶ added in v0.39.0
func (h *DefaultMCPAuthHandler) RedirectURI() string
RedirectURI returns the OAuth redirect URI pointing to the local callback server. This value is stable for the lifetime of the handler.
type DiffBlock ¶ added in v0.12.0
DiffBlock represents a single old→new text replacement within a file.
type EntryType ¶ added in v0.42.0
type EntryType string
EntryType identifies the kind of entry in the session tree.
type ErrorEvent ¶ added in v0.60.0
type ErrorEvent struct {
Error error
}
ErrorEvent fires when an agent-level error occurs during streaming. This is distinct from TurnEndEvent.Error — it fires at the point of failure.
func (ErrorEvent) EventType ¶ added in v0.60.0
func (e ErrorEvent) EventType() EventType
EventType implements Event.
type Event ¶
type Event interface {
EventType() EventType
}
Event is the interface implemented by all lifecycle events. Each concrete event type returns its EventType via this method.
type EventListener ¶
type EventListener func(event Event)
EventListener is a callback that receives lifecycle events.
type EventType ¶
type EventType string
EventType identifies the kind of lifecycle event.
const ( // EventTurnStart fires before the agent begins processing a prompt. EventTurnStart EventType = "turn_start" // EventTurnEnd fires after the agent finishes processing (success or error). EventTurnEnd EventType = "turn_end" // EventMessageStart fires when a new assistant message begins. EventMessageStart EventType = "message_start" // EventMessageUpdate fires for each streaming text chunk. EventMessageUpdate EventType = "message_update" // EventMessageEnd fires when the assistant message is complete. EventMessageEnd EventType = "message_end" // EventToolCallStart fires when the LLM begins generating tool call arguments. // The tool name is known but arguments are still streaming. EventToolCallStart EventType = "tool_call_start" // EventToolCallDelta fires for each streamed fragment of tool call arguments. EventToolCallDelta EventType = "tool_call_delta" // EventToolCallEnd fires when tool argument streaming is complete, before // the tool call is parsed and execution begins. EventToolCallEnd EventType = "tool_call_end" // EventToolCall fires when a tool call has been parsed and is about to execute. EventToolCall EventType = "tool_call" // EventToolExecutionStart fires when a tool begins executing. EventToolExecutionStart EventType = "tool_execution_start" // EventToolExecutionEnd fires when a tool finishes executing. EventToolExecutionEnd EventType = "tool_execution_end" // EventToolResult fires after a tool execution completes with its result. EventToolResult EventType = "tool_result" // EventToolCallContent fires when a step includes text alongside tool calls. EventToolCallContent EventType = "tool_call_content" // EventResponse fires when the LLM produces a final response. EventResponse EventType = "response" // EventCompaction fires after a successful compaction. EventCompaction EventType = "compaction" // EventReasoningDelta fires for each streaming reasoning/thinking chunk. EventReasoningDelta EventType = "reasoning_delta" // EventReasoningComplete fires when reasoning/thinking is finished, // after the last reasoning token has been processed. EventReasoningComplete EventType = "reasoning_complete" // EventToolOutput fires when a tool produces streaming output chunks. EventToolOutput EventType = "tool_output" EventStepUsage EventType = "step_usage" // EventPasswordPrompt fires when a sudo command needs a password. EventPasswordPrompt EventType = "password_prompt" // EventSteerConsumed fires when one or more steering messages have been // injected into the agent turn via PrepareStep. EventSteerConsumed EventType = "steer_consumed" // EventStepStart fires when a new LLM call begins within a turn. EventStepStart EventType = "step_start" // EventStepFinish fires when a step completes, providing full step context // including whether tool calls were made, the finish reason, and usage stats. EventStepFinish EventType = "step_finish" // EventTextStart fires when the LLM begins generating text content. EventTextStart EventType = "text_start" // EventTextEnd fires when the LLM finishes generating text content. EventTextEnd EventType = "text_end" // EventReasoningStart fires when the LLM begins reasoning/thinking. EventReasoningStart EventType = "reasoning_start" // EventWarnings fires when the LLM provider returns warnings. EventWarnings EventType = "warnings" // EventSource fires when the LLM references a source (e.g. from web search). EventSource EventType = "source" // EventStreamFinish fires when a per-step LLM stream completes with // usage stats and a finish reason. EventStreamFinish EventType = "stream_finish" // EventError fires when an agent-level error occurs during streaming. // This is distinct from TurnEndEvent.Error — it fires at the point of // failure, before the turn ends. EventError EventType = "error" // EventRetry fires when the LLM provider request is retried after a // transient error. EventRetry EventType = "retry" )
type ExtensionAPI ¶ added in v0.30.0
type ExtensionAPI interface {
// Context management
SetContext(ctx extensions.Context)
GetContext() extensions.Context
UpdateContextModel(model string)
// Widgets
SetWidget(config extensions.WidgetConfig)
RemoveWidget(id string)
GetWidgets(placement extensions.WidgetPlacement) []extensions.WidgetConfig
// Header/Footer
SetHeader(config extensions.HeaderFooterConfig)
RemoveHeader()
GetHeader() *extensions.HeaderFooterConfig
// Editor
SetEditor(config extensions.EditorConfig)
ResetEditor()
GetEditor() *extensions.EditorConfig
// UI Visibility
SetUIVisibility(v extensions.UIVisibility)
GetUIVisibility() *extensions.UIVisibility
// Tool rendering
GetToolRenderer(toolName string) *extensions.ToolRenderConfig
GetMessageRenderer(name string) *extensions.MessageRendererConfig
// Session data
GetSessionMessages() []extensions.SessionMessage
AppendEntry(extType, data string) (string, error)
GetEntries(extType string) []extensions.ExtensionEntry
// Status bar
SetStatus(entry extensions.StatusBarEntry)
RemoveStatus(key string)
GetStatusEntries() []extensions.StatusBarEntry
// Shortcuts
GetShortcuts() map[string]func()
// Tools
GetToolInfos() []extensions.ToolInfo
SetActiveTools(names []string)
// Options
GetOption(name string) string
SetOption(name, value string)
// Events
EmitSessionStart()
EmitModelChange(newModel, previousModel, source string)
EmitCustomEvent(name, data string)
EmitBeforeFork(targetID string, isUserMsg bool, userText string) (cancelled bool, reason string)
EmitBeforeSessionSwitch(switchReason string) (cancelled bool, reason string)
// Commands
Commands() []extensions.CommandDef
// Lifecycle
Reload() error
HasExtensions() bool
}
ExtensionAPI provides grouped access to all extension-related functionality. This cleans up the main Kit API surface while keeping all extension capabilities available.
type ExtensionDataEntry ¶ added in v0.42.0
ExtensionDataEntry represents custom extension data stored in the session.
type FileDiffInfo ¶ added in v0.12.0
type FileDiffInfo struct {
Path string `json:"path"` // Absolute file path
Additions int `json:"additions"` // Lines added
Deletions int `json:"deletions"` // Lines removed
IsNew bool `json:"is_new,omitempty"` // True if file was created (write only)
DiffBlocks []DiffBlock `json:"diff_blocks,omitempty"`
}
FileDiffInfo describes a file modification from an edit or write tool.
type HookPriority ¶
type HookPriority int
HookPriority controls execution order of hooks. Lower values run first.
const ( // HookPriorityHigh runs before normal hooks. HookPriorityHigh HookPriority = 0 // HookPriorityNormal is the default priority. HookPriorityNormal HookPriority = 50 // HookPriorityLow runs after normal hooks. HookPriorityLow HookPriority = 100 )
type Kit ¶
type Kit struct {
// contains filtered or unexported fields
}
Kit provides programmatic access to kit functionality, allowing integration of MCP tools and LLM interactions into Go applications. It manages agents, sessions, and model configurations.
func New ¶
New creates a Kit instance using the same initialization as the CLI. It loads configuration, initializes MCP servers, creates the LLM model, and sets up the agent for interaction. Returns an error if initialization fails.
Global viper state warning: fields on Options are applied by calling viper.Set on viper's process-global store. As a result, two Kits constructed in the same process are NOT isolated: the second New overwrites viper keys set by the first, and any downstream reader (e.g. Kit.SetModel, Kit.GetThinkingLevel) will observe the most recent value. Callers that need multiple independent Kits should call viper.Reset() between constructions, or avoid constructing more than one Kit per process. Writes during New are serialized by [viperInitMu].
TODO: refactor to use a per-call viper.New() instance so each Kit owns its own isolated config store and Options stop leaking through the global singleton.
func (*Kit) AddInProcessMCPServer ¶ added in v0.52.0
AddInProcessMCPServer connects an in-process mcp-go server and makes its tools available to the agent immediately. Unlike [AddMCPServer] with a command/URL config, this uses mcp-go's in-process transport — no subprocess is spawned and no network I/O occurs.
The server must be a *server.MCPServer from github.com/mark3labs/mcp-go/server. Kit does not take ownership of the server's lifecycle; the caller is responsible for any cleanup when the server is no longer needed.
Returns the number of tools loaded from the server.
Example:
import (
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)
mcpSrv := server.NewMCPServer("my-tools", "1.0.0",
server.WithToolCapabilities(true),
)
mcpSrv.AddTool(mcp.NewTool("search_docs",
mcp.WithDescription("Search documentation"),
mcp.WithString("query", mcp.Required()),
), searchHandler)
n, err := k.AddInProcessMCPServer(ctx, "docs", mcpSrv)
func (*Kit) AddMCPServer ¶ added in v0.47.0
AddMCPServer connects to a new MCP server at runtime and makes its tools available to the agent immediately. The server's tools are prefixed with the server name (e.g. "myserver__tool_name") to avoid naming conflicts, matching the behaviour of servers loaded at initialization.
Returns the number of tools loaded from the server.
AddMCPServer is safe to call while the agent is idle. If a turn is in progress (Kit.IsGenerating returns true), the new tools will be visible starting from the next LLM step.
Example:
n, err := k.AddMCPServer(ctx, "github", kit.MCPServerConfig{
Command: []string{"npx", "-y", "@modelcontextprotocol/server-github"},
Environment: map[string]string{"GITHUB_TOKEN": os.Getenv("GITHUB_TOKEN")},
})
func (*Kit) Branch ¶
Branch moves the session's leaf pointer to the given entry ID, creating a branch point. Subsequent Prompt() calls will extend from the new position.
func (*Kit) CancelMCPTask ¶ added in v0.64.0
CancelMCPTask issues tasks/cancel for an in-flight task on the named server. Returns the post-cancel task state when the server responded with one. Cancelling an already-terminal task is a no-op on most servers.
func (*Kit) ClearSession ¶
func (m *Kit) ClearSession()
ClearSession resets the session's leaf pointer to the root, starting a fresh conversation branch.
func (*Kit) ClearSkillCache ¶ added in v0.28.0
func (m *Kit) ClearSkillCache()
ClearSkillCache clears the skill cache for this Kit instance.
func (*Kit) Close ¶
Close cleans up resources including MCP server connections, model resources, and the tree session file handle. Should be called when the Kit instance is no longer needed. Returns an error if cleanup fails.
func (*Kit) CollapseBranch ¶ added in v0.28.0
CollapseBranch replaces a branch range with a summary entry. Returns an error if the session is unavailable or the operation fails.
func (*Kit) Compact ¶
func (m *Kit) Compact(ctx context.Context, opts *CompactionOptions, customInstructions string) (*CompactionResult, error)
Compact summarises older messages to reduce context usage. If opts is nil, the instance's CompactionOptions (or sensible defaults) are used. The model's context window is automatically populated from the model registry when opts.ContextWindow is 0.
customInstructions is optional text appended to the summary prompt (e.g. "Focus on the API design decisions"). Pass "" for the default prompt.
Compaction is non-destructive: a CompactionEntry is appended to the session tree recording the summary and the first kept entry ID. Old messages remain on disk but are skipped when building the LLM context — the summary is injected in their place.
func (*Kit) DiscoverSkillsForExtension ¶ added in v0.28.0
func (m *Kit) DiscoverSkillsForExtension() []extensions.Skill
DiscoverSkillsForExtension finds skills in standard locations for extensions. Returns skills in the extension-facing format. Results are cached per-Kit instance to avoid reloading on every call.
func (*Kit) DrainSteer ¶ added in v0.24.0
func (m *Kit) DrainSteer() []agent.SteerMessage
DrainSteer removes and returns all unconsumed steer messages. Called after a turn completes so the app layer can process any steer messages that arrived after the last PrepareStep fired (e.g. during a text-only response with no tool calls, or after the agent finished its last step).
func (*Kit) EstimateContextTokens ¶
EstimateContextTokens returns the estimated token count of the current conversation based on session messages.
func (*Kit) ExecuteCompletion ¶ added in v0.3.0
func (m *Kit) ExecuteCompletion(ctx context.Context, req extensions.CompleteRequest) (extensions.CompleteResponse, error)
ExecuteCompletion makes a standalone LLM completion call for extensions. When req.Model is empty the current agent model is reused (no provider creation overhead). When req.Model is set a temporary provider is created, used, and closed.
func (*Kit) Extensions ¶ added in v0.30.0
func (m *Kit) Extensions() ExtensionAPI
Extensions returns the ExtensionAPI for accessing all extension-related functionality.
func (*Kit) FollowUp ¶
FollowUp continues the conversation without explicit new user input. If text is empty, "Continue." is used as the prompt. Use FollowUp when the agent's previous response was truncated or you want the agent to elaborate.
Returns an error if there are no previous messages in the session.
func (*Kit) GetAvailableModels ¶ added in v0.3.0
func (m *Kit) GetAvailableModels() []extensions.ModelInfoEntry
GetAvailableModels returns a list of known models from the registry. Each entry includes provider, model ID, context limit, and whether the model supports reasoning. This is an advisory list — models not in the registry can still be used by specifying their provider/model string.
func (*Kit) GetBufferedDebugMessages ¶ added in v0.2.0
GetBufferedDebugMessages returns any debug messages that were buffered during initialization, then clears the buffer. Returns nil if no messages were buffered or if buffered logging was not configured.
func (*Kit) GetChildren ¶ added in v0.28.0
GetChildren returns direct child IDs of an entry.
func (*Kit) GetContextFiles ¶
func (m *Kit) GetContextFiles() []*ContextFile
GetContextFiles returns the context files (e.g. AGENTS.md) loaded during initialisation. Returns nil if no context files were found.
func (*Kit) GetContextStats ¶
func (m *Kit) GetContextStats() ContextStats
GetContextStats returns current context usage statistics including estimated token count, context limit, usage percentage, and message count.
When API-reported token counts are available (after at least one turn), EstimatedTokens uses the real input token count from the most recent API response. This is significantly more accurate than the text-based heuristic because it includes system prompts, tool definitions, and other overhead that the heuristic cannot account for.
func (*Kit) GetCurrentBranch ¶ added in v0.28.0
GetCurrentBranch returns the path from root to current leaf as TreeNodes.
func (*Kit) GetExtensionToolCount ¶ added in v0.2.0
GetExtensionToolCount returns the number of tools registered by extensions.
func (*Kit) GetLoadedServerNames ¶ added in v0.2.0
GetLoadedServerNames returns the names of successfully loaded MCP servers. If MCP servers are still loading in the background, this returns only the servers that have completed loading so far.
func (*Kit) GetLoadingMessage ¶ added in v0.2.0
GetLoadingMessage returns the agent's startup info message (e.g. GPU fallback info), or empty string if none.
func (*Kit) GetMCPPrompt ¶ added in v0.51.0
func (m *Kit) GetMCPPrompt(ctx context.Context, serverName, promptName string, args map[string]string) (*MCPPromptResult, error)
GetMCPPrompt retrieves and expands a specific prompt from an MCP server. This is a lazy call — the server is contacted each time to get the latest prompt content. Arguments are passed as key=value pairs to the server for template substitution.
Returns an error if the server is not found or the prompt expansion fails.
func (*Kit) GetMCPTask ¶ added in v0.64.0
GetMCPTask queries tasks/get for a single in-flight task on the named server. The returned MCPTask reflects the server's current view of the task.
func (*Kit) GetMCPToolCount ¶ added in v0.2.0
GetMCPToolCount returns the number of tools loaded from external MCP servers. If MCP servers are still loading in the background, this returns the count of tools loaded so far (may be 0).
func (*Kit) GetModelInfo ¶
GetModelInfo returns detailed information about the current model (capabilities, pricing, limits). Returns nil if the model is not in the registry — this is expected for new models or custom fine-tunes.
func (*Kit) GetModelString ¶
GetModelString returns the current model string identifier (e.g., "anthropic/claude-sonnet-4-5-20250929" or "openai/gpt-4") being used by the agent.
func (*Kit) GetSessionID ¶
GetSessionID returns the UUID of the active session, or empty when no session is configured.
func (*Kit) GetSessionManager ¶ added in v0.42.0
func (m *Kit) GetSessionManager() SessionManager
GetSessionManager returns the session manager, or nil if not configured.
func (*Kit) GetSessionPath ¶
GetSessionPath returns the file path of the active session, or empty for in-memory sessions or when no file-based session is configured.
func (*Kit) GetStructuredMessages ¶ added in v0.12.0
func (m *Kit) GetStructuredMessages() []StructuredMessage
GetStructuredMessages returns the conversation messages on the current branch with full typed content parts. Unlike GetSessionMessages() which flattens all content to a single text string, this preserves tool calls, tool results, reasoning blocks, and finish markers as distinct typed parts.
func (*Kit) GetThinkingLevel ¶ added in v0.7.0
GetThinkingLevel returns the current thinking level.
func (*Kit) GetToolNames ¶ added in v0.2.0
GetToolNames returns the names of all tools available to the agent.
func (*Kit) GetTreeNode ¶ added in v0.28.0
GetTreeNode returns a node by ID with full metadata and children. Returns nil if entry not found or no session.
func (*Kit) GetTreeSession ¶
func (m *Kit) GetTreeSession() *TreeManager
GetTreeSession returns the tree session manager, or nil if not configured. Deprecated: Use GetSessionManager instead.
func (*Kit) InjectSteer ¶ added in v0.24.0
InjectSteer sends a steering message into the currently active agent turn. The message will be injected as a user message between steps (after the current tool execution finishes, before the next LLM call). If no turn is active the message is silently dropped — callers should check IsGenerating() or use Prompt()/Steer() for idle-state messaging.
InjectSteer is safe to call from any goroutine. Multiple calls queue messages in order; all pending steer messages are drained and injected together at the next step boundary.
This is the preferred way to redirect an agent mid-turn without cancelling in-progress tool execution.
func (*Kit) InjectSteerWithFiles ¶ added in v0.36.0
func (m *Kit) InjectSteerWithFiles(message string, files []LLMFilePart)
InjectSteerWithFiles sends a steering message with optional file attachments (e.g. pasted images) into the currently active agent turn. Behaves like InjectSteer but includes file parts in the injected user message.
func (*Kit) IsGenerating ¶ added in v0.24.0
IsGenerating returns true if an agent turn is currently in progress. Use this to decide between InjectSteer (mid-turn) and Prompt (new turn).
func (*Kit) IsReasoningModel ¶ added in v0.7.0
IsReasoningModel returns true if the current model supports extended thinking / reasoning.
func (*Kit) ListMCPPrompts ¶ added in v0.51.0
ListMCPPrompts returns all prompts discovered from connected MCP servers. If MCP servers are still loading in the background, this returns only the prompts discovered so far. Returns nil if no prompts are available.
func (*Kit) ListMCPResources ¶ added in v0.51.0
func (m *Kit) ListMCPResources() []MCPResource
ListMCPResources returns all resources discovered from connected MCP servers. If MCP servers are still loading in the background, this returns only the resources discovered so far. Returns nil if no resources are available.
func (*Kit) ListMCPServers ¶ added in v0.47.0
func (m *Kit) ListMCPServers() []MCPServerStatus
ListMCPServers returns the status of all currently loaded MCP servers. The returned slice is a snapshot; it is safe to read concurrently.
func (*Kit) ListMCPTasks ¶ added in v0.64.0
ListMCPTasks queries tasks/list on the named MCP server and returns the active and recent tasks the server is willing to disclose. Returns an error when the server isn't loaded, doesn't expose tasks/list, or the underlying transport fails.
func (*Kit) LoadSkillForExtension ¶ added in v0.28.0
func (m *Kit) LoadSkillForExtension(path string) (*extensions.Skill, string)
LoadSkillForExtension loads a single skill file for extensions.
func (*Kit) LoadSkillsFromDirForExtension ¶ added in v0.28.0
func (m *Kit) LoadSkillsFromDirForExtension(dir string) extensions.SkillLoadResult
LoadSkillsFromDirForExtension loads all skills from a directory for extensions.
func (*Kit) MCPToolsReady ¶ added in v0.41.0
MCPToolsReady returns true if MCP tool loading has completed (or was never started). This is a non-blocking check useful for UI status display.
func (*Kit) MaxOutputLimit ¶ added in v0.54.0
MaxOutputLimit returns the catalog-reported output ceiling for the current model in tokens, or 0 when the model isn't in the registry (custom models, new releases, Ollama, etc.). Pair with MaxTokens() to detect when the agent is configured well below what the model supports and surface a hint to the user.
func (*Kit) MaxTokens ¶ added in v0.54.0
MaxTokens returns the effective max output tokens currently configured for the agent. This is the value actually sent to the LLM provider on each request, after CLI/env/config resolution, per-model overrides, model-aware right-sizing, and any Anthropic thinking-budget adjustments.
Returns 0 when the active provider suppresses the max_output_tokens parameter (e.g. OpenAI Codex OAuth) or when no model is configured yet. A non-zero value is the number that will cause a FinishReasonLength truncation if the model tries to generate beyond it.
func (*Kit) NavigateTo ¶ added in v0.28.0
NavigateTo branches/forks the session to the specified entry ID. Returns an error if the session is unavailable or the entry ID is not found.
func (*Kit) OnAfterToolResult ¶
func (m *Kit) OnAfterToolResult(p HookPriority, h func(AfterToolResultHook) *AfterToolResultResult) func()
OnAfterToolResult registers a hook that fires after each tool execution. Return a non-nil AfterToolResultResult to modify the tool's output before it reaches the LLM. Hooks execute in priority order; the first non-nil result wins. Returns an unregister function.
func (*Kit) OnAfterTurn ¶
func (m *Kit) OnAfterTurn(p HookPriority, h func(AfterTurnHook)) func()
OnAfterTurn registers a hook that fires after each prompt turn completes. This is observation-only — the handler cannot modify the response. Hooks execute in priority order. Returns an unregister function.
func (*Kit) OnBeforeCompact ¶ added in v0.3.0
func (m *Kit) OnBeforeCompact(p HookPriority, h func(BeforeCompactHook) *BeforeCompactResult) func()
OnBeforeCompact registers a hook that fires before context compaction runs. Return a non-nil BeforeCompactResult with Cancel=true to prevent compaction. Hooks execute in priority order; the first non-nil result wins. Returns an unregister function.
func (*Kit) OnBeforeToolCall ¶
func (m *Kit) OnBeforeToolCall(p HookPriority, h func(BeforeToolCallHook) *BeforeToolCallResult) func()
OnBeforeToolCall registers a hook that fires before each tool execution. Return a non-nil BeforeToolCallResult with Block=true to prevent the tool from running. Hooks execute in priority order; the first non-nil result wins. Returns an unregister function.
func (*Kit) OnBeforeTurn ¶
func (m *Kit) OnBeforeTurn(p HookPriority, h func(BeforeTurnHook) *BeforeTurnResult) func()
OnBeforeTurn registers a hook that fires before each prompt turn. Return a non-nil BeforeTurnResult to modify the prompt, inject a system message, or prepend context. Hooks execute in priority order; the first non-nil result wins. Returns an unregister function.
func (*Kit) OnCompaction ¶ added in v0.60.0
func (m *Kit) OnCompaction(handler func(CompactionEvent)) func()
OnCompaction registers a handler that fires only for CompactionEvent. Returns an unsubscribe function.
func (*Kit) OnContextPrepare ¶ added in v0.3.0
func (m *Kit) OnContextPrepare(p HookPriority, h func(ContextPrepareHook) *ContextPrepareResult) func()
OnContextPrepare registers a hook that fires after the context window is built from the session tree and before messages are sent to the LLM. Return a non-nil ContextPrepareResult with Messages to replace the entire context. Hooks execute in priority order; the first non-nil result wins. Returns an unregister function.
func (*Kit) OnError ¶ added in v0.60.0
func (m *Kit) OnError(handler func(ErrorEvent)) func()
OnError registers a handler that fires only for ErrorEvent. Returns an unsubscribe function.
func (*Kit) OnMessageEnd ¶ added in v0.60.0
func (m *Kit) OnMessageEnd(handler func(MessageEndEvent)) func()
OnMessageEnd registers a handler that fires only for MessageEndEvent. Returns an unsubscribe function.
func (*Kit) OnMessageStart ¶ added in v0.60.0
func (m *Kit) OnMessageStart(handler func(MessageStartEvent)) func()
OnMessageStart registers a handler that fires only for MessageStartEvent. Returns an unsubscribe function.
func (*Kit) OnMessageUpdate ¶ added in v0.60.0
func (m *Kit) OnMessageUpdate(handler func(MessageUpdateEvent)) func()
OnMessageUpdate registers a handler that fires only for MessageUpdateEvent (streaming text chunks). Returns an unsubscribe function.
func (*Kit) OnPrepareStep ¶ added in v0.60.0
func (m *Kit) OnPrepareStep(p HookPriority, h func(PrepareStepHook) *PrepareStepResult) func()
OnPrepareStep registers a hook that fires between steps within a multi-step agent turn, after steering messages are injected and before the messages are sent to the LLM. Return a non-nil PrepareStepResult with Messages to replace the entire context window for this step. Hooks execute in priority order; the first non-nil result wins. Returns an unregister function.
This is the most powerful interception point in the agent lifecycle. It enables patterns like transforming tool results, dynamic tool filtering, and mid-turn context injection.
func (*Kit) OnReasoningComplete ¶ added in v0.60.0
func (m *Kit) OnReasoningComplete(handler func(ReasoningCompleteEvent)) func()
OnReasoningComplete registers a handler that fires only for ReasoningCompleteEvent. Returns an unsubscribe function.
func (*Kit) OnReasoningDelta ¶ added in v0.60.0
func (m *Kit) OnReasoningDelta(handler func(ReasoningDeltaEvent)) func()
OnReasoningDelta registers a handler that fires only for ReasoningDeltaEvent. Returns an unsubscribe function.
func (*Kit) OnReasoningStart ¶ added in v0.60.0
func (m *Kit) OnReasoningStart(handler func(ReasoningStartEvent)) func()
OnReasoningStart registers a handler that fires only for ReasoningStartEvent. Returns an unsubscribe function.
func (*Kit) OnResponse ¶
func (m *Kit) OnResponse(handler func(ResponseEvent)) func()
OnResponse registers a handler that fires only for ResponseEvent. Returns an unsubscribe function.
func (*Kit) OnRetry ¶ added in v0.60.0
func (m *Kit) OnRetry(handler func(RetryEvent)) func()
OnRetry registers a handler that fires only for RetryEvent. Returns an unsubscribe function.
func (*Kit) OnSource ¶ added in v0.60.0
func (m *Kit) OnSource(handler func(SourceEvent)) func()
OnSource registers a handler that fires only for SourceEvent. Returns an unsubscribe function.
func (*Kit) OnSteerConsumed ¶ added in v0.60.0
func (m *Kit) OnSteerConsumed(handler func(SteerConsumedEvent)) func()
OnSteerConsumed registers a handler that fires only for SteerConsumedEvent. Returns an unsubscribe function.
func (*Kit) OnStepFinish ¶ added in v0.60.0
func (m *Kit) OnStepFinish(handler func(StepFinishEvent)) func()
OnStepFinish registers a handler that fires only for StepFinishEvent. Returns an unsubscribe function.
func (*Kit) OnStepStart ¶ added in v0.60.0
func (m *Kit) OnStepStart(handler func(StepStartEvent)) func()
OnStepStart registers a handler that fires only for StepStartEvent. Returns an unsubscribe function.
func (*Kit) OnStepUsage ¶ added in v0.60.0
func (m *Kit) OnStepUsage(handler func(StepUsageEvent)) func()
OnStepUsage registers a handler that fires only for StepUsageEvent. Returns an unsubscribe function.
func (*Kit) OnStreamFinish ¶ added in v0.60.0
func (m *Kit) OnStreamFinish(handler func(StreamFinishEvent)) func()
OnStreamFinish registers a handler that fires only for StreamFinishEvent. Returns an unsubscribe function.
func (*Kit) OnStreaming
deprecated
func (m *Kit) OnStreaming(handler func(MessageUpdateEvent)) func()
OnStreaming registers a handler that fires only for MessageUpdateEvent (streaming text chunks). Returns an unsubscribe function.
Deprecated: Use OnMessageUpdate instead. OnStreaming will be removed in a future release.
func (*Kit) OnTextEnd ¶ added in v0.60.0
func (m *Kit) OnTextEnd(handler func(TextEndEvent)) func()
OnTextEnd registers a handler that fires only for TextEndEvent. Returns an unsubscribe function.
func (*Kit) OnTextStart ¶ added in v0.60.0
func (m *Kit) OnTextStart(handler func(TextStartEvent)) func()
OnTextStart registers a handler that fires only for TextStartEvent. Returns an unsubscribe function.
func (*Kit) OnToolCall ¶
func (m *Kit) OnToolCall(handler func(ToolCallEvent)) func()
OnToolCall registers a handler that fires only for ToolCallEvent. Returns an unsubscribe function.
func (*Kit) OnToolCallContent ¶ added in v0.60.0
func (m *Kit) OnToolCallContent(handler func(ToolCallContentEvent)) func()
OnToolCallContent registers a handler that fires only for ToolCallContentEvent. Returns an unsubscribe function.
func (*Kit) OnToolCallDelta ¶ added in v0.58.0
func (m *Kit) OnToolCallDelta(handler func(ToolCallDeltaEvent)) func()
OnToolCallDelta registers a handler that fires only for ToolCallDeltaEvent. Each delta contains a JSON fragment of tool call arguments as they stream in. Returns an unsubscribe function.
func (*Kit) OnToolCallEnd ¶ added in v0.58.0
func (m *Kit) OnToolCallEnd(handler func(ToolCallEndEvent)) func()
OnToolCallEnd registers a handler that fires only for ToolCallEndEvent. This fires when tool argument streaming is complete, before the tool call is parsed and execution begins. Returns an unsubscribe function.
func (*Kit) OnToolCallStart ¶ added in v0.58.0
func (m *Kit) OnToolCallStart(handler func(ToolCallStartEvent)) func()
OnToolCallStart registers a handler that fires only for ToolCallStartEvent. This fires when the LLM begins generating tool call arguments — before the full argument JSON is available. Returns an unsubscribe function.
func (*Kit) OnToolExecutionEnd ¶ added in v0.60.0
func (m *Kit) OnToolExecutionEnd(handler func(ToolExecutionEndEvent)) func()
OnToolExecutionEnd registers a handler that fires only for ToolExecutionEndEvent. Returns an unsubscribe function.
func (*Kit) OnToolExecutionStart ¶ added in v0.60.0
func (m *Kit) OnToolExecutionStart(handler func(ToolExecutionStartEvent)) func()
OnToolExecutionStart registers a handler that fires only for ToolExecutionStartEvent. Returns an unsubscribe function.
func (*Kit) OnToolOutput ¶ added in v0.20.0
func (m *Kit) OnToolOutput(handler func(ToolOutputEvent)) func()
OnToolOutput registers a handler that fires only for ToolOutputEvent (streaming tool output chunks, e.g., from bash). Returns an unsubscribe function.
func (*Kit) OnToolResult ¶
func (m *Kit) OnToolResult(handler func(ToolResultEvent)) func()
OnToolResult registers a handler that fires only for ToolResultEvent. Returns an unsubscribe function.
func (*Kit) OnTurnEnd ¶
func (m *Kit) OnTurnEnd(handler func(TurnEndEvent)) func()
OnTurnEnd registers a handler that fires only for TurnEndEvent. Returns an unsubscribe function.
func (*Kit) OnTurnStart ¶
func (m *Kit) OnTurnStart(handler func(TurnStartEvent)) func()
OnTurnStart registers a handler that fires only for TurnStartEvent. Returns an unsubscribe function.
func (*Kit) OnWarnings ¶ added in v0.60.0
func (m *Kit) OnWarnings(handler func(WarningsEvent)) func()
OnWarnings registers a handler that fires only for WarningsEvent. Returns an unsubscribe function.
func (*Kit) Prompt ¶
Prompt sends a message to the agent and returns the response. The agent may use tools as needed to generate the response. The conversation history is automatically maintained in the tree session. Lifecycle events are emitted to all registered subscribers. Returns an error if generation fails.
func (*Kit) PromptResult ¶
PromptResult sends a message and returns the full turn result including usage statistics and conversation messages. Use this instead of Prompt() when you need more than just the response text.
func (*Kit) PromptResultWithFiles ¶ added in v0.7.0
func (m *Kit) PromptResultWithFiles(ctx context.Context, message string, files []LLMFilePart) (*TurnResult, error)
PromptResultWithFiles sends a multimodal message (text + images) and returns the full turn result. The files parameter carries binary file data (e.g. clipboard images) that are included alongside the text in the user message.
func (*Kit) PromptResultWithMessages ¶ added in v0.15.3
PromptResultWithMessages submits multiple user messages in a single turn. All messages are persisted to the session and sent to the agent together. The agent will respond once to the combined context of all messages. Returns the full turn result including usage statistics and conversation messages.
func (*Kit) PromptWithOptions ¶
func (m *Kit) PromptWithOptions(ctx context.Context, msg string, opts PromptOptions) (string, error)
PromptWithOptions sends a message with per-call configuration. It behaves like Prompt but allows injecting an additional system message before the user prompt. Both messages are persisted to the session.
func (*Kit) ReadMCPResource ¶ added in v0.51.0
func (m *Kit) ReadMCPResource(ctx context.Context, serverName, uri string) (*MCPResourceContent, error)
ReadMCPResource reads a specific resource from an MCP server by URI. Returns the resource content (text or binary blob).
func (*Kit) ReloadExtensions ¶ added in v0.3.0
ReloadExtensions hot-reloads all extensions from disk. Event handlers, commands, renderers, shortcuts, and extension-defined tools all update immediately.
func (*Kit) ReloadSkills ¶ added in v0.41.0
ReloadSkills re-discovers skills from disk, replacing the current set. This is called by file watchers when skill files change.
func (*Kit) RemoveMCPServer ¶ added in v0.47.0
RemoveMCPServer disconnects an MCP server and removes all its tools from the agent. After this call the agent will no longer see or be able to call tools from the named server.
RemoveMCPServer is safe to call while the agent is idle. If a turn is in progress, the tools are removed at the next LLM step. Any in-flight tool calls to the removed server will fail gracefully.
Returns an error if the named server is not currently loaded.
func (*Kit) SetModel ¶ added in v0.3.0
SetModel changes the active model at runtime. The existing tools and session are preserved. When the new model has a per-model system prompt (from modelSettings or customModels params), it is composed with the current AGENTS.md context and skills before being applied. The model string should be in "provider/model" format (e.g. "anthropic/claude-sonnet-4-5-20250929"). Returns an error if the model string is invalid or the provider cannot be created.
func (*Kit) SetSessionManager ¶ added in v0.42.0
func (m *Kit) SetSessionManager(sm SessionManager)
SetSessionManager replaces the session manager on a Kit instance.
func (*Kit) SetSessionName ¶
SetSessionName sets a user-defined display name for the active session.
func (*Kit) SetThinkingLevel ¶ added in v0.7.0
SetThinkingLevel changes the thinking level and recreates the agent with the new thinking budget. Returns an error if provider recreation fails.
With message-level caching, both thinking and caching work together. Caching reduces costs by 60-90% for repeated context.
func (*Kit) SetTreeSession ¶
func (m *Kit) SetTreeSession(ts *TreeManager)
SetTreeSession replaces the tree session on a Kit instance. This is used by the CLI when it handles session creation externally (e.g. --resume with a TUI picker) and needs to inject the result into a Kit-like workflow. Deprecated: Use SetSessionManager instead.
func (*Kit) ShouldCompact ¶
ShouldCompact reports whether the conversation is near the model's context limit and should be compacted. Formula: contextTokens > contextWindow − reserveTokens. Returns false if the model's context limit is unknown.
When API-reported token counts are available (after at least one turn), the real count is used instead of the text-based heuristic. This is significantly more accurate because it includes system prompts, tool definitions, and other overhead that the heuristic cannot account for.
func (*Kit) Steer ¶
Steer injects a system-level instruction and triggers a new agent turn. Use Steer to dynamically adjust agent behavior mid-conversation without a visible user message — for example, changing tone, focus, or constraints.
Under the hood, Steer appends a system message (the instruction) followed by a synthetic user message so the agent acknowledges and follows the directive. Both messages are persisted to the session.
func (*Kit) Subagent ¶ added in v0.12.0
func (m *Kit) Subagent(ctx context.Context, cfg SubagentConfig) (*SubagentResult, error)
Subagent spawns an in-process child Kit instance to perform a task. The child gets its own session, event bus, and agent loop but shares the parent's config (API keys, provider settings) and defaults to the parent's model when SubagentConfig.Model is empty.
This is the recommended way to run subagents in the SDK — no subprocess, no kit binary dependency, native Go types for results.
func (*Kit) Subscribe ¶
func (m *Kit) Subscribe(listener EventListener) func()
Subscribe registers an EventListener that will be called for every lifecycle event emitted during Prompt(). Returns an unsubscribe function that removes the listener.
func (*Kit) SubscribeMCPResource ¶ added in v0.51.0
SubscribeMCPResource subscribes to change notifications for a resource. When the resource changes on the server, the resource list is refreshed.
func (*Kit) SubscribeSubagent ¶ added in v0.17.0
func (m *Kit) SubscribeSubagent(toolCallID string, listener EventListener) func()
SubscribeSubagent registers a listener for real-time events from a subagent identified by its tool call ID. Returns an unsubscribe function.
The listener receives the same event types as Subscribe() (ToolCallEvent, MessageUpdateEvent, etc.) but scoped to the child agent's activity. If the tool call ID doesn't correspond to an active or future subagent call, the listener simply never fires.
Typical usage — register inside an OnToolCall handler:
kit.OnToolCall(func(e kit.ToolCallEvent) {
if e.ToolName == "subagent" {
kit.SubscribeSubagent(e.ToolCallID, func(child kit.Event) {
// real-time subagent events
})
}
})
func (*Kit) SummarizeBranch ¶ added in v0.28.0
SummarizeBranch uses the LLM to summarize the conversation between two entry IDs. Returns the summary text, or an error if the range is invalid, the session is unavailable, or the LLM call fails.
func (*Kit) UnsubscribeMCPResource ¶ added in v0.51.0
UnsubscribeMCPResource cancels change notifications for a resource.
func (*Kit) WaitForMCPTools ¶ added in v0.41.0
WaitForMCPTools blocks until background MCP tool loading completes. Returns nil if no MCP servers are configured or if loading succeeded. Returns the loading error if all servers failed. Safe to call multiple times.
type LLMFilePart ¶ added in v0.30.0
LLMFilePart represents a file attachment (image, document, audio, etc.) that can be included in a multimodal prompt via PromptResultWithFiles.
type LLMFinishReason ¶ added in v0.33.0
type LLMFinishReason = fantasy.FinishReason
LLMFinishReason indicates why the LLM stopped generating.
type LLMMessage ¶ added in v0.30.0
LLMMessage represents a message in an LLM conversation, carrying a role and a slice of typed content parts (text, tool calls, reasoning, etc.).
func ConvertToLLMMessages ¶ added in v0.30.0
func ConvertToLLMMessages(msg *Message) []LLMMessage
ConvertToLLMMessages converts an SDK message to a slice of LLMMessages. Each SDK message may expand to multiple LLM messages depending on its content.
type LLMMessagePart ¶ added in v0.33.0
type LLMMessagePart = fantasy.MessagePart
LLMMessagePart is the interface implemented by all LLM message content parts.
type LLMMessageRole ¶ added in v0.33.0
type LLMMessageRole = fantasy.MessageRole
LLMMessageRole identifies the participant role in an LLM conversation.
type LLMPrompt ¶ added in v0.61.0
LLMPrompt is an ordered sequence of LLMMessage values forming a complete prompt for the LLM.
type LLMProviderMetadata ¶ added in v0.61.0
type LLMProviderMetadata = fantasy.ProviderMetadata
LLMProviderMetadata carries provider-specific metadata returned alongside LLM responses, keyed by provider name.
type LLMProviderOptions ¶ added in v0.61.0
type LLMProviderOptions = fantasy.ProviderOptions
LLMProviderOptions carries provider-specific key/value option maps, keyed by provider name (e.g. "anthropic"). Use this when configuring or inspecting provider-specific tool behaviour.
type LLMReasoningPart ¶ added in v0.33.0
type LLMReasoningPart = fantasy.ReasoningPart
LLMReasoningPart is a reasoning/chain-of-thought content part.
type LLMResponse ¶ added in v0.30.0
LLMResponse represents a complete response from the LLM provider.
type LLMTextPart ¶ added in v0.33.0
LLMTextPart is a plain-text content part for constructing LLM messages.
type LLMToolCall ¶ added in v0.59.0
LLMToolCall represents the raw tool invocation passed to a Tool's Run method. It carries the call ID, tool name, and the JSON-encoded input arguments from the LLM. This is the execution-layer call object — distinct from ToolCall (a message content part).
type LLMToolCallPart ¶ added in v0.33.0
type LLMToolCallPart = fantasy.ToolCallPart
LLMToolCallPart represents an LLM-initiated tool invocation within a message.
type LLMToolInfo ¶ added in v0.61.0
LLMToolInfo describes a tool's name, description, and JSON-Schema parameters.
type LLMToolResponse ¶ added in v0.59.0
type LLMToolResponse = fantasy.ToolResponse
LLMToolResponse represents the raw response returned from a Tool's Run method. Most SDK consumers should use ToolOutput with NewTool / NewParallelTool instead — this alias is provided for advanced use cases that need to call Tool.Run() directly (e.g. testing).
type LLMToolResultContentType ¶ added in v0.61.0
type LLMToolResultContentType = fantasy.ToolResultContentType
LLMToolResultContentType classifies the kind of a tool result output ("text", "error", or "media").
type LLMToolResultOutputContent ¶ added in v0.33.0
type LLMToolResultOutputContent = fantasy.ToolResultOutputContent
LLMToolResultOutputContent is the interface for tool result output content.
type LLMToolResultOutputContentError ¶ added in v0.33.0
type LLMToolResultOutputContentError = fantasy.ToolResultOutputContentError
LLMToolResultOutputContentError is an error-valued tool result output.
type LLMToolResultOutputContentMedia ¶ added in v0.61.0
type LLMToolResultOutputContentMedia = fantasy.ToolResultOutputContentMedia
LLMToolResultOutputContentMedia is a media-valued tool result output (images, audio, etc.) carrying base64-encoded data and a MIME type.
type LLMToolResultOutputContentText ¶ added in v0.33.0
type LLMToolResultOutputContentText = fantasy.ToolResultOutputContentText
LLMToolResultOutputContentText is a text-valued tool result output.
type LLMToolResultPart ¶ added in v0.33.0
type LLMToolResultPart = fantasy.ToolResultPart
LLMToolResultPart represents the result of a tool execution within a message.
type LLMUsage ¶ added in v0.30.0
LLMUsage contains token usage information returned by the LLM provider.
type MCPAuthHandler ¶ added in v0.39.0
type MCPAuthHandler interface {
// RedirectURI returns the OAuth redirect URI that the callback server
// will listen on. This is called during MCP transport setup — before any
// OAuth errors occur — so the redirect URI can be registered with the
// authorization server.
RedirectURI() string
// HandleAuth is called when an MCP server requires OAuth authorization.
// It receives the server name and an authorization URL that the user must
// visit. The handler must:
// 1. Direct the user to authURL (e.g. open browser, display URL)
// 2. Listen for the OAuth callback on the redirect URI
// 3. Return the full callback URL (with code and state query params)
//
// Return an error to abort the connection to this MCP server.
// The context controls the overall timeout; implementations should
// respect ctx.Done().
HandleAuth(ctx context.Context, serverName string, authURL string) (callbackURL string, err error)
}
MCPAuthHandler handles OAuth authorization for MCP servers. Implementations control the user experience — opening a browser, showing a prompt, displaying a URL, posting to a message bus, etc.
DefaultMCPAuthHandler provides the transport mechanics (port reservation and callback server) but performs no user-facing I/O on its own; consumers wire presentation via [DefaultMCPAuthHandler.OnAuthURL] or implement MCPAuthHandler from scratch.
type MCPPrompt ¶ added in v0.51.0
type MCPPrompt struct {
// Name is the prompt name on the MCP server.
Name string
// Description is a human-readable description.
Description string
// Arguments lists the prompt's expected arguments.
Arguments []MCPPromptArgument
// ServerName is the MCP server that provides this prompt.
ServerName string
}
MCPPrompt describes a prompt exposed by an MCP server.
type MCPPromptArgument ¶ added in v0.51.0
type MCPPromptArgument struct {
// Name is the argument name.
Name string
// Description is a human-readable description.
Description string
// Required indicates whether this argument must be provided.
Required bool
}
MCPPromptArgument describes a single argument for an MCP prompt.
type MCPPromptMessage ¶ added in v0.51.0
type MCPPromptMessage struct {
// Role is "user" or "assistant".
Role string
// Content is the text content of the message.
Content string
// FileParts contains binary attachments extracted from embedded resources,
// images, or audio content blocks within the prompt message. Empty for
// text-only messages.
FileParts []LLMFilePart
}
MCPPromptMessage is a single message returned by a prompt expansion.
type MCPPromptResult ¶ added in v0.51.0
type MCPPromptResult struct {
// Description is an optional description returned by the server.
Description string
// Messages contains the expanded prompt messages.
Messages []MCPPromptMessage
}
MCPPromptResult is the result of expanding an MCP prompt.
type MCPResource ¶ added in v0.51.0
type MCPResource struct {
// URI is the unique resource identifier (e.g. "file:///path" or custom scheme).
URI string
// Name is a human-readable name for the resource.
Name string
// Description is an optional description of the resource.
Description string
// MIMEType is the MIME type of the resource, if known.
MIMEType string
// ServerName is the MCP server that provides this resource.
ServerName string
}
MCPResource describes a resource exposed by an MCP server.
type MCPResourceContent ¶ added in v0.51.0
type MCPResourceContent struct {
// URI is the resource URI that was read.
URI string
// MIMEType is the MIME type of the content.
MIMEType string
// Text is the text content (non-empty for text resources).
Text string
// BlobData is the decoded binary content (non-empty for blob resources).
BlobData []byte
// IsBlob is true when the content is binary (BlobData is set).
IsBlob bool
}
MCPResourceContent is the result of reading an MCP resource.
type MCPServer ¶ added in v0.52.0
MCPServer is an in-process MCP server from the mcp-go library. Pass an instance to Kit.AddInProcessMCPServer or [Options.InProcessMCPServers] to register tools without spawning a subprocess or making network calls.
type MCPServerConfig ¶
type MCPServerConfig = config.MCPServerConfig
MCPServerConfig represents configuration for an MCP server, supporting both local (stdio) and remote (StreamableHTTP/SSE) server types.
type MCPServerStatus ¶ added in v0.47.0
type MCPServerStatus struct {
// Name is the configured server name.
Name string
// ToolCount is the number of tools loaded from this server.
ToolCount int
}
MCPServerStatus describes the runtime state of a loaded MCP server.
type MCPTask ¶ added in v0.64.0
type MCPTask struct {
// Server is the configured MCP server name this task lives on.
Server string
// TaskID is the server-assigned identifier for the task.
TaskID string
// Status is the current task lifecycle state.
Status MCPTaskStatus
// StatusMessage is an optional human-readable description provided by
// the server.
StatusMessage string
// CreatedAt is when the task was created on the server.
CreatedAt time.Time
// UpdatedAt is when the task was last updated on the server.
UpdatedAt time.Time
// TTL is how long the server intends to retain this task after creation.
// Zero means the server did not advertise a TTL.
TTL time.Duration
// PollInterval is the suggested time between status checks. Zero means
// the client should use its own default.
PollInterval time.Duration
}
MCPTask is the SDK-level view of an MCP Task. Timestamps are best-effort parsed from the server's ISO-8601 strings; they may be the zero time when the server omitted them or used a non-RFC3339 format.
type MCPTaskMode ¶ added in v0.64.0
type MCPTaskMode string
MCPTaskMode controls when Kit augments tools/call requests with MCP task metadata for a specific server.
const ( // MCPTaskModeAuto augments tools/call with task metadata only when the // server advertises tasks/toolCalls capability during initialize. // This is the default and is safe to leave unconfigured for any // existing MCP server. MCPTaskModeAuto MCPTaskMode = MCPTaskMode(tools.MCPTaskModeAuto) // MCPTaskModeNever forces every tools/call to be issued synchronously // (no Task field), regardless of server capability. MCPTaskModeNever MCPTaskMode = MCPTaskMode(tools.MCPTaskModeNever) // MCPTaskModeAlways always opts into task augmentation, even when the // server didn't advertise the capability. The server may still respond // synchronously; this just expresses client intent unconditionally. MCPTaskModeAlways MCPTaskMode = MCPTaskMode(tools.MCPTaskModeAlways) )
type MCPTaskProgress ¶ added in v0.64.0
type MCPTaskProgress struct {
// Server is the configured MCP server name.
Server string
// TaskID is the server-assigned identifier for the in-flight task.
TaskID string
// Status is the most recent task status observed.
Status MCPTaskStatus
// Message is the optional human-readable status message from the server.
Message string
}
MCPTaskProgress is a single status update emitted while Kit is waiting on a task-augmented tool call.
type MCPTaskProgressHandler ¶ added in v0.64.0
type MCPTaskProgressHandler func(MCPTaskProgress)
MCPTaskProgressHandler is called once when a task is accepted and again on every observed status transition. The final invocation always carries a terminal status. Implementations must not block; long work should be dispatched on a goroutine.
type MCPTaskStatus ¶ added in v0.64.0
type MCPTaskStatus string
MCPTaskStatus represents the lifecycle state of a task-augmented MCP tool call. See https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/tasks for the underlying spec.
const ( // MCPTaskStatusWorking indicates the task is currently being processed. MCPTaskStatusWorking MCPTaskStatus = MCPTaskStatus(mcp.TaskStatusWorking) // MCPTaskStatusInputRequired indicates the server is waiting for client // input before it can proceed (rare; typically surfaced via elicitation). MCPTaskStatusInputRequired MCPTaskStatus = MCPTaskStatus(mcp.TaskStatusInputRequired) // MCPTaskStatusCompleted indicates the task finished successfully. MCPTaskStatusCompleted MCPTaskStatus = MCPTaskStatus(mcp.TaskStatusCompleted) // MCPTaskStatusFailed indicates the task ended in error. MCPTaskStatusFailed MCPTaskStatus = MCPTaskStatus(mcp.TaskStatusFailed) // MCPTaskStatusCancelled indicates the task was cancelled before completion. MCPTaskStatusCancelled MCPTaskStatus = MCPTaskStatus(mcp.TaskStatusCancelled) )
func (MCPTaskStatus) IsTerminal ¶ added in v0.64.0
func (s MCPTaskStatus) IsTerminal() bool
IsTerminal reports whether the status represents a final state — that is, the task will not change again. Terminal states are completed, failed, and cancelled.
type MCPToken ¶ added in v0.47.0
MCPToken represents an OAuth token for an MCP server, containing access and refresh tokens along with expiration metadata.
type MCPTokenStore ¶ added in v0.47.0
type MCPTokenStore = transport.TokenStore
MCPTokenStore persists OAuth tokens for a single MCP server. Implementations must be safe for concurrent use.
This is a type alias for the mcp-go transport.TokenStore interface. SDK consumers can implement this interface to provide custom storage backends (database, encrypted file, in-memory, etc.).
type MCPTokenStoreFactory ¶ added in v0.47.0
type MCPTokenStoreFactory func(serverURL string) (MCPTokenStore, error)
MCPTokenStoreFactory creates an MCPTokenStore for a given MCP server URL. It is called once per remote MCP server during connection setup.
type Message ¶
Message is a single conversation message containing heterogeneous content parts (text, reasoning, tool calls, tool results, finish markers).
func ConvertFromLLMMessage ¶ added in v0.30.0
func ConvertFromLLMMessage(msg LLMMessage) Message
ConvertFromLLMMessage converts an LLMMessage to an SDK message.
type MessageEndEvent ¶
type MessageEndEvent struct {
Content string
}
MessageEndEvent fires when the assistant message is complete.
func (MessageEndEvent) EventType ¶
func (e MessageEndEvent) EventType() EventType
EventType implements Event.
type MessageEntry ¶
type MessageEntry = session.MessageEntry
MessageEntry stores a conversation message as a tree entry in JSONL sessions.
type MessageRole ¶
type MessageRole = message.MessageRole
MessageRole identifies the sender of a message (user, assistant, tool, system).
type MessageStartEvent ¶
type MessageStartEvent struct{}
MessageStartEvent fires when a new assistant message begins.
func (MessageStartEvent) EventType ¶
func (e MessageStartEvent) EventType() EventType
EventType implements Event.
type MessageUpdateEvent ¶
type MessageUpdateEvent struct {
Chunk string
}
MessageUpdateEvent fires for each streaming text chunk.
func (MessageUpdateEvent) EventType ¶
func (e MessageUpdateEvent) EventType() EventType
EventType implements Event.
type ModelInfo ¶
ModelInfo represents information about a specific model (capabilities, pricing, limits).
func LookupModel ¶
LookupModel returns information about a model, or nil if unknown.
type ModelLimit ¶
ModelLimit represents the context and output limits for a model.
type ModelsRegistry ¶
type ModelsRegistry = models.ModelsRegistry
ModelsRegistry provides validation and information about models, maintaining a registry of all supported LLM providers and their models.
func GetGlobalRegistry ¶
func GetGlobalRegistry() *ModelsRegistry
GetGlobalRegistry returns the global models registry instance.
type OpenAICredentials ¶ added in v0.25.0
type OpenAICredentials = auth.OpenAICredentials
OpenAICredentials holds OpenAI API credentials supporting both OAuth and API key authentication methods.
type Options ¶
type Options struct {
Model string // Override model (e.g., "anthropic/claude-sonnet-4-5-20250929")
SystemPrompt string // Override system prompt
ConfigFile string // Override config file path
MaxSteps int // Override max steps (0 = use default)
Streaming bool // Enable streaming (default from config)
Quiet bool // Suppress debug output
Tools []Tool // Custom tool set. If empty, AllTools() is used.
ExtraTools []Tool // Additional tools added alongside core/MCP/extension tools.
// MaxTokens overrides the maximum output tokens per LLM response.
// 0 = let the precedence chain resolve a value (env → config →
// per-model → 8192 SDK floor, matching the CLI default). Setting a
// non-zero value here suppresses automatic right-sizing, matching
// the CLI's --max-tokens flag semantics. Bump this when generating
// long outputs (HTML artifacts, large refactors, etc.) to avoid
// silent truncation mid-tool-call. The cap also applies after
// model switches via [Kit.SetModel].
MaxTokens int
// ThinkingLevel sets the reasoning effort for models that support
// extended thinking. Valid values: "off", "none", "minimal", "low",
// "medium", "high". "" = let the precedence chain resolve a level
// (env → config → per-model → "off"). Use [Kit.SetThinkingLevel]
// to change at runtime.
ThinkingLevel string
// Temperature controls sampling randomness (typically 0.0–2.0).
// nil = leave provider/per-model default in place. Pointer type
// so explicit 0.0 (deterministic) is distinguishable from "unset".
Temperature *float32
// TopP is the nucleus-sampling cutoff (0.0–1.0).
// nil = leave provider/per-model default in place.
TopP *float32
// TopK limits sampling to the top K tokens.
// nil = leave provider/per-model default in place.
TopK *int32
// FrequencyPenalty discourages repeated tokens (OpenAI-family models).
// nil = leave provider/per-model default in place.
FrequencyPenalty *float32
// PresencePenalty discourages repeating topics (OpenAI-family models).
// nil = leave provider/per-model default in place.
PresencePenalty *float32
// ProviderAPIKey overrides the API key used to authenticate with the
// model provider. "" = use the value from config or the
// provider-specific environment variable.
ProviderAPIKey string
// ProviderURL overrides the provider endpoint. "" = use the provider's
// default URL.
ProviderURL string
// TLSSkipVerify disables TLS certificate verification on provider
// HTTP clients. Only set this for self-signed certificates in
// development. Once enabled here it cannot be disabled via Options
// (use the config file or env var to opt back out).
TLSSkipVerify bool
// SkipConfig, when true, skips loading .kit.yml configuration files.
// Viper defaults (setSDKDefaults) and environment variables (KIT_*)
// are still applied. Use this for fully programmatic configuration.
SkipConfig bool
// DisableCoreTools, when true, prevents loading any core tools.
// Use with Tools or ExtraTools to provide only custom tools.
// If both DisableCoreTools is true and Tools is empty, the agent
// will have no tools (useful for simple chat completions).
DisableCoreTools bool
// Session configuration
SessionDir string // Base directory for session discovery (default: cwd)
SessionPath string // Open a specific session file by path
Continue bool // Continue the most recent session for SessionDir
NoSession bool // Ephemeral mode — in-memory session, no persistence
// Skills
Skills []string // Explicit skill files/dirs to load (empty = auto-discover)
SkillsDir string // Override default project-local skills directory
NoSkills bool // Disable skill loading entirely (auto-discovery and explicit)
// NoExtensions disables Yaegi extension loading entirely.
NoExtensions bool
// NoContextFiles disables automatic loading of project context files
// (e.g. AGENTS.md) from the working directory.
NoContextFiles bool
// MCPConfig provides a pre-loaded MCP configuration. When set,
// LoadAndValidateConfig is skipped during Kit creation — avoiding
// viper access entirely. This is set automatically for in-process
// subagents (inheriting the parent's loaded config) and can be used
// by SDK consumers who build config programmatically.
MCPConfig *config.Config
// InProcessMCPServers registers mcp-go servers that run in the same
// process. Each key is the server name (used to prefix tool names, e.g.
// "docs__search"). The value must be a *[server.MCPServer].
//
// In-process servers bypass subprocess spawning and network I/O entirely.
// Kit does not take ownership of the servers — the caller is responsible
// for any cleanup after [Kit.Close].
//
// Example:
//
// mcpSrv := server.NewMCPServer("my-tools", "1.0.0",
// server.WithToolCapabilities(true),
// )
// mcpSrv.AddTool(mcp.NewTool("search", ...), handler)
//
// host, _ := kit.New(ctx, &kit.Options{
// InProcessMCPServers: map[string]*kit.MCPServer{
// "docs": mcpSrv,
// },
// })
InProcessMCPServers map[string]*MCPServer
// Compaction
AutoCompact bool // Auto-compact when near context limit
CompactionOptions *CompactionOptions // Config for auto-compaction (nil = defaults)
// Debug enables debug logging for the SDK.
Debug bool
// MCPAuthHandler handles OAuth authorization for remote MCP servers.
// When set, remote transports (streamable HTTP, SSE) are configured
// with OAuth support. If the server returns a 401, the handler is
// invoked to let the user authorize.
//
// If nil, OAuth is disabled: remote MCP servers requiring authorization
// will fail to connect and the underlying authorization-required error
// is surfaced to the caller. The SDK deliberately does not construct a
// default handler — doing so would bind a local TCP port and trigger
// presentation I/O (browser open, stderr writes) without the consumer
// opting in, which is wrong for library, daemon, or web-app embedders.
//
// CLI consumers: pass [NewCLIMCPAuthHandler] to get the standard
// "open browser + print status" behavior.
//
// Custom UX: implement [MCPAuthHandler] directly, or use
// [DefaultMCPAuthHandler] and set its OnAuthURL hook to plug in your
// own presentation (TUI modal, QR code, web redirect, etc.).
MCPAuthHandler MCPAuthHandler
// MCPTokenStoreFactory, if non-nil, is called to create a token store for
// each remote MCP server that requires OAuth. The factory receives the
// server's URL and returns a [MCPTokenStore] implementation.
//
// When nil (default), tokens are persisted to a JSON file at
// $XDG_CONFIG_HOME/.kit/mcp_tokens.json (or ~/.config/.kit/mcp_tokens.json).
//
// Use this to store tokens in a database, encrypt them, keep them
// in-memory, or write them to a custom file path.
MCPTokenStoreFactory MCPTokenStoreFactory
// OnMCPServerLoaded, if non-nil, is called when each MCP server finishes
// loading during Kit initialization. The callback receives the server name,
// tool count, and any error. Called from a background goroutine; safe to
// call app.NotifyMCPServerLoaded() from within the callback to display
// real-time progress in the TUI.
OnMCPServerLoaded func(serverName string, toolCount int, err error)
// MCPTaskMode overrides the per-server [MCPTaskMode] for task-augmented
// tools/call execution. Keys are MCP server names. Servers not present
// in the map fall back to the TasksMode field of MCPServerConfig (or
// MCPTaskModeAuto when that is empty). See the MCP Tasks spec for the
// underlying semantics:
// https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/tasks
MCPTaskMode map[string]MCPTaskMode
// MCPTaskTimeout is the maximum wall-clock duration to wait for a
// task-augmented tool call to reach a terminal state. Independent of
// any per-call context deadline; whichever fires first wins. Zero
// means use the default (15 minutes).
MCPTaskTimeout time.Duration
// MCPTaskTTL is the TTL hint sent in TaskParams for every
// task-augmented tools/call. Zero omits the TTL and lets the server
// pick its own retention policy.
MCPTaskTTL time.Duration
// MCPTaskPollInterval is the fallback interval between tasks/get
// requests when the server does not suggest one. Zero means use the
// default (1 second).
MCPTaskPollInterval time.Duration
// MCPTaskMaxPollInterval caps the polling interval (a server-supplied
// pollInterval can otherwise grow without bound). Zero means use the
// default (5 seconds).
MCPTaskMaxPollInterval time.Duration
// MCPTaskProgress, if non-nil, is invoked once when a task is accepted
// and on every status transition observed by the polling loop. The
// final invocation always carries a terminal status. Implementations
// must not block; long work should run on a goroutine.
MCPTaskProgress MCPTaskProgressHandler
// CLI is optional CLI-specific configuration. SDK users leave this nil.
CLI *CLIOptions
// SessionManager allows custom session storage backends.
// If nil (default), Kit uses the built-in file-based TreeManager.
// When provided, SessionPath, Continue, and NoSession options are ignored.
SessionManager SessionManager
}
Options configures Kit creation with optional overrides for model, prompts, configuration, and behavior settings. All fields are optional and will use CLI defaults if not specified.
Global viper state warning: Options are applied by New via viper.Set calls against viper's process-global store. This store is shared with every downstream reader (e.g. Kit.SetModel, Kit.GetThinkingLevel, BuildProviderConfig, and any other code path that calls viper.Get*). Two consequences:
- Kit instances are NOT isolated from each other within a single process. Values set by the second New() call overwrite the first, and any code that later reads viper will see the most recent Set.
- Fields left at the zero value do NOT clear prior viper state; they simply skip the viper.Set. Callers that need a clean slate between constructions should invoke viper.Reset() (the test suite uses a private resetViper() helper that wraps it) before the next New().
Recommended usage: create one Kit per process, or reset viper between constructions. Concurrent calls to New are serialized internally by [viperInitMu], but that mutex does not prevent later viper reads (from a different Kit) from observing mutated keys.
TODO: refactor New to use a per-instance *viper.Viper (constructed via viper.New()) so each Kit owns its own isolated config store and Options no longer leak through the global singleton.
type PasswordPromptEvent ¶ added in v0.53.0
type PasswordPromptEvent struct {
// Prompt is the message to display to the user.
Prompt string
// ResponseCh receives the password from the TUI.
// The TUI must send exactly one value: (password, false) for submit
// or ("", true) for cancel.
ResponseCh chan<- PasswordPromptResponse
}
PasswordPromptEvent fires when a sudo command needs a password. The TUI should display a password prompt and send the result back via ResponseCh.
func (PasswordPromptEvent) EventType ¶ added in v0.53.0
func (e PasswordPromptEvent) EventType() EventType
EventType implements Event.
type PasswordPromptResponse ¶ added in v0.53.0
PasswordPromptResponse carries the password prompt result.
type PrepareStepHook ¶ added in v0.60.0
type PrepareStepHook struct {
// StepNumber is the zero-based step index within the current turn.
StepNumber int
// Messages is the current context window that will be sent to the LLM.
// This includes any steering messages already injected in this step.
Messages []LLMMessage
}
PrepareStepHook is the input for hooks that fire between steps within a multi-step agent turn, with full message replacement capability. This is the most powerful interception point — it fires after the existing steering logic (if any) and before the messages are sent to the LLM.
Use cases:
- Transforming tool results (e.g. converting image tool results to FilePart user messages for vision models that don't support media in tool results)
- Dynamic tool filtering per step
- Mid-turn context injection beyond simple steering
- Custom stop conditions that inspect message history
type PrepareStepResult ¶ added in v0.60.0
type PrepareStepResult struct {
// Messages replaces the entire context window for this step. If nil,
// the original messages (including any steering) are used unchanged.
Messages []LLMMessage
}
PrepareStepResult can replace the context window between steps.
type PromptBuilder ¶
type PromptBuilder = skills.PromptBuilder
PromptBuilder composes a system prompt from a base prompt, skills, and arbitrary named sections.
func NewPromptBuilder ¶
func NewPromptBuilder(basePrompt string) *PromptBuilder
NewPromptBuilder creates a PromptBuilder with the given base system prompt. The base prompt is always emitted first.
type PromptOptions ¶
type PromptOptions struct {
// SystemMessage is prepended as a system message before the user prompt.
// Use it to inject per-call instructions or context without permanently
// modifying the agent's system prompt.
SystemMessage string
}
PromptOptions configures a single PromptWithOptions call.
type PromptTemplate ¶
type PromptTemplate = skills.PromptTemplate
PromptTemplate is a named text template with {{variable}} placeholders.
func LoadPromptTemplate ¶
func LoadPromptTemplate(path string) (*PromptTemplate, error)
LoadPromptTemplate reads a template from a file. The template name is derived from the filename (without extension).
func NewPromptTemplate ¶
func NewPromptTemplate(name, content string) *PromptTemplate
NewPromptTemplate creates a PromptTemplate, automatically extracting variable names from {{...}} placeholders in content.
type ProviderConfig ¶
type ProviderConfig = models.ProviderConfig
ProviderConfig holds configuration for creating LLM providers.
type ProviderInfo ¶
type ProviderInfo = models.ProviderInfo
ProviderInfo represents information about a model provider from the models.dev database.
func GetProviderInfo ¶
func GetProviderInfo(provider string) *ProviderInfo
GetProviderInfo returns information about a provider (env vars, API URL, etc.). Returns nil if the provider is not in the registry.
type ProviderResult ¶
type ProviderResult = models.ProviderResult
ProviderResult contains the result of provider creation (model + optional feedback message + closer).
func CreateProvider ¶
func CreateProvider(ctx context.Context, cfg *ProviderConfig) (*ProviderResult, error)
CreateProvider creates a LanguageModel based on provider config.
type ReasoningCompleteEvent ¶ added in v0.35.0
type ReasoningCompleteEvent struct{}
ReasoningCompleteEvent fires when reasoning/thinking is finished, after the last reasoning token has been processed.
func (ReasoningCompleteEvent) EventType ¶ added in v0.35.0
func (e ReasoningCompleteEvent) EventType() EventType
EventType implements Event.
type ReasoningContent ¶
type ReasoningContent = message.ReasoningContent
ReasoningContent holds extended thinking / reasoning output from the LLM.
type ReasoningDeltaEvent ¶ added in v0.7.0
type ReasoningDeltaEvent struct {
Delta string
}
ReasoningDeltaEvent fires for each streaming reasoning/thinking chunk.
func (ReasoningDeltaEvent) EventType ¶ added in v0.7.0
func (e ReasoningDeltaEvent) EventType() EventType
EventType implements Event.
type ReasoningStartEvent ¶ added in v0.60.0
type ReasoningStartEvent struct {
ID string
}
ReasoningStartEvent fires when the LLM begins reasoning/thinking. Paired with ReasoningDeltaEvent (deltas) and ReasoningCompleteEvent.
func (ReasoningStartEvent) EventType ¶ added in v0.60.0
func (e ReasoningStartEvent) EventType() EventType
EventType implements Event.
type ResponseEvent ¶
type ResponseEvent struct {
Content string
}
ResponseEvent fires when the LLM produces a final response.
func (ResponseEvent) EventType ¶
func (e ResponseEvent) EventType() EventType
EventType implements Event.
type ResponseHandler ¶
type ResponseHandler = agent.ResponseHandler
ResponseHandler is a function type for handling LLM responses.
type RetryEvent ¶ added in v0.60.0
RetryEvent fires when the LLM provider request is retried after a transient error.
func (RetryEvent) EventType ¶ added in v0.60.0
func (e RetryEvent) EventType() EventType
EventType implements Event.
type SessionHeader ¶
type SessionHeader = session.SessionHeader
SessionHeader is the first line in a JSONL session file, carrying metadata.
type SessionInfo ¶
type SessionInfo = session.SessionInfo
SessionInfo contains metadata about a discovered session, used for listing and session picker display.
func ListAllSessions ¶
func ListAllSessions() ([]SessionInfo, error)
ListAllSessions finds all sessions across all working directories, sorted by modification time (newest first).
func ListSessions ¶
func ListSessions(dir string) ([]SessionInfo, error)
ListSessions finds all sessions for the given working directory, sorted by modification time (newest first). If dir is empty, the current working directory is used.
type SessionManager ¶ added in v0.42.0
type SessionManager interface {
// AppendMessage adds a message to the current branch and returns its entry ID.
// The entry ID is used for tree navigation and must be unique within the session.
//
// During generation, AppendMessage is called incrementally after each
// completed agent step rather than in a batch at the end of the turn.
// For tool-calling steps, the assistant message (containing tool_use parts)
// and the tool-role message (containing tool_result parts) are appended
// together as a pair. This ensures the session never contains an orphaned
// tool call without its result, which would break subsequent LLM requests.
AppendMessage(msg LLMMessage) (entryID string, err error)
// GetMessages returns all messages on the current branch (from root to leaf),
// including any compaction summaries at the appropriate positions.
GetMessages() []LLMMessage
// BuildContext returns the message history to send to the LLM, applying
// compaction rules and branch summaries as needed.
// Returns: messages, currentProvider, currentModelID
BuildContext() (messages []LLMMessage, provider string, modelID string)
// Branch moves the leaf pointer to the given entry ID, creating a branch point.
// Subsequent AppendMessage calls extend from this new position.
// entryID can be empty to reset to root (new conversation branch).
Branch(entryID string) error
// GetCurrentBranch returns the path from root to current leaf as entry metadata.
// Used for UI display and navigation.
GetCurrentBranch() []BranchEntry
// GetChildren returns direct child entry IDs for a given parent entry.
// Used to display branch points in the conversation tree.
GetChildren(parentID string) []string
// GetEntry returns a specific entry by ID, or nil if not found.
GetEntry(entryID string) *BranchEntry
// GetSessionID returns the unique session identifier (UUID).
GetSessionID() string
// GetSessionName returns the user-defined display name, or empty.
GetSessionName() string
// SetSessionName sets a display name for the session.
SetSessionName(name string) error
// GetCreatedAt returns when the session was created.
GetCreatedAt() time.Time
// IsPersisted returns true if this session writes to durable storage.
IsPersisted() bool
// AppendCompaction adds a compaction entry that summarizes older messages.
// firstKeptEntryID is the ID of the first message to preserve in context.
// readFiles and modifiedFiles track file changes for the compaction summary.
AppendCompaction(summary string, firstKeptEntryID string,
tokensBefore, tokensAfter int, messagesRemoved int, readFiles, modifiedFiles []string) (string, error)
// GetLastCompaction returns the most recent compaction entry on the current
// branch, or nil if none exists.
GetLastCompaction() *CompactionEntry
// AppendExtensionData stores custom extension data in the session tree.
// Extensions use this to persist state across restarts.
AppendExtensionData(extType, data string) (string, error)
// GetExtensionData returns all extension data entries of the given type
// on the current branch. If extType is empty, returns all extension data.
GetExtensionData(extType string) []ExtensionDataEntry
// AppendModelChange records a provider/model switch in the session.
AppendModelChange(provider, modelID string) (string, error)
// GetContextEntryIDs returns the entry IDs corresponding to the messages
// returned by BuildContext, in the same order. Used by compaction to
// determine which entries to summarize.
GetContextEntryIDs() []string
// Close releases resources (database connections, file handles, etc.).
Close() error
}
SessionManager defines the contract for conversation storage backends. Implementations can use files (default), databases, cloud storage, etc.
Implementations must be safe for concurrent use. During generation, AppendMessage is called incrementally from the agent's step-completion callback while read methods (GetMessages, GetCurrentBranch, etc.) may be called concurrently from the UI or extension goroutines.
func NewTreeManagerAdapter ¶ added in v0.42.0
func NewTreeManagerAdapter(tm *session.TreeManager) SessionManager
NewTreeManagerAdapter creates an adapter (exported for use in New function). This is used by the SDK when no custom SessionManager is provided.
type Skill ¶
Skill represents a markdown-based instruction file with optional YAML frontmatter that provides domain-specific context and workflows.
func LoadSkill ¶
LoadSkill reads a single skill file (markdown with optional YAML frontmatter). If no frontmatter is present the skill name is derived from the filename.
func LoadSkills ¶
LoadSkills auto-discovers skills from standard directories:
- Global: $XDG_CONFIG_HOME/kit/skills/ (default ~/.config/kit/skills/)
- Project-local: <cwd>/.kit/skills/
cwd is the working directory for project-local discovery; if empty the current working directory is used.
func LoadSkillsFromDir ¶
LoadSkillsFromDir loads all skills from a single directory. It finds *.md and *.txt files directly in the directory, and SKILL.md files in immediate subdirectories.
type SourceEvent ¶ added in v0.60.0
SourceEvent fires when the LLM references a source (e.g. from web search tools).
func (SourceEvent) EventType ¶ added in v0.60.0
func (e SourceEvent) EventType() EventType
EventType implements Event.
type SpinnerFunc ¶
type SpinnerFunc = agent.SpinnerFunc
SpinnerFunc wraps a function in a loading spinner animation. Used for Ollama model loading. Signature: func(fn func() error) error.
type SteerConsumedEvent ¶ added in v0.24.0
type SteerConsumedEvent struct {
Count int
}
SteerConsumedEvent fires when one or more steering messages have been injected into the agent turn via PrepareStep. The Count indicates how many messages were consumed in this batch.
func (SteerConsumedEvent) EventType ¶ added in v0.24.0
func (e SteerConsumedEvent) EventType() EventType
EventType implements Event.
type StepFinishEvent ¶ added in v0.60.0
StepFinishEvent fires when a step completes, providing full step context. This is a unified event that carries the same data as the existing ToolCallContentEvent and StepUsageEvent, plus additional step metadata.
func (StepFinishEvent) EventType ¶ added in v0.60.0
func (e StepFinishEvent) EventType() EventType
EventType implements Event.
type StepStartEvent ¶ added in v0.60.0
type StepStartEvent struct {
StepNumber int
}
StepStartEvent fires when a new LLM call begins within a multi-step agent turn.
func (StepStartEvent) EventType ¶ added in v0.60.0
func (e StepStartEvent) EventType() EventType
EventType implements Event.
type StepUsageEvent ¶ added in v0.23.0
type StepUsageEvent struct {
InputTokens uint64
OutputTokens uint64
CacheReadTokens uint64
CacheWriteTokens uint64
}
StepUsageEvent fires after each complete step in a multi-step agent turn, carrying the token usage for that specific step. This enables real-time cost tracking during long-running tool-calling conversations.
func (StepUsageEvent) EventType ¶ added in v0.23.0
func (e StepUsageEvent) EventType() EventType
EventType implements Event.
type StreamFinishEvent ¶ added in v0.60.0
StreamFinishEvent fires when a per-step LLM stream completes. Provides per-stream usage stats and finish reason.
func (StreamFinishEvent) EventType ¶ added in v0.60.0
func (e StreamFinishEvent) EventType() EventType
EventType implements Event.
type StreamingResponseHandler ¶
type StreamingResponseHandler = agent.StreamingResponseHandler
StreamingResponseHandler is a function type for handling streaming LLM responses.
type StructuredMessage ¶ added in v0.12.0
type StructuredMessage struct {
ID string
ParentID string
Role MessageRole
Parts []ContentPart
Model string
Provider string
Timestamp string // RFC3339 format
}
StructuredMessage represents a conversation message with typed content parts (tool calls, reasoning, finish markers, etc.) instead of flattened text.
type SubagentConfig ¶ added in v0.12.0
type SubagentConfig struct {
// Prompt is the task/instruction for the subagent (required).
Prompt string
// Model overrides the parent's model (e.g. "anthropic/claude-haiku-3-5-20241022").
// Empty string uses the parent's current model.
Model string
// SystemPrompt provides domain-specific instructions for the subagent.
// Empty string uses a minimal default prompt.
SystemPrompt string
// Tools overrides the tool set. If nil, SubagentTools() is used (all
// core tools except subagent, preventing infinite recursion).
Tools []Tool
// NoSession, when true, uses an in-memory ephemeral session. When false
// (default), the subagent's session is persisted and can be loaded for
// replay/inspection.
NoSession bool
// Timeout limits execution time. Zero means 5 minute default.
Timeout time.Duration
// OnEvent, when set, receives all events from the subagent's event bus.
// This enables the parent to stream subagent tool calls, text chunks,
// etc. in real time.
OnEvent func(Event)
}
SubagentConfig configures an in-process subagent spawned via Kit.Subagent().
type SubagentResult ¶ added in v0.12.0
type SubagentResult struct {
// Response is the subagent's final text response.
Response string
// SessionID is the subagent's session identifier (for replay).
SessionID string
// StopReason is the LLM's finish reason for the subagent's final turn.
StopReason string
// Usage contains token usage from the subagent's run.
Usage *LLMUsage
// Elapsed is the total execution time.
Elapsed time.Duration
}
SubagentResult contains the outcome of an in-process subagent execution. Errors are returned as the error return value of Subagent(), not in this struct.
type TextContent ¶
type TextContent = message.TextContent
TextContent holds plain text content within a message.
type TextEndEvent ¶ added in v0.60.0
type TextEndEvent struct {
ID string
}
TextEndEvent fires when the LLM finishes generating text content.
func (TextEndEvent) EventType ¶ added in v0.60.0
func (e TextEndEvent) EventType() EventType
EventType implements Event.
type TextStartEvent ¶ added in v0.60.0
type TextStartEvent struct {
ID string
}
TextStartEvent fires when the LLM begins generating text content. Paired with MessageUpdateEvent (deltas) and TextEndEvent.
func (TextStartEvent) EventType ¶ added in v0.60.0
func (e TextStartEvent) EventType() EventType
EventType implements Event.
type Tool ¶
Tool is the interface that all Kit tools implement.
func CodingTools ¶
func CodingTools(opts ...ToolOption) []Tool
CodingTools returns the default set of core tools for a coding agent: bash, read, write, edit.
func NewBashTool ¶
func NewBashTool(opts ...ToolOption) Tool
NewBashTool creates a bash command execution tool.
func NewEditTool ¶
func NewEditTool(opts ...ToolOption) Tool
NewEditTool creates a surgical text-editing tool.
func NewFindTool ¶
func NewFindTool(opts ...ToolOption) Tool
NewFindTool creates a file search tool (uses fd when available).
func NewGrepTool ¶
func NewGrepTool(opts ...ToolOption) Tool
NewGrepTool creates a content search tool (uses ripgrep when available).
func NewLsTool ¶
func NewLsTool(opts ...ToolOption) Tool
NewLsTool creates a directory listing tool.
func NewParallelTool ¶ added in v0.43.0
func NewParallelTool[TInput any](name, description string, fn func(ctx context.Context, input TInput) (ToolOutput, error)) Tool
NewParallelTool is like NewTool but marks the tool as safe for concurrent execution alongside other tools. Use this when the tool has no side effects or when concurrent calls are safe.
func NewReadTool ¶
func NewReadTool(opts ...ToolOption) Tool
NewReadTool creates a file-reading tool.
func NewTool ¶ added in v0.43.0
func NewTool[TInput any](name, description string, fn func(ctx context.Context, input TInput) (ToolOutput, error)) Tool
NewTool creates a custom Tool with automatic JSON schema generation from the TInput struct type. The handler receives a typed input (deserialized from the LLM's JSON arguments) and returns a ToolOutput.
Struct tags on TInput control the generated schema:
json:"name" → parameter name description:"..." → parameter description shown to the LLM enum:"a,b,c" → restrict valid values omitempty → marks the parameter as optional
The tool call ID is injected into the context and can be retrieved with ToolCallIDFromContext.
Binary results: When [ToolOutput.Data] and [ToolOutput.MediaType] are set, the response type is automatically inferred so the LLM receives the binary content (e.g. an image) instead of only the text. Use ImageResult or MediaResult for convenience.
Example:
type WeatherInput struct {
City string `json:"city" description:"City name"`
}
tool := kit.NewTool("get_weather", "Get weather for a city",
func(ctx context.Context, input WeatherInput) (kit.ToolOutput, error) {
return kit.TextResult("72°F, sunny in " + input.City), nil
},
)
func NewWriteTool ¶
func NewWriteTool(opts ...ToolOption) Tool
NewWriteTool creates a file-writing tool.
func ReadOnlyTools ¶
func ReadOnlyTools(opts ...ToolOption) []Tool
ReadOnlyTools returns tools for read-only exploration: read, grep, find, ls.
func SubagentTools ¶ added in v0.12.0
func SubagentTools(opts ...ToolOption) []Tool
SubagentTools returns all core tools except subagent. Use this when creating child Kit instances (in-process subagents) to prevent infinite recursion.
type ToolCallContentEvent ¶
type ToolCallContentEvent struct {
Content string
}
ToolCallContentEvent fires when a step includes text alongside tool calls.
func (ToolCallContentEvent) EventType ¶
func (e ToolCallContentEvent) EventType() EventType
EventType implements Event.
type ToolCallContentHandler ¶
type ToolCallContentHandler = agent.ToolCallContentHandler
ToolCallContentHandler is a function type for handling content that accompanies tool calls.
type ToolCallDeltaEvent ¶ added in v0.58.0
type ToolCallDeltaEvent struct {
ToolCallID string // Stable ID for correlating tool lifecycle events
Delta string // JSON fragment of tool arguments
}
ToolCallDeltaEvent fires for each streamed fragment of tool call arguments. Useful for live-previewing artifact content as it's generated, or showing a progress indicator with byte count.
func (ToolCallDeltaEvent) EventType ¶ added in v0.58.0
func (e ToolCallDeltaEvent) EventType() EventType
EventType implements Event.
type ToolCallEndEvent ¶ added in v0.58.0
type ToolCallEndEvent struct {
ToolCallID string // Stable ID for correlating tool lifecycle events
}
ToolCallEndEvent fires when tool argument streaming is complete, before the tool call is parsed and execution begins. UIs can use this to transition from an "generating args" state to an "executing" state.
func (ToolCallEndEvent) EventType ¶ added in v0.58.0
func (e ToolCallEndEvent) EventType() EventType
EventType implements Event.
type ToolCallEvent ¶
type ToolCallEvent struct {
ToolCallID string // Stable ID for correlating tool lifecycle events
ToolName string
ToolKind string // Tool classification: "execute", "edit", "read", "search", "agent"
ToolArgs string // JSON-encoded arguments
ParsedArgs map[string]any // Pre-parsed arguments for convenience (nil on parse failure)
}
ToolCallEvent fires when a tool call has been parsed.
func (ToolCallEvent) EventType ¶
func (e ToolCallEvent) EventType() EventType
EventType implements Event.
type ToolCallHandler ¶
type ToolCallHandler = agent.ToolCallHandler
ToolCallHandler is a function type for handling tool calls as they happen.
type ToolCallStartEvent ¶ added in v0.58.0
type ToolCallStartEvent struct {
ToolCallID string // Stable ID for correlating tool lifecycle events
ToolName string
ToolKind string // Tool classification: "execute", "edit", "read", "search", "agent"
}
ToolCallStartEvent fires when the LLM begins generating tool call arguments. The tool name is known at this point but the full arguments are still being streamed. UIs can use this to show a "running" indicator immediately instead of waiting for the full argument JSON to finish streaming.
func (ToolCallStartEvent) EventType ¶ added in v0.58.0
func (e ToolCallStartEvent) EventType() EventType
EventType implements Event.
type ToolExecutionEndEvent ¶
ToolExecutionEndEvent fires when a tool finishes executing.
func (ToolExecutionEndEvent) EventType ¶
func (e ToolExecutionEndEvent) EventType() EventType
EventType implements Event.
type ToolExecutionHandler ¶
type ToolExecutionHandler = agent.ToolExecutionHandler
ToolExecutionHandler is a function type for handling tool execution start/end events.
type ToolExecutionStartEvent ¶
type ToolExecutionStartEvent struct {
ToolCallID string
ToolName string
ToolKind string
ToolArgs string
}
ToolExecutionStartEvent fires when a tool begins executing.
func (ToolExecutionStartEvent) EventType ¶
func (e ToolExecutionStartEvent) EventType() EventType
EventType implements Event.
type ToolOutput ¶ added in v0.43.0
type ToolOutput struct {
// Content is the text content returned to the LLM.
Content string
// IsError, when true, signals to the LLM that the tool call failed.
IsError bool
// Data contains optional binary data (images, audio, etc.).
Data []byte
// MediaType is the MIME type for binary Data (e.g. "image/png").
MediaType string
// Metadata is optional opaque metadata attached to the response.
// It is not sent to the LLM but may be consumed by hooks or the UI.
Metadata any
}
ToolOutput is the return value from custom tool handlers created with NewTool or NewParallelTool. It provides a dependency-free way to return results without importing the underlying LLM framework.
func ErrorResult ¶ added in v0.43.0
func ErrorResult(content string) ToolOutput
ErrorResult creates an error ToolOutput. The LLM will see the content as a tool error, allowing it to retry or adjust its approach.
func ImageResult ¶ added in v0.59.0
func ImageResult(content string, data []byte, mediaType string) ToolOutput
ImageResult creates a ToolOutput that returns an image to the LLM. The data is the raw image bytes and mediaType is the MIME type (e.g. "image/png", "image/jpeg"). The optional text content accompanies the image and is visible to the LLM alongside it.
func MediaResult ¶ added in v0.59.0
func MediaResult(content string, data []byte, mediaType string) ToolOutput
MediaResult creates a ToolOutput that returns non-image binary media (e.g. audio, video) to the LLM. The data is the raw bytes and mediaType is the MIME type (e.g. "audio/wav", "video/mp4"). The optional text content accompanies the media.
func TextResult ¶ added in v0.43.0
func TextResult(content string) ToolOutput
TextResult creates a successful text ToolOutput.
type ToolOutputEvent ¶ added in v0.20.0
ToolOutputEvent fires when a tool produces streaming output chunks (e.g., bash output).
func (ToolOutputEvent) EventType ¶ added in v0.20.0
func (e ToolOutputEvent) EventType() EventType
EventType implements Event.
type ToolResult ¶
type ToolResult = message.ToolResult
ToolResult represents the result of executing a tool.
type ToolResultEvent ¶
type ToolResultEvent struct {
ToolCallID string
ToolName string
ToolKind string
ToolArgs string
ParsedArgs map[string]any // Pre-parsed arguments for convenience
Result string
IsError bool
Metadata *ToolResultMetadata // Optional structured metadata from tool execution
}
ToolResultEvent fires after a tool execution completes with its result.
func (ToolResultEvent) EventType ¶
func (e ToolResultEvent) EventType() EventType
EventType implements Event.
type ToolResultHandler ¶
type ToolResultHandler = agent.ToolResultHandler
ToolResultHandler is a function type for handling tool results.
type ToolResultMetadata ¶ added in v0.12.0
type ToolResultMetadata struct {
FileDiffs []FileDiffInfo `json:"file_diffs,omitempty"` // Present for edit/write tools
SubagentSessionID string `json:"subagent_session_id,omitempty"` // Present for subagent tool
}
ToolResultMetadata carries structured data from tool executions.
type TreeManager ¶
type TreeManager = session.TreeManager
TreeManager manages a tree-structured JSONL session with branching, leaf-pointer tracking, and context building.
func OpenTreeSession ¶ added in v0.16.0
func OpenTreeSession(path string) (*TreeManager, error)
OpenTreeSession opens an existing JSONL session file. This is a package-level function (no Kit instance required) used by the CLI for session switching.
type TreeNode ¶ added in v0.28.0
type TreeNode struct {
ID string
ParentID string
Type string // "message", "branch_summary", "model_change", "extension_data"
Role string // for messages: "user", "assistant", "system", "tool"
Content string
Model string
Provider string
Timestamp string
Children []string
}
TreeNode represents a node in the session tree for SDK consumers.
type TurnEndEvent ¶
type TurnEndEvent struct {
Response string
Error error
// StopReason is the LLM provider's finish reason for the final step of
// the turn. Compare against the FinishReason* constants — in particular,
// FinishReasonLength indicates the response was truncated because the
// agent hit its max_output_tokens budget.
StopReason string
}
TurnEndEvent fires after the agent finishes processing.
func (TurnEndEvent) EventType ¶
func (e TurnEndEvent) EventType() EventType
EventType implements Event.
type TurnResult ¶
type TurnResult struct {
// Response is the assistant's final text response.
Response string
// StopReason indicates why the turn ended. Derived from the LLM
// provider's finish reason: FinishReasonStop, FinishReasonLength (max
// output tokens reached), FinishReasonToolCalls, FinishReasonContentFilter,
// FinishReasonError, FinishReasonOther, FinishReasonUnknown.
StopReason string
// SessionID is the UUID of the session this turn belongs to.
SessionID string
// TotalUsage is the aggregate token usage across all steps in the turn
// (includes tool-calling loop iterations). Nil if the provider didn't
// report usage.
TotalUsage *LLMUsage
// FinalUsage is the token usage from the last API call only. For context
// window fill, sum all categories: InputTokens + CacheReadTokens +
// CacheCreationTokens + OutputTokens. With prompt caching, InputTokens
// alone understates the context (cached tokens are reported separately).
// Nil if unavailable.
FinalUsage *LLMUsage
// Messages is the full updated conversation after the turn, including
// any tool call/result messages added during the agent loop.
// Each message carries role and plain-text content.
Messages []LLMMessage
}
TurnResult contains the full result of a prompt turn, including usage statistics and the updated conversation. Use PromptResult() instead of Prompt() when you need access to this data.
type TurnStartEvent ¶
type TurnStartEvent struct {
Prompt string
}
TurnStartEvent fires before the agent begins processing a prompt.
func (TurnStartEvent) EventType ¶
func (e TurnStartEvent) EventType() EventType
EventType implements Event.
type WarningsEvent ¶ added in v0.60.0
type WarningsEvent struct {
Warnings []string
}
WarningsEvent fires when the LLM provider returns warnings about the request.
func (WarningsEvent) EventType ¶ added in v0.60.0
func (e WarningsEvent) EventType() EventType
EventType implements Event.