kit

package
v0.36.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 2, 2026 License: MIT Imports: 26 Imported by: 0

README

KIT SDK

The KIT SDK (pkg/kit) lets you embed Kit's full agent capabilities — LLM interactions, tool execution, session management, streaming, hooks — into any Go application.

Installation

go get github.com/mark3labs/kit

Basic Usage

package main

import (
    "context"
    "fmt"
    "log"

    kit "github.com/mark3labs/kit/pkg/kit"
)

func main() {
    ctx := context.Background()

    // Create Kit instance with default configuration
    host, err := kit.New(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }
    defer func() { _ = host.Close() }()

    // Send a prompt
    response, err := host.Prompt(ctx, "What is 2+2?")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(response)
}

Configuration

The SDK behaves identically to the CLI:

  • Loads configuration from ~/.kit.yml by default
  • Creates default configuration if none exists
  • Respects all environment variables (KIT_*)
  • Uses the same defaults as the CLI
Options

You can override specific settings:

host, err := kit.New(ctx, &kit.Options{
    Model:        "ollama/llama3",            // Override model
    SystemPrompt: "You are a helpful bot",    // Override system prompt
    ConfigFile:   "/path/to/config.yml",      // Use specific config file
    MaxSteps:     10,                         // Override max steps
    Streaming:    true,                       // Enable streaming
    Quiet:        true,                       // Suppress debug output

    // Session options
    SessionPath:  "./session.jsonl",          // Open specific session
    Continue:     true,                       // Resume most recent session
    NoSession:    true,                       // Ephemeral mode

    // Tool options
    Tools:        []kit.Tool{kit.NewBashTool()}, // Replace default tool set
    ExtraTools:   []kit.Tool{myTool},            // Add alongside defaults

    // Compaction
    AutoCompact:  true,                       // Auto-compact near context limit
})

Advanced Usage

With Tool Callbacks

Monitor tool execution in real-time:

unsub := host.OnToolCall(func(e kit.ToolCallEvent) {
    fmt.Printf("Calling tool: %s\n", e.ToolName)
})
defer unsub()

unsub2 := host.OnToolResult(func(e kit.ToolResultEvent) {
    if e.IsError {
        fmt.Printf("Tool %s failed: %s\n", e.ToolName, e.Result)
    } else {
        fmt.Printf("Tool %s succeeded\n", e.ToolName)
    }
})
defer unsub2()

unsub3 := host.OnStreaming(func(e kit.MessageUpdateEvent) {
    fmt.Print(e.Chunk)
})
defer unsub3()

response, err := host.Prompt(
    ctx,
    "List files in the current directory",
)
Session Management

Maintain conversation context:

// First message
host.Prompt(ctx, "My name is Alice")

// Second message (remembers context)
response, _ := host.Prompt(ctx, "What's my name?")
// Response: "Your name is Alice"

// Clear conversation history
host.ClearSession()

Re-exported Types

The SDK re-exports types so you don't need direct internal imports:

// Message types
kit.Message, kit.MessageRole, kit.ContentPart
kit.TextContent, kit.ReasoningContent, kit.ToolCall, kit.ToolResult, kit.Finish
kit.RoleUser, kit.RoleAssistant, kit.RoleTool, kit.RoleSystem

// LLM types — concrete Kit-owned structs, no external library dependency
kit.LLMMessage      // {Role LLMMessageRole, Content string}
kit.LLMMessageRole  // "user" | "assistant" | "system" | "tool"
kit.LLMUsage        // {InputTokens, OutputTokens, TotalTokens, ...}
kit.LLMResponse     // {Content, FinishReason, Usage}
kit.LLMFilePart     // {Filename, Data []byte, MediaType}

// Conversion helpers
msgs := kit.ConvertToLLMMessages(&msg)   // SDK Message → []LLMMessage
msg  := kit.ConvertFromLLMMessage(lMsg)  // LLMMessage  → SDK Message

API Reference

Types
  • Kit - Main SDK type
  • Options - Configuration options
  • Message - Conversation message with typed content parts
  • Tool - Agent tool interface
  • TurnResult - Full result from a prompt including usage stats
