Documentation
¶
Index ¶
- Constants
- Variables
- func CheckProviderReady(provider string) error
- func ConvertToFantasyMessages(msg *Message) []fantasy.Message
- func DeleteSession(path string) error
- func FormatSkillsForPrompt(s []*Skill) string
- func GetAnthropicAPIKey() string
- func GetFantasyProviders() []string
- func GetModelsForProvider(provider string) (map[string]ModelInfo, error)
- func GetSupportedProviders() []string
- func HasAnthropicCredentials() bool
- func InitConfig(configFile string, debug bool) error
- func InitTreeSession(opts *Options) (*session.TreeManager, error)
- func LoadConfigWithEnvSubstitution(configPath string) error
- func RefreshModelRegistry()
- func SuggestModels(provider, invalidModel string) []string
- func ValidateEnvironment(provider string, apiKey string) error
- type AfterToolResultHook
- type AfterToolResultResult
- type AfterTurnHook
- type AfterTurnResult
- type AgentConfig
- type AnthropicCredentials
- type BeforeToolCallHook
- type BeforeToolCallResult
- type BeforeTurnHook
- type BeforeTurnResult
- type CLIOptions
- type CompactionEvent
- type CompactionOptions
- type CompactionResult
- type Config
- type ContentPart
- type ContextFile
- type ContextStats
- type CredentialManager
- type CredentialStore
- type Event
- type EventListener
- type EventType
- type FantasyMessage
- type FantasyResponse
- type FantasyUsage
- type Finish
- type GenerateResult
- type HookPriority
- type Kit
- func (m *Kit) Branch(entryID string) error
- func (m *Kit) ClearSession()
- func (m *Kit) Close() error
- func (m *Kit) Compact(ctx context.Context, opts *CompactionOptions, customInstructions string) (*CompactionResult, error)
- func (m *Kit) EmitSessionStart()
- func (m *Kit) EstimateContextTokens() int
- func (m *Kit) ExtensionCommands() []extensions.CommandDef
- func (m *Kit) FollowUp(ctx context.Context, text string) (string, error)
- func (m *Kit) GetAgent() *agent.Agentdeprecated
- func (m *Kit) GetBufferedDebugMessages() []string
- func (m *Kit) GetBufferedLogger() *tools.BufferedDebugLoggerdeprecated
- func (m *Kit) GetContextFiles() []*ContextFile
- func (m *Kit) GetContextStats() ContextStats
- func (m *Kit) GetExtRunner() *extensions.Runnerdeprecated
- func (m *Kit) GetExtensionContext() extensions.Context
- func (m *Kit) GetExtensionEditor() *extensions.EditorConfig
- func (m *Kit) GetExtensionFooter() *extensions.HeaderFooterConfig
- func (m *Kit) GetExtensionHeader() *extensions.HeaderFooterConfig
- func (m *Kit) GetExtensionToolCount() int
- func (m *Kit) GetExtensionToolRenderer(toolName string) *extensions.ToolRenderConfig
- func (m *Kit) GetExtensionWidgets(placement extensions.WidgetPlacement) []extensions.WidgetConfig
- func (m *Kit) GetLoadedServerNames() []string
- func (m *Kit) GetLoadingMessage() string
- func (m *Kit) GetMCPToolCount() int
- func (m *Kit) GetModelInfo() *ModelInfo
- func (m *Kit) GetModelString() string
- func (m *Kit) GetSessionID() string
- func (m *Kit) GetSessionPath() string
- func (m *Kit) GetSkills() []*Skill
- func (m *Kit) GetToolNames() []string
- func (m *Kit) GetTools() []Tool
- func (m *Kit) GetTreeSession() *TreeManager
- func (m *Kit) HasExtensions() bool
- func (m *Kit) OnAfterToolResult(p HookPriority, h func(AfterToolResultHook) *AfterToolResultResult) func()
- func (m *Kit) OnAfterTurn(p HookPriority, h func(AfterTurnHook)) 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) OnResponse(handler func(ResponseEvent)) func()
- func (m *Kit) OnStreaming(handler func(MessageUpdateEvent)) func()
- func (m *Kit) OnToolCall(handler func(ToolCallEvent)) 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) Prompt(ctx context.Context, message string) (string, error)
- func (m *Kit) PromptResult(ctx context.Context, message string) (*TurnResult, error)
- func (m *Kit) PromptWithCallbacks(ctx context.Context, message string, onToolCall func(name, args string), ...) (string, error)deprecated
- func (m *Kit) PromptWithOptions(ctx context.Context, msg string, opts PromptOptions) (string, error)
- func (m *Kit) RemoveExtensionFooter()
- func (m *Kit) RemoveExtensionHeader()
- func (m *Kit) RemoveExtensionWidget(id string)
- func (m *Kit) ResetExtensionEditor()
- func (m *Kit) SetExtensionContext(ctx extensions.Context)
- func (m *Kit) SetExtensionEditor(config extensions.EditorConfig)
- func (m *Kit) SetExtensionFooter(config extensions.HeaderFooterConfig)
- func (m *Kit) SetExtensionHeader(config extensions.HeaderFooterConfig)
- func (m *Kit) SetExtensionWidget(config extensions.WidgetConfig)
- func (m *Kit) SetSessionName(name 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) Subscribe(listener EventListener) func()
- type MCPServerConfig
- type Message
- type MessageEndEvent
- type MessageEntry
- type MessageRole
- type MessageStartEvent
- type MessageUpdateEvent
- type ModelCost
- type ModelInfo
- type ModelLimit
- type ModelsRegistry
- type Options
- type PromptBuilder
- type PromptOptions
- type PromptTemplate
- type ProviderConfig
- type ProviderInfo
- type ProviderResult
- type ReasoningContent
- type ResponseEvent
- type ResponseHandler
- type SessionHeader
- type SessionInfo
- type Skill
- type SpinnerFunc
- type StreamingResponseHandler
- type TextContent
- 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 NewReadTool(opts ...ToolOption) Tool
- func NewWriteTool(opts ...ToolOption) Tool
- func ReadOnlyTools(opts ...ToolOption) []Tool
- type ToolCall
- type ToolCallContentEvent
- type ToolCallContentHandler
- type ToolCallEvent
- type ToolCallHandler
- type ToolExecutionEndEvent
- type ToolExecutionHandler
- type ToolExecutionStartEvent
- type ToolOption
- type ToolResult
- type ToolResultEvent
- type ToolResultHandler
- type TreeManager
- type TurnEndEvent
- type TurnResult
- type TurnStartEvent
Constants ¶
const ( RoleUser = message.RoleUser RoleAssistant = message.RoleAssistant RoleTool = message.RoleTool RoleSystem = message.RoleSystem )
Variables ¶
var ( // ParseModelString parses a model string in "provider/model" format. ParseModelString = models.ParseModelString // CreateProvider creates a fantasy LanguageModel based on provider config. CreateProvider = models.CreateProvider // GetGlobalRegistry returns the global models registry instance. GetGlobalRegistry = models.GetGlobalRegistry // LoadSystemPrompt loads system prompt from file or returns string directly. LoadSystemPrompt = config.LoadSystemPrompt )
var WithWorkDir = core.WithWorkDir
WithWorkDir sets the working directory for file-based tools. If empty, os.Getwd() is used at execution time.
Functions ¶
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 ConvertToFantasyMessages ¶
ConvertToFantasyMessages converts an SDK message to the underlying fantasy messages used by the agent for LLM interactions.
func DeleteSession ¶
DeleteSession removes a session file from disk.
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 GetFantasyProviders ¶
func GetFantasyProviders() []string
GetFantasyProviders returns provider IDs that can be used with fantasy, either through a native provider or via openaicompat auto-routing.
func GetModelsForProvider ¶
GetModelsForProvider returns all known models for a provider.
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 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 LoadConfigWithEnvSubstitution ¶
LoadConfigWithEnvSubstitution loads a config file with ${ENV_VAR} expansion.
func RefreshModelRegistry ¶
func RefreshModelRegistry()
RefreshModelRegistry reloads the global model database from the current data sources (cache -> embedded). Call after updating the cache.
func SuggestModels ¶
SuggestModels returns model names similar to an invalid model string.
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 ¶
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 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 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
}
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 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 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" )
type FantasyMessage ¶
FantasyMessage is the underlying message type used by the fantasy agent library. Re-exported so SDK users can work with fantasy types without a direct import of charm.land/fantasy.
type FantasyResponse ¶
FantasyResponse is the response type returned by the fantasy agent library.
type FantasyUsage ¶
FantasyUsage contains token usage information from an LLM response.
type GenerateResult ¶
type GenerateResult = agent.GenerateWithLoopResult
GenerateResult contains the result and conversation history from an agent interaction.
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.
func (*Kit) Branch ¶
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) 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) 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.
After compaction, the tree session is cleared and replaced with the compacted messages (summary + preserved recent messages).
func (*Kit) EmitSessionStart ¶ added in v0.2.0
func (m *Kit) EmitSessionStart()
EmitSessionStart fires the SessionStart event for extensions. No-op if extensions are disabled or no handlers are registered.
func (*Kit) EstimateContextTokens ¶
EstimateContextTokens returns the estimated token count of the current conversation based on tree session messages.
func (*Kit) ExtensionCommands ¶ added in v0.2.0
func (m *Kit) ExtensionCommands() []extensions.CommandDef
ExtensionCommands returns the slash commands registered by extensions. Returns nil if extensions are disabled or no commands are registered.
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) 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) GetBufferedLogger
deprecated
func (m *Kit) GetBufferedLogger() *tools.BufferedDebugLogger
GetBufferedLogger returns the buffered debug logger (nil if not configured).
Deprecated: Use GetBufferedDebugMessages instead.
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.
func (*Kit) GetExtRunner
deprecated
func (m *Kit) GetExtRunner() *extensions.Runner
GetExtRunner returns the extension runner (nil if extensions are disabled).
Deprecated: Use SetExtensionContext and EmitSessionStart instead. GetExtRunner leaks the internal extensions.Runner type across the SDK boundary.
func (*Kit) GetExtensionContext ¶ added in v0.2.0
func (m *Kit) GetExtensionContext() extensions.Context
GetExtensionContext returns the current extension runtime context. Returns a zero Context if extensions are disabled.
func (*Kit) GetExtensionEditor ¶ added in v0.2.0
func (m *Kit) GetExtensionEditor() *extensions.EditorConfig
GetExtensionEditor returns the current editor interceptor, or nil if none is set. Returns nil if extensions are disabled.
func (*Kit) GetExtensionFooter ¶ added in v0.2.0
func (m *Kit) GetExtensionFooter() *extensions.HeaderFooterConfig
GetExtensionFooter returns the current custom footer, or nil if none is set. Returns nil if extensions are disabled.
func (*Kit) GetExtensionHeader ¶ added in v0.2.0
func (m *Kit) GetExtensionHeader() *extensions.HeaderFooterConfig
GetExtensionHeader returns the current custom header, or nil if none is set. Returns nil if extensions are disabled.
func (*Kit) GetExtensionToolCount ¶ added in v0.2.0
GetExtensionToolCount returns the number of tools registered by extensions.
func (*Kit) GetExtensionToolRenderer ¶ added in v0.2.0
func (m *Kit) GetExtensionToolRenderer(toolName string) *extensions.ToolRenderConfig
GetExtensionToolRenderer returns the custom renderer for the named tool, or nil if no extension registered a renderer for it. Returns nil if extensions are disabled.
func (*Kit) GetExtensionWidgets ¶ added in v0.2.0
func (m *Kit) GetExtensionWidgets(placement extensions.WidgetPlacement) []extensions.WidgetConfig
GetExtensionWidgets returns extension widgets matching the given placement. Returns nil if extensions are disabled or no widgets match.
func (*Kit) GetLoadedServerNames ¶ added in v0.2.0
GetLoadedServerNames returns the names of successfully loaded MCP servers.
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) GetMCPToolCount ¶ added in v0.2.0
GetMCPToolCount returns the number of tools loaded from external MCP servers.
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 tree session, or empty when no tree session is configured.
func (*Kit) GetSessionPath ¶
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) GetToolNames ¶ added in v0.2.0
GetToolNames returns the names of all tools available to the agent.
func (*Kit) GetTreeSession ¶
func (m *Kit) GetTreeSession() *TreeManager
GetTreeSession returns the tree session manager, or nil if not configured.
func (*Kit) HasExtensions ¶ added in v0.2.0
HasExtensions returns true if the extension runner is configured and active.
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) 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) 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) 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 ¶
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) PromptWithCallbacks
deprecated
func (m *Kit) PromptWithCallbacks( ctx context.Context, message string, onToolCall func(name, args string), onToolResult func(name, args, result string, isError bool), onStreaming func(chunk string), ) (string, error)
PromptWithCallbacks sends a message with callbacks for monitoring tool execution and streaming responses. Lifecycle events are also emitted to all registered subscribers (via Subscribe).
Deprecated: Use Subscribe/OnToolCall/OnToolResult/OnStreaming instead of inline callbacks. PromptWithCallbacks is retained for backward compatibility.
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) RemoveExtensionFooter ¶ added in v0.2.0
func (m *Kit) RemoveExtensionFooter()
RemoveExtensionFooter removes the custom extension footer. Delegates to the extension runner. No-op if extensions are disabled.
func (*Kit) RemoveExtensionHeader ¶ added in v0.2.0
func (m *Kit) RemoveExtensionHeader()
RemoveExtensionHeader removes the custom extension header. Delegates to the extension runner. No-op if extensions are disabled.
func (*Kit) RemoveExtensionWidget ¶ added in v0.2.0
RemoveExtensionWidget removes a previously placed extension widget by ID. Delegates to the extension runner. No-op if extensions are disabled.
func (*Kit) ResetExtensionEditor ¶ added in v0.2.0
func (m *Kit) ResetExtensionEditor()
ResetExtensionEditor removes the active editor interceptor from extensions. Delegates to the extension runner. No-op if extensions are disabled.
func (*Kit) SetExtensionContext ¶ added in v0.2.0
func (m *Kit) SetExtensionContext(ctx extensions.Context)
SetExtensionContext configures the extension runner with the given context functions. No-op if extensions are disabled.
func (*Kit) SetExtensionEditor ¶ added in v0.2.0
func (m *Kit) SetExtensionEditor(config extensions.EditorConfig)
SetExtensionEditor installs an editor interceptor from extensions. Delegates to the extension runner. No-op if extensions are disabled.
func (*Kit) SetExtensionFooter ¶ added in v0.2.0
func (m *Kit) SetExtensionFooter(config extensions.HeaderFooterConfig)
SetExtensionFooter places or replaces the custom footer from extensions. Delegates to the extension runner. No-op if extensions are disabled.
func (*Kit) SetExtensionHeader ¶ added in v0.2.0
func (m *Kit) SetExtensionHeader(config extensions.HeaderFooterConfig)
SetExtensionHeader places or replaces the custom header from extensions. Delegates to the extension runner. No-op if extensions are disabled.
func (*Kit) SetExtensionWidget ¶ added in v0.2.0
func (m *Kit) SetExtensionWidget(config extensions.WidgetConfig)
SetExtensionWidget places or updates a persistent extension widget. Delegates to the extension runner. No-op if extensions are disabled.
func (*Kit) SetSessionName ¶
SetSessionName sets a user-defined display name for the active tree session.
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 ¶
ShouldCompact reports whether the conversation is near the model's context limit and should be compacted. Uses Pi's formula: contextTokens > contextWindow − reserveTokens. Returns false if the model's context limit is unknown.
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) Subscribe ¶
func (m *Kit) Subscribe(listener EventListener) func()
Subscribe registers an EventListener that will be called for every lifecycle event emitted during Prompt() and PromptWithCallbacks(). Returns an unsubscribe function that removes the listener.
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 ¶
Message is a single conversation message containing heterogeneous content parts (text, reasoning, tool calls, tool results, finish markers).
func ConvertFromFantasyMessage ¶
ConvertFromFantasyMessage converts a fantasy message from the agent to an SDK message format for use in the SDK API.
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.
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).
type ReasoningContent ¶
type ReasoningContent = message.ReasoningContent
ReasoningContent holds extended thinking / reasoning output from the LLM.
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 ¶
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 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 StreamingResponseHandler ¶
type StreamingResponseHandler = agent.StreamingResponseHandler
StreamingResponseHandler is a function type for handling streaming LLM responses.
type TextContent ¶
type TextContent = message.TextContent
TextContent holds plain text content within a message.
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 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.
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 ¶
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 {
ToolName 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 {
ToolName string
}
ToolExecutionStartEvent fires when a tool begins executing.
func (ToolExecutionStartEvent) EventType ¶
func (e ToolExecutionStartEvent) EventType() EventType
EventType implements Event.
type ToolResult ¶
type ToolResult = message.ToolResult
ToolResult represents the result of executing a tool.
type ToolResultEvent ¶
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 TreeManager ¶
type TreeManager = session.TreeManager
TreeManager manages a tree-structured JSONL session with branching, leaf-pointer tracking, and context building.
type TurnEndEvent ¶
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
// 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 *FantasyUsage
// 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 *FantasyUsage
// Messages is the full updated conversation after the turn, including
// any tool call/result messages added during the agent loop.
Messages []FantasyMessage
}
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.