Key Methods
  • New(ctx, opts) - Create new Kit instance
  • Prompt(ctx, message) - Send message and get response string
  • PromptResult(ctx, message) - Send message and get full TurnResult
  • PromptWithOptions(ctx, message, opts) - Prompt with per-call options
  • Steer(ctx, instruction) - System-level steering
  • FollowUp(ctx, text) - Continue without new user input
  • SetModel(ctx, model) - Switch model at runtime
  • GetModelString() - Get current model string
  • GetModelInfo() - Get model capabilities and limits
  • ClearSession() - Clear conversation history
  • GetSessionPath() - Get session file path
  • GetSessionID() - Get session UUID
  • Close() - Clean up resources

Environment Variables

All CLI environment variables work with the SDK:

  • KIT_MODEL - Override model
  • ANTHROPIC_API_KEY - Anthropic API key
  • OPENAI_API_KEY - OpenAI API key
  • GEMINI_API_KEY - Google API key
  • etc.

License

Same as KIT CLI

Documentation

Index

Constants

View Source
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.

View Source
const (
	RoleUser      = message.RoleUser
	RoleAssistant = message.RoleAssistant
	RoleTool      = message.RoleTool
	RoleSystem    = message.RoleSystem
)
View Source
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 fantasy.MessageRole* values under clean LLM-prefixed names.

Variables

View Source
var NewLLMSystemMessage = fantasy.NewSystemMessage

NewLLMSystemMessage constructs a system-role LLMMessage from one or more prompt strings. It is equivalent to fantasy.NewSystemMessage.

View Source
var NewLLMUserMessage = fantasy.NewUserMessage

NewLLMUserMessage constructs a user-role LLMMessage with optional file attachments. It is equivalent to fantasy.NewUserMessage.

View Source
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

func AddProviderToModel(provider, model string) string

AddProviderToModel adds a provider prefix to a bare model ID.

func CheckModelAvailable added in v0.28.0

func CheckModelAvailable(model string) bool

CheckModelAvailable verifies if a model string is valid and provider exists.

func CheckProviderReady

func CheckProviderReady(provider string) error

CheckProviderReady validates that a provider is properly configured by checking that it exists in the registry and has required environment variables set.

func DeleteSession

func DeleteSession(path string) error

DeleteSession removes a session file from disk.

func EvaluateModelConditional added in v0.28.0

func EvaluateModelConditional(currentModel, condition string) bool

EvaluateModelConditional checks if condition matches current model. Condition supports wildcards: * matches any, ? matches single char.

func ExtractModelFromPath added in v0.28.0

func ExtractModelFromPath(model string) string

ExtractModelFromPath extracts model ID from a path-like model string.

func ExtractProviderFromPath added in v0.28.0

func ExtractProviderFromPath(model string) string

ExtractProviderFromPath extracts provider from a path-like model string.

func FormatSkillsForPrompt

func FormatSkillsForPrompt(s []*Skill) string

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

func GetCurrentModelID(model string) string

GetCurrentModelID extracts model ID from model string.

func GetCurrentProvider added in v0.28.0

func GetCurrentProvider(model string) string

GetCurrentProvider extracts provider from model string.

func GetFantasyProviders deprecated

func GetFantasyProviders() []string

Deprecated: Use GetLLMProviders instead.

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

func GetModelsForProvider(provider string) (map[string]ModelInfo, error)

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

func InitConfig(configFile string, debug bool) error

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

func IsBareModelID(model string) bool

IsBareModelID checks if a string is a bare model ID (no provider).

func JoinModel added in v0.28.0

func JoinModel(provider, modelID string) string

JoinModel combines provider and model ID into a model string.

func LoadConfigWithEnvSubstitution

func LoadConfigWithEnvSubstitution(configPath string) error

LoadConfigWithEnvSubstitution loads a config file with ${ENV_VAR} expansion.

func LoadSystemPrompt

func LoadSystemPrompt(pathOrContent string) (string, error)

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

func MatchModelGlob(model, pattern string) bool

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

func ParseModelString(model string) (provider, modelID string, err error)

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

func RemoveProviderFromModel(model string) string

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

func RenderWithModelConditionals(content, currentModel string) string

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

func SimpleParseArguments(input string, count int) []string

SimpleParseArguments parses $1, $2, $@ style arguments. Returns slice where [0]=full input, [1]=$1, [2]=$2, ... [n]=$@

func SuggestModels

func SuggestModels(provider, invalidModel string) []string

SuggestModels returns model names similar to an invalid model string.

func ValidateEnvironment

func ValidateEnvironment(provider string, apiKey string) error

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

type AfterTurnHook struct {
	Response string
	Error    error
}

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

type BeforeToolCallHook struct {
	ToolCallID string
	ToolName   string
	ToolArgs   string
}

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 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
}

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 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

type Config = config.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 DiffBlock added in v0.12.0

type DiffBlock struct {
	OldText string `json:"old_text"`
	NewText string `json:"new_text"`
}

DiffBlock represents a single old→new text replacement within a file.

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"
	// 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"
	// EventSteerConsumed fires when one or more steering messages have been
	// injected into the agent turn via PrepareStep.
	EventSteerConsumed EventType = "steer_consumed"
)

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
	SetFooter(config extensions.HeaderFooterConfig)
	RemoveFooter()
	GetFooter() *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 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 Finish

type Finish = message.Finish

Finish marks the end of an assistant turn, carrying the stop reason.

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

func New(ctx context.Context, opts *Options) (*Kit, error)

func (*Kit) Branch

func (m *Kit) Branch(entryID string) error

Branch moves the tree session's leaf pointer to the given entry ID, creating a branch point. Subsequent Prompt() calls will extend from the new position.

func (*Kit) ClearSession

func (m *Kit) ClearSession()

ClearSession resets the tree 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

func (m *Kit) Close() error

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

func (m *Kit) CollapseBranch(fromID, toID, summary string) error

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

func (m *Kit) EstimateContextTokens() int

EstimateContextTokens returns the estimated token count of the current conversation based on tree 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

func (m *Kit) FollowUp(ctx context.Context, text string) (string, error)

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

func (m *Kit) GetBufferedDebugMessages() []string

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

func (m *Kit) GetChildren(parentID string) []string

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

func (m *Kit) GetCurrentBranch() []TreeNode

GetCurrentBranch returns the path from root to current leaf as TreeNodes.

func (*Kit) GetExtensionToolCount added in v0.2.0

func (m *Kit) GetExtensionToolCount() int

GetExtensionToolCount returns the number of tools registered by extensions.

func (*Kit) GetLoadedServerNames added in v0.2.0

func (m *Kit) GetLoadedServerNames() []string

GetLoadedServerNames returns the names of successfully loaded MCP servers.

func (*Kit) GetLoadingMessage added in v0.2.0

func (m *Kit) GetLoadingMessage() string

GetLoadingMessage returns the agent's startup info message (e.g. GPU fallback info), or empty string if none.

func (*Kit) GetMCPToolCount added in v0.2.0

func (m *Kit) GetMCPToolCount() int

GetMCPToolCount returns the number of tools loaded from external MCP servers.

func (*Kit) GetModelInfo

func (m *Kit) GetModelInfo() *ModelInfo

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

func (m *Kit) GetModelString() string

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

func (m *Kit) GetSessionID() string

GetSessionID returns the UUID of the active tree session, or empty when no tree session is configured.

func (*Kit) GetSessionPath

func (m *Kit) GetSessionPath() string

GetSessionPath returns the file path of the active tree session, or empty for in-memory sessions or when no tree session is configured.

func (*Kit) GetSkills

func (m *Kit) GetSkills() []*Skill

GetSkills returns the skills loaded during initialisation.

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

func (m *Kit) GetThinkingLevel() string

GetThinkingLevel returns the current thinking level.

func (*Kit) GetToolNames added in v0.2.0

func (m *Kit) GetToolNames() []string

GetToolNames returns the names of all tools available to the agent.

func (*Kit) GetTools

func (m *Kit) GetTools() []Tool

GetTools returns all tools available to the agent (core + MCP + extensions).

func (*Kit) GetTreeNode added in v0.28.0

func (m *Kit) GetTreeNode(entryID string) *TreeNode

GetTreeNode returns a node by ID with full metadata and children. Returns nil if entry not found or no tree session.

func (*Kit) GetTreeSession

func (m *Kit) GetTreeSession() *TreeManager

GetTreeSession returns the tree session manager, or nil if not configured.

func (*Kit) InjectSteer added in v0.24.0

func (m *Kit) InjectSteer(message string)

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

func (m *Kit) IsGenerating() bool

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

func (m *Kit) IsReasoningModel() bool

IsReasoningModel returns true if the current model supports extended thinking / reasoning.

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) NavigateTo added in v0.28.0

func (m *Kit) NavigateTo(entryID string) error

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) 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) OnResponse

func (m *Kit) OnResponse(handler func(ResponseEvent)) func()

OnResponse registers a handler that fires only for ResponseEvent. Returns an unsubscribe function.

func (*Kit) OnStreaming

func (m *Kit) OnStreaming(handler func(MessageUpdateEvent)) func()

OnStreaming registers a handler that fires only for MessageUpdateEvent (streaming text chunks). 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) 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) Prompt

func (m *Kit) Prompt(ctx context.Context, message string) (string, error)

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

func (m *Kit) PromptResult(ctx context.Context, message string) (*TurnResult, error)

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

func (m *Kit) PromptResultWithMessages(ctx context.Context, messages []string) (*TurnResult, error)

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) ReloadExtensions added in v0.3.0

func (m *Kit) ReloadExtensions() error

ReloadExtensions hot-reloads all extensions from disk. Event handlers, commands, renderers, shortcuts, and extension-defined tools all update immediately.

func (*Kit) SetModel added in v0.3.0

func (m *Kit) SetModel(ctx context.Context, modelString string) error

SetModel changes the active model at runtime. The existing tools, system prompt, and session are preserved. 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) SetSessionName

func (m *Kit) SetSessionName(name string) error

SetSessionName sets a user-defined display name for the active tree session.

func (*Kit) SetThinkingLevel added in v0.7.0

func (m *Kit) SetThinkingLevel(ctx context.Context, level string) error

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.

func (*Kit) ShouldCompact

func (m *Kit) ShouldCompact() bool

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.

func (*Kit) Steer

func (m *Kit) Steer(ctx context.Context, instruction string) (string, error)

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) 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

func (m *Kit) SummarizeBranch(fromID, toID string) (string, error)

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.

type LLMFilePart added in v0.30.0

type LLMFilePart = fantasy.FilePart

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

type LLMMessage = fantasy.Message

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 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

type LLMResponse = fantasy.Response

LLMResponse represents a complete response from the LLM provider.

type LLMTextPart added in v0.33.0

type LLMTextPart = fantasy.TextPart

LLMTextPart is a plain-text content part for constructing LLM messages.

type LLMToolCallPart added in v0.33.0

type LLMToolCallPart = fantasy.ToolCallPart

LLMToolCallPart represents an LLM-initiated tool invocation within a message.

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 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

type LLMUsage = fantasy.Usage

LLMUsage contains token usage information returned by the LLM provider.

type MCPServerConfig

type MCPServerConfig = config.MCPServerConfig

MCPServerConfig represents configuration for an MCP server, supporting both local (stdio) and remote (StreamableHTTP/SSE) server types.

type Message

type Message = message.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 ModelCost

type ModelCost = models.Cost

ModelCost represents the pricing information for a model.

type ModelInfo

type ModelInfo = models.ModelInfo

ModelInfo represents information about a specific model (capabilities, pricing, limits).

func LookupModel

func LookupModel(provider, modelID string) *ModelInfo

LookupModel returns information about a model, or nil if unknown.

type ModelLimit

type ModelLimit = models.Limit

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.

	// 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

	// 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

	// CLI is optional CLI-specific configuration. SDK users leave this nil.
	CLI *CLIOptions
}

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.

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 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 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 Skill

type Skill = skills.Skill

Skill represents a markdown-based instruction file with optional YAML frontmatter that provides domain-specific context and workflows.

func LoadSkill

func LoadSkill(path string) (*Skill, error)

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

func LoadSkills(cwd string) ([]*Skill, error)

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

func LoadSkillsFromDir(dir string) ([]*Skill, error)

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 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 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 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 Tool

type Tool = fantasy.AgentTool

Tool is the interface that all Kit tools implement.

func AllTools

func AllTools(opts ...ToolOption) []Tool

AllTools returns all available core tools.

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 NewReadTool

func NewReadTool(opts ...ToolOption) Tool

NewReadTool creates a file-reading tool.

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 ToolCall

type ToolCall = message.ToolCall

ToolCall represents a tool invocation initiated by the LLM.

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 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 ToolExecutionEndEvent

type ToolExecutionEndEvent struct {
	ToolCallID string
	ToolName   string
	ToolKind   string
}

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 ToolOption

type ToolOption = core.ToolOption

ToolOption configures tool behavior.

type ToolOutputEvent added in v0.20.0

type ToolOutputEvent struct {
	ToolCallID string
	ToolName   string
	Chunk      string
	IsStderr   bool
}

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 string // "end_turn", "max_tokens", "tool_use", "error", etc.
}

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: "stop", "length" (max tokens), "tool-calls",
	// "content-filter", "error", "other", "unknown".
	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. Use this
	// for context window fill estimation (InputTokens + OutputTokens ≈
	// current context size). 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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL