extensions

package
v0.124.2 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Overview

Package extensions implements an in-process extension system for KIT. Extensions are plain Go files loaded at runtime via Yaegi (a Go interpreter). They register event handlers using an API object, enabling tool interception, input transformation, and lifecycle observation — all without recompilation.

Package extensions provides subagent spawning capabilities for Kit extensions.

Index

Constants

View Source
const (
	ToolKindExecute  = "execute" // Shell execution (the shell tool)
	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.

This is the single source of truth for tool-kind classification; the pkg/kit SDK re-exports these constants.

View Source
const SystemExtensionsDirEnv = "KIT_SYSTEM_EXTENSIONS_DIR"

SystemExtensionsDirEnv is the environment variable that overrides SystemExtensionsDir at runtime. It accepts one or more directories separated by the platform list separator (":" on Unix). An empty value disables system-wide discovery.

Variables

View Source
var ErrAgentBusy = errors.New("agent is busy")

ErrAgentBusy is returned (wrapped) when an extension API call that requires the agent to be idle cannot proceed because the agent is still processing a turn or post-turn hooks. Most notably, ctx.NewSession waits for idle internally; if its wait deadline elapses it returns an error that wraps this sentinel.

Extensions can detect the condition with errors.Is:

if err := ctx.NewSession(prompt); err != nil {
    if errors.Is(err, ext.ErrAgentBusy) {
        // agent never settled — fall back to a queued message instead
    }
}
View Source
var SystemExtensionsDir = "/usr/share/kit/extensions"

SystemExtensionsDir is the system-wide extensions directory. It holds extensions that ship with a packaged installation of Kit (rpm, deb, and so on) and are shared by every user of the machine.

Packagers can point it somewhere else at build time:

go build -ldflags "-X github.com/mark3labs/kit/internal/extensions.SystemExtensionsDir=/opt/kit/extensions" ./cmd/kit

Set it to an empty string to disable system-wide discovery.

Functions

func CleanupTempDir added in v0.14.0

func CleanupTempDir(tempDir string)

CleanupTempDir removes a temporary directory used for preview.

func ExtensionToolsAsLLMTools added in v0.51.0

func ExtensionToolsAsLLMTools(defs []ToolDef, runner *Runner) []fantasy.AgentTool

ExtensionToolsAsLLMTools converts ToolDef values registered by extensions into LLM agent tool implementations so the LLM can invoke them. The runner is optional; if provided, ToolContext.OnProgress routes progress messages through the runner's Print function.

func FindInManifest added in v0.14.0

func FindInManifest(identity string) (*ManifestEntry, InstallScope, error)

FindInManifest finds an entry by identity in either global or project manifest. Returns the entry and its scope, or nil if not found.

func NormalizeShortcutKey added in v0.95.0

func NormalizeShortcutKey(key string) string

NormalizeShortcutKey converts a shortcut binding into the canonical spelling Kit matches against. Modifier aliases are folded, modifiers are reordered into canonical order, duplicates are dropped, and known key names are normalized. Bindings containing an unrecognized modifier are returned trimmed but otherwise untouched, so an unusual-but-valid terminal key name still has a chance to match.

func Symbols

func Symbols() interp.Exports

Symbols returns the Yaegi export table that makes KIT's extension API available to interpreted Go code. Extensions import these types as:

import "kit/ext"

IMPORTANT: Only concrete types (structs, constants) are exported.

Yaegi cannot SYNTHESIZE an interface wrapper at runtime: when interpreted code must produce a value of a host interface type, it panics in genInterfaceWrapper. Two consequences shape this table:

  1. The Event, Result and HandlerFunc types are not exported, so there is no generic On(EventType, HandlerFunc). Extensions use event-specific methods like api.OnToolCall() with concrete function signatures. Measured: a handler returning a concrete Result works, but the idiomatic `return nil` panics during Eval — which is why the generic form is not offered.
  2. Build-time wrappers (the `_Iface` structs that `yaegi extract` generates) DO work, and would let interpreted types satisfy host interfaces. Adopting them additionally requires the export key to match the type's real Go package path — the virtual "kit/ext" path works for structs but yields a nil dereference for interfaces.

func ToolKindFor added in v0.75.1

func ToolKindFor(toolName string) string

ToolKindFor returns the ToolKind for a given tool name, defaulting to ToolKindExecute for unknown tools (including MCP tools).

func ValidateShortcutKey added in v0.95.0

func ValidateShortcutKey(key string) (normalized string, warning string, err error)

ValidateShortcutKey normalizes a binding and reports whether Kit can deliver it. A non-nil error means the shortcut must be rejected: the handler could never fire. A non-empty warning means the shortcut will fire but shadows built-in behaviour.

func WatchedDirs added in v0.35.0

func WatchedDirs(extraPaths []string) []string

WatchedDirs returns the directories to watch for extension changes. This includes the system-wide extensions directories, the per-user extensions directory and the project-local .kit/extensions/ directory (if they exist). Explicit -e paths that point to directories are also included; explicit file paths cause their parent directory to be watched instead.

func WrapToolsWithExtensions

func WrapToolsWithExtensions(tools []fantasy.AgentTool, runner *Runner) []fantasy.AgentTool

If the runner has no relevant handlers the original tools are returned unchanged (zero overhead).

Types

type API

type API struct {
	// contains filtered or unexported fields
}

API is passed to each extension's Init function. Extensions use it to register typed event handlers, custom tools, and slash commands.

func NewTestAPI added in v0.15.0

func NewTestAPI(ext *LoadedExtension) API

NewTestAPI creates an API object wired for testing. This is used by the test harness to load extensions and verify behavior. The registration functions wire handlers directly to the provided extension.

func (*API) OnAgentEnd

func (a *API) OnAgentEnd(handler func(AgentEndEvent, Context))

OnAgentEnd registers a handler for when the agent finishes responding.

func (*API) OnAgentStart

func (a *API) OnAgentStart(handler func(AgentStartEvent, Context))

OnAgentStart registers a handler for when the agent loop begins.

func (*API) OnBeforeAgentStart

func (a *API) OnBeforeAgentStart(handler func(BeforeAgentStartEvent, Context) *BeforeAgentStartResult)

OnBeforeAgentStart registers a handler that fires before the agent loop.

func (*API) OnBeforeCompact added in v0.3.0

func (a *API) OnBeforeCompact(handler func(BeforeCompactEvent, Context) *BeforeCompactResult)

OnBeforeCompact registers a handler that fires before context compaction runs. Return a non-nil BeforeCompactResult with Cancel=true to prevent compaction from proceeding.

func (*API) OnBeforeFork added in v0.3.0

func (a *API) OnBeforeFork(handler func(BeforeForkEvent, Context) *BeforeForkResult)

OnBeforeFork registers a handler that fires before the session tree is branched to a different entry point. Return a non-nil BeforeForkResult with Cancel=true to prevent the fork.

func (*API) OnBeforeSessionSwitch added in v0.3.0

func (a *API) OnBeforeSessionSwitch(handler func(BeforeSessionSwitchEvent, Context) *BeforeSessionSwitchResult)

OnBeforeSessionSwitch registers a handler that fires before the session is switched to a new branch (e.g. /new command). Return a non-nil BeforeSessionSwitchResult with Cancel=true to prevent the switch.

func (*API) OnContextPrepare added in v0.3.0

func (a *API) OnContextPrepare(handler func(ContextPrepareEvent, Context) *ContextPrepareResult)

OnContextPrepare registers a handler that fires after the context window is built from the session tree (including compaction) and before the messages are sent to the LLM. The handler can inspect the context and return a modified message set to filter, reorder, or inject messages.

Return nil to leave the context unchanged. Return a non-nil result with a Messages slice to replace the context window entirely. Messages with a non-negative Index reuse the original message at that position (preserving tool calls, reasoning parts, etc.); messages with Index < 0 are created fresh from Role + Content.

Example — inject a RAG context message:

api.OnContextPrepare(func(e ext.ContextPrepareEvent, ctx ext.Context) *ext.ContextPrepareResult {
    ragContext := fetchRelevantDocs(e.Messages[len(e.Messages)-1].Content)
    injected := ext.ContextMessage{Index: -1, Role: "system", Content: ragContext}
    msgs := append([]ext.ContextMessage{injected}, e.Messages...)
    return &ext.ContextPrepareResult{Messages: msgs}
})

func (*API) OnCustomEvent added in v0.3.0

func (a *API) OnCustomEvent(name string, handler func(string))

OnCustomEvent registers a handler for a custom inter-extension event. The handler receives the data string published by EmitCustomEvent. Multiple handlers can subscribe to the same event name; they execute in registration order.

func (*API) OnError added in v0.60.0

func (a *API) OnError(handler func(ErrorEvent, Context))

OnError registers a handler that fires when an agent-level error occurs during streaming.

func (*API) OnInput

func (a *API) OnInput(handler func(InputEvent, Context) *InputResult)

OnInput registers a handler that fires when user input is received. Return a non-nil InputResult to transform or handle the input.

func (*API) OnLLMUsage added in v0.75.0

func (a *API) OnLLMUsage(handler func(LLMUsageEvent, Context))

OnLLMUsage registers a handler that fires after each LLM provider call with the token and cost deltas for that single call. Use this for per-call usage attribution, real-time budget enforcement, and cost dashboards that need to react between calls within a single agent turn.

Handlers receive an LLMUsageEvent describing the call's input/output tokens, cache tokens, computed cost, model, and provider. A single agent turn typically fires multiple LLMUsageEvents (one per tool-loop iteration).

func (*API) OnMessageEnd

func (a *API) OnMessageEnd(handler func(MessageEndEvent, Context))

OnMessageEnd registers a handler for when the assistant message is complete.

func (*API) OnMessageStart

func (a *API) OnMessageStart(handler func(MessageStartEvent, Context))

OnMessageStart registers a handler for when an assistant message begins.

func (*API) OnMessageUpdate

func (a *API) OnMessageUpdate(handler func(MessageUpdateEvent, Context))

OnMessageUpdate registers a handler for streaming text chunks.

func (*API) OnModelChange added in v0.3.0

func (a *API) OnModelChange(handler func(ModelChangeEvent, Context))

OnModelChange registers a handler that fires after the active model is changed via ctx.SetModel(). The handler receives the new and previous model strings plus the source of the change.

func (*API) OnPrepareStep added in v0.60.0

func (a *API) OnPrepareStep(handler func(PrepareStepEvent, Context) *PrepareStepResult)

OnPrepareStep registers a handler that fires between steps within a multi-step agent turn, after steering messages are injected and before messages are sent to the LLM. Return a non-nil PrepareStepResult with Messages to replace the context window for this step.

func (*API) OnReasoningStart added in v0.60.0

func (a *API) OnReasoningStart(handler func(ReasoningStartEvent, Context))

OnReasoningStart registers a handler that fires when the LLM begins reasoning/thinking.

func (*API) OnRetry added in v0.60.0

func (a *API) OnRetry(handler func(RetryEvent, Context))

OnRetry registers a handler that fires when the LLM provider request is retried after a transient error.

func (*API) OnSessionShutdown

func (a *API) OnSessionShutdown(handler func(SessionShutdownEvent, Context))

OnSessionShutdown registers a handler for when the application is closing.

func (*API) OnSessionStart

func (a *API) OnSessionStart(handler func(SessionStartEvent, Context))

OnSessionStart registers a handler for when a session is loaded or created.

func (*API) OnSource added in v0.60.0

func (a *API) OnSource(handler func(SourceEvent, Context))

OnSource registers a handler that fires when the LLM references a source (e.g. from web search tools).

func (*API) OnStepFinish added in v0.60.0

func (a *API) OnStepFinish(handler func(StepFinishEvent, Context))

OnStepFinish registers a handler that fires when a step completes, providing step number, finish reason, and decomposed token usage.

func (*API) OnStepStart added in v0.60.0

func (a *API) OnStepStart(handler func(StepStartEvent, Context))

OnStepStart registers a handler that fires when a new LLM call begins within a multi-step agent turn.

func (*API) OnSubagentChunk added in v0.24.0

func (a *API) OnSubagentChunk(handler func(SubagentChunkEvent, Context))

OnSubagentChunk registers a handler for real-time events from a running subagent. ChunkType identifies the kind of event ("text", "tool_call", "tool_result", "tool_execution_start", "tool_execution_end", etc.). Correlate with OnSubagentStart via the ToolCallID field.

func (*API) OnSubagentEnd added in v0.24.0

func (a *API) OnSubagentEnd(handler func(SubagentEndEvent, Context))

OnSubagentEnd registers a handler that fires when a subagent call completes. ErrorMsg is non-empty when the subagent failed.

func (*API) OnSubagentStart added in v0.24.0

func (a *API) OnSubagentStart(handler func(SubagentStartEvent, Context))

OnSubagentStart registers a handler that fires when a subagent tool call begins executing. Use the ToolCallID to correlate with subsequent OnSubagentChunk and OnSubagentEnd events for the same subagent.

func (*API) OnTerminalResize added in v0.91.0

func (a *API) OnTerminalResize(handler func(TerminalResizeEvent, Context))

OnTerminalResize registers a handler that fires when the terminal is resized, and once at startup with the initial dimensions.

Footer, header, and widget content is rendered at full width without truncation, so an over-long line wraps and eats a row of scrollback. Use this to re-render chrome at the new width.

Example:

api.OnTerminalResize(func(e ext.TerminalResizeEvent, ctx ext.Context) {
    ctx.SetFooter(ext.HeaderFooterConfig{
        Content: ext.WidgetContent{Text: fit(line, e.Width)},
    })
})

func (*API) OnThinkingLevelChange added in v0.91.0

func (a *API) OnThinkingLevelChange(handler func(ThinkingLevelChangeEvent, Context))

OnThinkingLevelChange registers a handler that fires after the extended thinking effort level changes, whether from the /thinking command, the shift+tab shortcut, or an automatic downgrade on model switch.

Example — keep a footer in sync with the effort level:

api.OnThinkingLevelChange(func(e ext.ThinkingLevelChangeEvent, ctx ext.Context) {
    ctx.SetFooter(ext.HeaderFooterConfig{
        Content: ext.WidgetContent{Text: "effort: " + e.NewLevel},
    })
})

func (*API) OnToolCall

func (a *API) OnToolCall(handler func(ToolCallEvent, Context) *ToolCallResult)

OnToolCall registers a handler that fires before a tool executes. Return a non-nil ToolCallResult with Block=true to prevent execution.

The event's ToolName is the tool's registered name. The command-execution tool is registered as "shell"; before its shell became configurable it was registered as "bash", so a handler that should run on either version of KIT matches both:

if tc.ToolName != "shell" && tc.ToolName != "bash" { return nil }

The bundled extension examples match both names for that reason.

func (*API) OnToolCallInputDelta added in v0.58.0

func (a *API) OnToolCallInputDelta(handler func(ToolCallInputDeltaEvent, Context))

OnToolCallInputDelta registers a handler that fires for each streamed fragment of tool call arguments as they arrive from the LLM.

func (*API) OnToolCallInputEnd added in v0.58.0

func (a *API) OnToolCallInputEnd(handler func(ToolCallInputEndEvent, Context))

OnToolCallInputEnd registers a handler that fires when tool argument streaming is complete, before the tool call is parsed and execution begins.

func (*API) OnToolCallInputStart added in v0.58.0

func (a *API) OnToolCallInputStart(handler func(ToolCallInputStartEvent, Context))

OnToolCallInputStart registers a handler that fires when the LLM begins generating tool call arguments. The tool name is known but the full argument JSON is still being streamed. Useful for showing a "running" indicator immediately without waiting for the full arguments.

func (*API) OnToolExecutionEnd

func (a *API) OnToolExecutionEnd(handler func(ToolExecutionEndEvent, Context))

OnToolExecutionEnd registers a handler for tool execution end.

func (*API) OnToolExecutionStart

func (a *API) OnToolExecutionStart(handler func(ToolExecutionStartEvent, Context))

OnToolExecutionStart registers a handler for tool execution start.

func (*API) OnToolOutput added in v0.20.0

func (a *API) OnToolOutput(handler func(ToolOutputEvent, Context))

OnToolOutput registers a handler for streaming tool output chunks. This fires for each output line as it arrives from tools like the shell tool, allowing extensions to observe or process output in real-time.

func (*API) OnToolResult

func (a *API) OnToolResult(handler func(ToolResultEvent, Context) *ToolResultResult)

OnToolResult registers a handler that fires after tool execution. Return a non-nil ToolResultResult to modify the output.

func (*API) OnTurnStateChange added in v0.91.0

func (a *API) OnTurnStateChange(handler func(TurnStateChangeEvent, Context))

OnTurnStateChange registers a handler that fires when the UI enters or leaves its working state.

This covers every busy/idle transition, including shell commands that never reach the agent loop and turns that end in cancellation or error — cases AgentStart/AgentEnd do not report. Use it to drive a spinner or turn timer.

Example — time every turn:

api.OnTurnStateChange(func(e ext.TurnStateChangeEvent, ctx ext.Context) {
    if e.State == "working" {
        started = time.Now()
    } else {
        elapsed = time.Since(started)
    }
})

func (*API) OnWarnings added in v0.60.0

func (a *API) OnWarnings(handler func(WarningsEvent, Context))

OnWarnings registers a handler that fires when the LLM provider returns warnings about the request.

func (*API) RegisterCommand

func (a *API) RegisterCommand(cmd CommandDef)

RegisterCommand adds a slash command available in interactive mode.

func (*API) RegisterMessageRenderer added in v0.3.0

func (a *API) RegisterMessageRenderer(config MessageRendererConfig)

RegisterMessageRenderer registers a named message renderer that extensions can invoke via ctx.RenderMessage(name, content). Use this to define reusable visual styles for branded output, progress reports, or custom notification formats. If multiple extensions register the same name, the last one wins.

func (*API) RegisterOption added in v0.3.0

func (a *API) RegisterOption(opt OptionDef)

RegisterOption declares a named configuration option. The option can be set via environment variables (KIT_OPT_<NAME>) or config file (options.<name>). Multiple extensions can register options with the same name; the last default wins.

func (*API) RegisterShortcut added in v0.3.0

func (a *API) RegisterShortcut(def ShortcutDef, handler func(Context))

RegisterShortcut registers a global keyboard shortcut that fires across all app states except modal prompts/overlays. Use modifier combinations like "ctrl+p", "alt+t", or "f1" — avoid bare characters that conflict with text input. If multiple extensions register the same key, the last registration wins. The handler runs in a goroutine so it can call blocking APIs like PromptSelect without stalling the TUI event loop.

Keys are normalized at registration, so "Ctrl+Shift+S", "control+shift+s" and "shift+ctrl+s" all resolve to the same binding. Both spellings of a shifted key work: "shift+a" and "A" match the same press.

Two classes of binding are handled specially:

  • "ctrl+c" is reserved. Kit consumes it for cancel/quit before extensions are consulted, so the registration is rejected with a logged warning rather than silently never firing.
  • Keys bound by Kit itself ("esc", "ctrl+x", "pgup", "enter", ...) are accepted but log a warning, because the shortcut dispatcher runs first and will shadow the built-in behaviour.

An armed Ctrl+X leader chord takes precedence over shortcuts, so binding a chord suffix does not break the built-in chords.

func (*API) RegisterTool

func (a *API) RegisterTool(tool ToolDef)

RegisterTool adds a custom tool that the LLM can invoke.

func (*API) RegisterToolRenderer added in v0.2.0

func (a *API) RegisterToolRenderer(config ToolRenderConfig)

RegisterToolRenderer registers a custom renderer for a specific tool's display in the TUI. The renderer controls the header (parameter summary) and/or body (result display) of the tool's output block. If multiple extensions register renderers for the same tool name, the last one wins.

type AgentEndEvent

type AgentEndEvent struct {
	Response   string
	StopReason string // "completed", "cancelled", "error"

	// ToolCallCount is the total number of tool invocations observed during
	// this turn (sum across all steps).
	ToolCallCount int

	// ToolNames lists the tool names invoked during this turn, in call order.
	// Duplicates are preserved (e.g. two shell calls produce ["shell", "shell"]).
	ToolNames []string

	// LLMCallCount is the number of LLM round-trips (tool-loop iterations)
	// performed during this turn. Always >= 1 for a successful turn.
	LLMCallCount int

	// InputTokensDelta is the sum of input tokens consumed during this turn
	// across every LLM call (including cache-hit input tokens).
	InputTokensDelta int

	// OutputTokensDelta is the sum of output tokens generated during this turn.
	OutputTokensDelta int

	// CacheReadTokensDelta is the sum of cache-read tokens during this turn.
	CacheReadTokensDelta int

	// CacheWriteTokensDelta is the sum of cache-write tokens during this turn.
	CacheWriteTokensDelta int

	// CostDelta is the total cost in USD attributable to this turn. Computed
	// from per-step usage and current model pricing. Zero when pricing is
	// unknown or OAuth credentials are in use.
	CostDelta float64

	// DurationMs is the elapsed wall-clock time from AgentStart to AgentEnd,
	// in milliseconds.
	DurationMs int64
}

AgentEndEvent fires when the agent finishes responding. In addition to the final response and stop reason, the event carries per-turn aggregates so observer-style extensions don't have to maintain parallel bookkeeping in OnToolResult / OnStepFinish handlers.

func (AgentEndEvent) Type

func (e AgentEndEvent) Type() EventType

type AgentStartEvent

type AgentStartEvent struct {
	Prompt string
}

AgentStartEvent fires when the agent loop begins.

func (AgentStartEvent) Type

func (e AgentStartEvent) Type() EventType

type ArgumentPattern added in v0.28.0

type ArgumentPattern struct {
	// Positional names for $1, $2, etc.
	Positional []string
	// Rest is the variable name for $@ (all remaining).
	Rest string
	// Flags maps flag names to variable names (e.g., "--loop" -> "loop").
	Flags map[string]string
}

ArgumentPattern defines how to parse command arguments.

type BeforeAgentStartEvent

type BeforeAgentStartEvent struct {
	Prompt string
}

BeforeAgentStartEvent fires before the agent loop begins.

func (BeforeAgentStartEvent) Type

type BeforeAgentStartResult

type BeforeAgentStartResult struct {
	InjectText   *string
	SystemPrompt *string
}

BeforeAgentStartResult can inject context before the agent runs.

type BeforeCompactEvent added in v0.3.0

type BeforeCompactEvent 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
	// (as opposed to manual /compact command).
	IsAutomatic bool
}

BeforeCompactEvent fires before context compaction runs. Provides information about the current context state to help extensions decide whether to allow or block compaction.

func (BeforeCompactEvent) Type added in v0.3.0

func (e BeforeCompactEvent) Type() EventType

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 shown to the user when
	// Cancel is true. Empty string uses a default message.
	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. Return Cancel=true with an optional Reason to block compaction, or provide a custom Summary to replace the default LLM-generated one.

type BeforeForkEvent added in v0.3.0

type BeforeForkEvent struct {
	// TargetID is the session entry ID being branched to.
	TargetID string
	// IsUserMessage is true if the selected entry is a user message
	// (which causes the fork to target the parent entry).
	IsUserMessage bool
	// UserText is the user message text (non-empty only when IsUserMessage is true).
	UserText string
}

BeforeForkEvent fires before the session tree is branched to a different entry point (via the tree selector or /fork command).

func (BeforeForkEvent) Type added in v0.3.0

func (e BeforeForkEvent) Type() EventType

type BeforeForkResult added in v0.3.0

type BeforeForkResult struct {
	// Cancel, when true, prevents the fork from proceeding.
	Cancel bool
	// Reason is a human-readable explanation shown to the user when
	// Cancel is true. Empty string uses a default message.
	Reason string
}

BeforeForkResult controls whether the fork proceeds. Return Cancel=true with an optional Reason to block the fork.

type BeforeSessionSwitchEvent added in v0.3.0

type BeforeSessionSwitchEvent struct {
	// Reason describes why the switch is happening: "new" for /new command,
	// "clear" for /clear command.
	Reason string
	// InitialPrompt, when non-empty, is the prompt that will be submitted
	// as the first user turn of the new session. Set when /new is invoked
	// with an argument (e.g. "/new continue from HANDOFF.md") or when an
	// extension calls ctx.NewSession(prompt). Extensions may inspect this
	// to decide whether to allow the switch.
	InitialPrompt string
}

BeforeSessionSwitchEvent fires before the session is switched to a new branch (e.g. /new or /clear commands).

func (BeforeSessionSwitchEvent) Type added in v0.3.0

type BeforeSessionSwitchResult added in v0.3.0

type BeforeSessionSwitchResult struct {
	// Cancel, when true, prevents the session switch from proceeding.
	Cancel bool
	// Reason is a human-readable explanation shown to the user when
	// Cancel is true. Empty string uses a default message.
	Reason string
}

BeforeSessionSwitchResult controls whether the session switch proceeds. Return Cancel=true with an optional Reason to block the switch.

type CommandDef

type CommandDef struct {
	Name        string
	Description string
	Execute     func(args string, ctx Context) (string, error)
	// Complete provides argument tab-completion for this command.
	// Called with the partial argument text typed so far; returns
	// candidate completions. Nil means no argument completion.
	Complete func(prefix string, ctx Context) []string
}

CommandDef describes a slash command registered by an extension.

type CompactConfig added in v0.38.0

type CompactConfig struct {
	// CustomInstructions is optional text appended to the summary prompt
	// (e.g. "Focus on the API design decisions"). Empty uses the default.
	CustomInstructions string
	// OnComplete is called when compaction finishes successfully.
	// May be nil if the caller doesn't need notification.
	OnComplete func()
	// OnError is called when compaction fails. The argument is the error message.
	// May be nil if the caller doesn't need notification.
	OnError func(errMsg string)
}

CompactConfig configures a programmatic context compaction request.

type CompleteRequest added in v0.3.0

type CompleteRequest struct {
	// Model is the model to use in "provider/model" format (e.g.
	// "anthropic/claude-haiku-3-5-20241022"). Empty string uses the current
	// session model, avoiding extra provider creation overhead.
	Model string

	// Prompt is the user input text sent to the model.
	Prompt string

	// System is an optional system prompt. Empty uses no system prompt.
	System string

	// Messages is optional conversation history. If provided, Prompt is
	// appended as the final user message.
	Messages []SessionMessage

	// MaxTokens limits the response length (0 = provider default).
	MaxTokens int

	// OnChunk is called for each streaming text delta. When set, the
	// completion is performed in streaming mode. When nil, the call blocks
	// until the full response is available.
	OnChunk func(chunk string)
}

CompleteRequest configures a standalone LLM completion call. Extensions use this with ctx.Complete() to make direct LLM calls without the agent tool loop.

type CompleteResponse added in v0.3.0

type CompleteResponse struct {
	// Text is the complete response text.
	Text string

	// InputTokens is the number of tokens in the request.
	InputTokens int

	// OutputTokens is the number of tokens in the response.
	OutputTokens int

	// Model is the actual model used (useful when CompleteRequest.Model was empty).
	Model string
}

CompleteResponse contains the LLM response and usage metadata from a standalone completion call.

type Context

type Context struct {
	SessionID   string
	CWD         string
	Model       string
	Interactive bool

	// Print outputs plain text to the user. In interactive mode this
	// routes through BubbleTea's scrollback (tea.Println); in
	// non-interactive mode it writes to stdout. Extensions must use
	// this instead of fmt.Println, which is swallowed by BubbleTea.
	Print func(string)

	// PrintInfo outputs text as a styled system message block (bordered,
	// themed). Use this for informational notices the user should see.
	PrintInfo func(string)

	// PrintError outputs text as a styled error block (red border, bold).
	// Use this for error messages or warnings.
	PrintError func(string)

	// PrintBlock outputs text as a custom styled block with caller-chosen
	// border color and optional subtitle. Example:
	//
	//   ctx.PrintBlock(ext.PrintBlockOpts{
	//       Text:        "Deployment complete!",
	//       BorderColor: "#a6e3a1",
	//       Subtitle:    "my-extension",
	//   })
	PrintBlock func(PrintBlockOpts)

	// SendMessage injects a message into the conversation and triggers a
	// new agent turn. If the agent is currently busy the message is queued
	// and processed after the current turn completes.
	//
	// This is safe to call from goroutines. Common pattern:
	//
	//   go func() {
	//       out, _ := exec.Command("kit", "-p", task).Output()
	//       ctx.SendMessage("Subagent result:\n" + string(out))
	//   }()
	SendMessage func(string)

	// CancelAndSend cancels the current agent turn (if running), clears
	// the message queue, and sends a new message that executes as soon as
	// cancellation completes. If the agent is idle, the message executes
	// immediately. This is the "steer" delivery mode.
	//
	// Use this for directive changes that should interrupt the current
	// operation, e.g. switching modes or redirecting the agent.
	//
	// Example:
	//
	//   ctx.CancelAndSend("Stop what you're doing and focus on the tests")
	CancelAndSend func(string)

	// Abort cancels the current agent turn (if running) and clears the
	// message queue. Unlike CancelAndSend, no new message is injected —
	// the agent simply stops. Safe to call when idle (no-op).
	//
	// Example:
	//
	//   ctx.Abort()  // stop whatever the agent is doing
	Abort func()

	// IsIdle returns true when the agent is not processing a turn.
	// Extensions can use this to decide whether to dispatch immediately
	// or queue work for later.
	//
	// Example:
	//
	//   if ctx.IsIdle() {
	//       ctx.SendMessage("start new task")
	//   }
	IsIdle func() bool

	// Compact triggers context compaction, summarising older messages to
	// free context window space. Returns an error if compaction cannot
	// start (e.g. agent is busy or app is closed). The actual compaction
	// runs asynchronously; use OnComplete/OnError callbacks in
	// CompactConfig to observe the result.
	//
	// Example:
	//
	//   err := ctx.Compact(ext.CompactConfig{
	//       OnComplete: func() { ctx.PrintInfo("Compaction done") },
	//       OnError:    func(errMsg string) { ctx.PrintError("Compact failed: " + errMsg) },
	//   })
	Compact func(CompactConfig) error

	// SendMultimodalMessage injects a message with file attachments (images,
	// documents) into the conversation and triggers a new agent turn. Files
	// are described by FilePart structs containing the raw bytes, filename,
	// and MIME type. If the agent is busy the message is queued.
	//
	// Example:
	//
	//   data, _ := os.ReadFile("photo.jpg")
	//   ctx.SendMultimodalMessage("Describe this image", []ext.FilePart{
	//       {Filename: "photo.jpg", Data: data, MediaType: "image/jpeg"},
	//   })
	SendMultimodalMessage func(text string, files []FilePart)

	// NewSession ends the current session and starts a fresh one (matching
	// the /new slash command). When prompt is non-empty it is submitted as
	// the first user turn of the new session, with @file references
	// expanded the same way they are for normal user input. Pass an empty
	// string to start an empty session.
	//
	// If the agent is currently busy when NewSession is called (for example,
	// from an OnAgentEnd hook that fires before the agent fully settles, or
	// while post-turn formatters/linters are still running), the call blocks
	// until the agent transitions to idle. This avoids the v0.79.0
	// phase-handoff race where NewSession from OnAgentEnd would fail with
	// "agent is busy" because TurnEnd fires before the busy flag clears.
	// The wait has a generous internal timeout; if it elapses the returned
	// error wraps ErrAgentBusy (detectable with errors.Is).
	//
	// Returns an error if the agent does not become idle within the wait
	// window, if a registered BeforeSessionSwitch handler cancels the
	// switch, or if the new session file cannot be created. In
	// non-interactive (ACP / headless) mode this is a no-op that returns
	// an error.
	//
	// Because NewSession may block, call it from a goroutine — not
	// directly from inside an event handler that the agent loop is waiting
	// on.
	//
	// Typical pattern — start a fresh session at the end of a phase by
	// reading a handoff file:
	//
	//   api.OnAgentEnd(func(e ext.AgentEndEvent, ctx ext.Context) {
	//       msgs := ctx.GetMessages()
	//       if len(msgs) == 0 {
	//           return
	//       }
	//       last := msgs[len(msgs)-1].Content
	//       if strings.Contains(last, "<HANDOFF_READY>") {
	//           go func() {
	//               _ = ctx.NewSession("Read @HANDOFF.md and continue the next phase.")
	//           }()
	//       }
	//   })
	NewSession func(prompt string) error

	// GetSessionUsage returns aggregated token usage and cost statistics
	// for the current session. This includes total input/output tokens,
	// cache read/write tokens, total cost, and request count.
	//
	// Example:
	//
	//   usage := ctx.GetSessionUsage()
	//   fmt.Sprintf("Tokens: ↑%d ↓%d Cost: $%.3f",
	//       usage.TotalInputTokens, usage.TotalOutputTokens, usage.TotalCost)
	GetSessionUsage func() SessionUsage

	// SetWidget places or updates a persistent widget in the TUI. Widgets
	// remain visible across agent turns until explicitly removed. The
	// widget is identified by WidgetConfig.ID; calling SetWidget with the
	// same ID replaces the previous content.
	//
	// Example:
	//
	//   ctx.SetWidget(ext.WidgetConfig{
	//       ID:        "my-status",
	//       Placement: ext.WidgetAbove,
	//       Content:   ext.WidgetContent{Text: "Build: passing"},
	//       Style:     ext.WidgetStyle{BorderColor: "#a6e3a1"},
	//   })
	SetWidget func(WidgetConfig)

	// RemoveWidget removes a previously placed widget by its ID. No-op if
	// the ID does not exist.
	RemoveWidget func(id string)

	// SetHeader places a custom header at the top of the TUI view, above
	// the stream region. Only one header can be active at a time; calling
	// SetHeader replaces any previous header. The header persists across
	// agent turns until explicitly removed.
	//
	// Example:
	//
	//   ctx.SetHeader(ext.HeaderFooterConfig{
	//       Content: ext.WidgetContent{Text: "Project: my-app | Branch: master"},
	//       Style:   ext.WidgetStyle{BorderColor: "#89b4fa"},
	//   })
	SetHeader func(HeaderFooterConfig)

	// RemoveHeader removes the custom header. No-op if no header is set.
	RemoveHeader func()

	// SetFooter places a custom footer at the bottom of the TUI view,
	// below the status bar. Only one footer can be active at a time;
	// calling SetFooter replaces any previous footer. The footer persists
	// across agent turns until explicitly removed.
	//
	// Example:
	//
	//   ctx.SetFooter(ext.HeaderFooterConfig{
	//       Content: ext.WidgetContent{Text: "Ready | 3 tasks remaining"},
	//       Style:   ext.WidgetStyle{BorderColor: "#a6e3a1"},
	//   })
	SetFooter func(HeaderFooterConfig)

	// RemoveFooter removes the custom footer. No-op if no footer is set.
	RemoveFooter func()

	// PromptSelect shows a selection list to the user and blocks until
	// they pick an option or cancel (ESC). Returns a cancelled result in
	// non-interactive mode. Safe to call from event handlers and slash
	// command handlers.
	//
	// Example:
	//
	//   result := ctx.PromptSelect(ext.PromptSelectConfig{
	//       Message: "Choose a deployment target:",
	//       Options: []string{"staging", "production", "local"},
	//   })
	//   if !result.Cancelled {
	//       fmt.Println("Selected:", result.Value)
	//   }
	PromptSelect func(PromptSelectConfig) PromptSelectResult

	// PromptConfirm shows a yes/no confirmation to the user and blocks
	// until they respond or cancel. Returns a cancelled result in
	// non-interactive mode.
	//
	// Example:
	//
	//   result := ctx.PromptConfirm(ext.PromptConfirmConfig{
	//       Message:      "Deploy to production?",
	//       DefaultValue: false,
	//   })
	//   if !result.Cancelled && result.Value {
	//       // proceed with deployment
	//   }
	PromptConfirm func(PromptConfirmConfig) PromptConfirmResult

	// PromptInput shows a text input field to the user and blocks until
	// they submit text or cancel. Returns a cancelled result in
	// non-interactive mode.
	//
	// Example:
	//
	//   result := ctx.PromptInput(ext.PromptInputConfig{
	//       Message:     "Enter the release tag:",
	//       Placeholder: "v1.0.0",
	//   })
	//   if !result.Cancelled {
	//       fmt.Println("Tag:", result.Value)
	//   }
	PromptInput func(PromptInputConfig) PromptInputResult

	// PromptMultiSelect shows a multi-selection list to the user, allowing
	// them to toggle options with spacebar and confirm with enter. In
	// non-interactive mode, returns all options as selected.
	//
	// Example:
	//
	//   result := ctx.PromptMultiSelect(ext.PromptMultiSelectConfig{
	//       Message: "Select extensions to install:",
	//       Options: []string{"git", "todo", "weather"},
	//       DefaultSelected: []int{0, 1, 2},  // All selected by default
	//   })
	//   if !result.Cancelled {
	//       fmt.Println("Selected:", result.Values)
	//   }
	PromptMultiSelect func(PromptMultiSelectConfig) PromptMultiSelectResult

	// ShowOverlay displays a modal overlay dialog that blocks until the
	// user dismisses it or selects an action. The overlay renders as a
	// centered (or anchored) bordered box over the TUI. Returns a
	// cancelled result in non-interactive mode.
	//
	// Example:
	//
	//   result := ctx.ShowOverlay(ext.OverlayConfig{
	//       Title:   "Deployment Summary",
	//       Content: ext.WidgetContent{Text: "All 3 services deployed."},
	//       Style:   ext.OverlayStyle{BorderColor: "#a6e3a1"},
	//       Actions: []string{"Continue", "Rollback", "Details"},
	//   })
	//   if !result.Cancelled {
	//       fmt.Println("Selected:", result.Action)
	//   }
	ShowOverlay func(OverlayConfig) OverlayResult

	// SetEditor installs an editor interceptor that wraps the built-in
	// input editor. The interceptor can intercept keys (remap, consume,
	// submit) and modify the rendered output. Only one interceptor is
	// active at a time; calling SetEditor replaces any previous interceptor.
	//
	// Example — vim-like normal mode:
	//
	//   ctx.SetEditor(ext.EditorConfig{
	//       HandleKey: func(key, text string) ext.EditorKeyAction {
	//           switch key {
	//           case "h":
	//               return ext.EditorKeyAction{Type: ext.EditorKeyRemap, RemappedKey: "left"}
	//           case "i":
	//               ctx.ResetEditor()
	//               return ext.EditorKeyAction{Type: ext.EditorKeyConsumed}
	//           }
	//           return ext.EditorKeyAction{Type: ext.EditorKeyPassthrough}
	//       },
	//       Render: func(width int, content string) string {
	//           return "[NORMAL]\n" + content
	//       },
	//   })
	SetEditor func(EditorConfig)

	// ResetEditor removes the active editor interceptor and restores the
	// default built-in editor behavior. No-op if no interceptor is set.
	ResetEditor func()

	// SetUIVisibility controls which built-in TUI chrome elements are
	// visible. By default all elements are shown (zero value = show all).
	// Call this during OnSessionStart to configure the initial layout.
	//
	// Example — minimal chrome:
	//
	//   ctx.SetUIVisibility(ext.UIVisibility{
	//       HideStartupMessage: true,
	//       HideStatusBar:      true,
	//       HideSeparator:      true,
	//       HideInputHint:      true,
	//   })
	SetUIVisibility func(UIVisibility)

	// GetContextStats returns current context-window usage information
	// (estimated tokens, context limit, usage percentage, message count).
	// Useful for building context meters, auto-compaction triggers, etc.
	//
	// Example:
	//
	//   stats := ctx.GetContextStats()
	//   pct := int(stats.UsagePercent * 100)
	//   fmt.Sprintf("[%s%s] %d%%", strings.Repeat("#", pct/10), strings.Repeat("-", 10-pct/10), pct)
	GetContextStats func() ContextStats

	// GetMessages returns the conversation messages on the current branch,
	// ordered from root to leaf. This is a read-only view; extensions
	// cannot modify messages directly.
	//
	// Example:
	//
	//   msgs := ctx.GetMessages()
	//   for _, m := range msgs {
	//       if m.Role == "assistant" {
	//           lastResponse = m.Content
	//       }
	//   }
	GetMessages func() []SessionMessage

	// GetSessionPath returns the file path of the current session's JSONL
	// file. Returns empty string for in-memory (ephemeral) sessions.
	GetSessionPath func() string

	// AppendEntry persists custom extension data in the session tree.
	// The data survives across session restarts and can be retrieved via
	// GetEntries. Use entryType to namespace your data (e.g. "myext:state").
	//
	// AppendEntry is append-only and lives in the conversation tree, which
	// makes it the right tool for audit logs and event histories. For
	// last-write-wins snapshot state — "what's the current value of X?" —
	// prefer SetState / GetState instead. Those primitives store data in a
	// sidecar file outside the conversation tree, are O(1) to read/write,
	// and do not bloat branch reads or duplicate on fork.
	//
	// Example:
	//
	//   data, _ := json.Marshal(myState)
	//   ctx.AppendEntry("myext:state", string(data))
	AppendEntry func(entryType string, data string) (string, error)

	// GetEntries retrieves all persisted extension data entries matching
	// the given type on the current branch, ordered root to leaf. Pass
	// empty string to retrieve all extension data entries.
	//
	// Example — restore state on session resume:
	//
	//   entries := ctx.GetEntries("myext:state")
	//   if len(entries) > 0 {
	//       last := entries[len(entries)-1]
	//       json.Unmarshal([]byte(last.Data), &myState)
	//   }
	GetEntries func(entryType string) []ExtensionEntry

	// SetState stores a key-value pair in session-scoped, last-write-wins
	// extension state. Unlike AppendEntry the value is kept in a sidecar
	// file outside the conversation tree, so:
	//   - reads are O(1) (no branch walk)
	//   - writes don't bloat the session JSONL
	//   - state is not duplicated on fork (branches share the sidecar)
	//   - state is invisible to the LLM
	//
	// Use SetState for snapshot state ("current value of X"); use
	// AppendEntry for audit logs and event histories. Namespace keys with
	// your extension name to avoid collisions (e.g. "myext:budget-cap").
	//
	// State persists for the lifetime of the session. For ephemeral or
	// in-memory sessions the state lives only in memory.
	//
	// Example:
	//
	//   ctx.SetState("myext:budget-cap", "10.00")
	SetState func(key string, value string)

	// GetState returns the value previously stored via SetState. The bool
	// is false when the key was never written. Returns ("", false) when
	// state is unavailable.
	//
	// Example:
	//
	//   if cap, ok := ctx.GetState("myext:budget-cap"); ok {
	//       fmt.Println("current cap:", cap)
	//   }
	GetState func(key string) (string, bool)

	// DeleteState removes a key from session-scoped extension state.
	// No-op when the key is missing.
	DeleteState func(key string)

	// ListState returns all keys currently stored in session-scoped
	// extension state, in unspecified order.
	ListState func() []string

	// SetEditorText sets the text content of the input editor. This can
	// be used to pre-fill the editor with suggested text (e.g. extracted
	// questions, handoff prompts). The cursor is moved to the end.
	//
	// Example:
	//
	//   ctx.SetEditorText("Please review the changes in src/main.go")
	SetEditorText func(text string)

	// SetStatus places or updates a keyed entry in the TUI status bar.
	// Multiple entries from different extensions coexist; each is identified
	// by a unique key. Lower priority values render further left.
	//
	// Example:
	//
	//   ctx.SetStatus("myext:branch", "master", 50)
	SetStatus func(key string, text string, priority int)

	// RemoveStatus removes a keyed status bar entry. No-op if the key
	// does not exist.
	RemoveStatus func(key string)

	// GetOption returns the value of a named extension option. Options are
	// resolved in priority order:
	//   1. Runtime override (via SetOption)
	//   2. Environment variable: KIT_OPT_<NAME> (uppercase, dashes → underscores)
	//   3. Config file: options.<name> in .kit.yml
	//   4. Default value registered by the extension
	//
	// Returns empty string if the option was not registered.
	//
	// Example:
	//
	//   preset := ctx.GetOption("preset")
	//   if preset == "fast" {
	//       ctx.SetModel("anthropic/claude-haiku-3-5-20241022")
	//   }
	GetOption func(name string) string

	// SetOption sets a runtime override for a named extension option. This
	// takes highest priority over env vars, config, and defaults. Useful for
	// persisting user choices during a session.
	SetOption func(name string, value string)

	// SetModel changes the active LLM model at runtime. The model string
	// should be in "provider/model" format (e.g. "anthropic/claude-sonnet-4-5-20250929").
	// Existing tools, system prompt, and session are preserved. Returns an
	// error if the model string is invalid or the provider cannot be created.
	//
	// Example:
	//
	//   err := ctx.SetModel("openai/gpt-4o")
	//   if err != nil {
	//       ctx.PrintError("Failed to switch model: " + err.Error())
	//   }
	SetModel func(modelString string) error

	// GetAvailableModels returns a list of known models from the registry.
	// This is an advisory list — models not in the registry can still be
	// used by specifying their provider/model string directly.
	//
	// Example:
	//
	//   models := ctx.GetAvailableModels()
	//   for _, m := range models {
	//       fmt.Printf("%s/%s (ctx: %dk)\n", m.Provider, m.ModelID, m.ContextLimit/1000)
	//   }
	GetAvailableModels func() []ModelInfoEntry

	// EmitCustomEvent publishes a named event that other extensions can
	// subscribe to via api.OnCustomEvent(). Data is an arbitrary string
	// (JSON-encode complex payloads). Handlers run synchronously in
	// registration order.
	//
	// Example:
	//
	//   ctx.EmitCustomEvent("plan-mode:toggled", `{"active":true}`)
	EmitCustomEvent func(name string, data string)

	// GetAllTools returns information about all tools available to the agent,
	// including core tools (shell, read, write, etc.), MCP server tools, and
	// extension-registered tools. Each entry includes the tool's enabled status.
	//
	// Example — list read-only tools:
	//
	//   for _, t := range ctx.GetAllTools() {
	//       if t.Source == "core" && t.Enabled {
	//           fmt.Println(t.Name, "-", t.Description)
	//       }
	//   }
	GetAllTools func() []ToolInfo

	// SetActiveTools restricts the agent to only the named tools. Tools not
	// in the list are blocked from execution (the LLM receives an error if
	// it tries to call them). Pass nil or an empty slice to re-enable all
	// tools. Tool names are case-sensitive.
	//
	// Example — plan mode (read-only):
	//
	//   ctx.SetActiveTools([]string{"Read", "Glob", "Grep", "LS"})
	SetActiveTools func(names []string)

	// Exit triggers a graceful application shutdown. In interactive mode
	// this sends a quit signal to the TUI; in non-interactive mode it
	// cancels the current operation. Safe to call from any goroutine.
	//
	// Example:
	//
	//   api.RegisterCommand(ext.CommandDef{
	//       Name:        "quit",
	//       Description: "Exit the application",
	//       Execute: func(args string, ctx ext.Context) (string, error) {
	//           ctx.Exit()
	//           return "", nil
	//       },
	//   })
	Exit func()

	// Complete makes a standalone LLM completion call, bypassing the agent
	// tool loop. Use this for summarisation, question extraction, or any
	// sub-task that needs an LLM response without tool access.
	//
	// If Model is empty the current session model is reused (no extra
	// provider creation overhead). Specify a different model string to
	// use a cheaper/faster model for the sub-task.
	//
	// Example — summarise with a fast model:
	//
	//   resp, err := ctx.Complete(ext.CompleteRequest{
	//       Model:  "anthropic/claude-haiku-3-5-20241022",
	//       System: "You are a concise summarisation assistant.",
	//       Prompt: "Summarise this conversation:\n" + text,
	//   })
	//   if err != nil {
	//       ctx.PrintError("completion failed: " + err.Error())
	//       return
	//   }
	//   ctx.PrintInfo(resp.Text)
	//
	// Example — streaming completion:
	//
	//   resp, err := ctx.Complete(ext.CompleteRequest{
	//       Prompt: "Explain quantum computing",
	//       OnChunk: func(chunk string) {
	//           fmt.Print(chunk) // stream to stdout
	//       },
	//   })
	Complete func(CompleteRequest) (CompleteResponse, error)

	// SuspendTUI temporarily releases the terminal from the TUI, runs the
	// provided callback (which may spawn interactive processes like vim or
	// htop), and then restores the TUI. In non-interactive mode the
	// callback runs directly with no terminal changes.
	//
	// The callback has full access to stdin/stdout/stderr while the TUI is
	// suspended. Return from the callback to restore the TUI.
	//
	// Example — launch $EDITOR:
	//
	//   err := ctx.SuspendTUI(func() {
	//       editor := os.Getenv("EDITOR")
	//       if editor == "" { editor = "vim" }
	//       cmd := exec.Command(editor, "file.go")
	//       cmd.Stdin = os.Stdin
	//       cmd.Stdout = os.Stdout
	//       cmd.Stderr = os.Stderr
	//       cmd.Run()
	//   })
	SuspendTUI func(callback func()) error

	// RenderMessage outputs text using a named message renderer registered
	// by an extension via api.RegisterMessageRenderer(). If no renderer
	// with the given name exists, the content is printed as plain text.
	//
	// This allows extensions to define reusable visual styles (borders,
	// colors, formatting) for specific message categories and invoke them
	// by name at runtime.
	//
	// Example:
	//
	//   ctx.RenderMessage("build-status", "All 42 tests passed.")
	RenderMessage func(rendererName string, content string)

	// RegisterTheme adds a named theme to the runtime theme registry.
	// If a theme with the same name already exists it is replaced.
	// The theme becomes available via /theme and ctx.SetTheme().
	//
	// Example:
	//
	//   ctx.RegisterTheme("neon", ext.ThemeColorConfig{
	//       Primary:   ext.ThemeColor{Dark: "#FF00FF"},
	//       Secondary: ext.ThemeColor{Dark: "#00FFFF"},
	//       Success:   ext.ThemeColor{Dark: "#00FF00"},
	//       Warning:   ext.ThemeColor{Dark: "#FFFF00"},
	//       Error:     ext.ThemeColor{Dark: "#FF0000"},
	//       Info:      ext.ThemeColor{Dark: "#00FFFF"},
	//       Text:      ext.ThemeColor{Dark: "#FFFFFF"},
	//       Background: ext.ThemeColor{Dark: "#000000"},
	//   })
	RegisterTheme func(name string, config ThemeColorConfig)

	// SetTheme switches the active color theme by name. The name must
	// match a built-in theme, a user/project theme file, or a theme
	// registered via RegisterTheme. Returns an error if not found.
	//
	// Example:
	//
	//   err := ctx.SetTheme("neon")
	SetTheme func(name string) error

	// ListThemes returns the names of all available themes.
	ListThemes func() []string

	// GetTheme returns the colors of the currently active theme, already
	// resolved for the terminal's light/dark appearance and formatted as
	// "#rrggbb" hex strings.
	//
	// Use it to draw widget content that follows the user's theme instead of
	// hardcoding a palette. Pair it with ThemeColors.ANSI to emit escape
	// sequences:
	//
	//	theme := ctx.GetTheme()
	//	line := theme.ANSI(theme.Accent, "selected")
	//
	// Call it inside the render path rather than caching the result, so a
	// theme switch is picked up on the next frame.
	GetTheme func() ThemeColors

	// ReloadExtensions hot-reloads all extensions from disk. Existing
	// extensions receive a SessionShutdown event, then new code is loaded
	// and receives a SessionStart event. Event handlers, commands,
	// renderers, and shortcuts update immediately; extension-defined tools
	// are NOT updated (they are baked into the agent at creation time).
	//
	// After calling ReloadExtensions the calling extension's code has been
	// replaced; the caller should return promptly.
	//
	// Example:
	//
	//   api.RegisterCommand(ext.CommandDef{
	//       Name: "reload",
	//       Description: "Hot-reload all extensions",
	//       Execute: func(args string, ctx ext.Context) (string, error) {
	//           if err := ctx.ReloadExtensions(); err != nil {
	//               return "", err
	//           }
	//           return "Extensions reloaded", nil
	//       },
	//   })
	ReloadExtensions func() error

	// SpawnSubagent spawns an in-process child Kit instance to perform a
	// task autonomously. The subagent gets its own session, event bus, and
	// agent loop but shares the parent's provider configuration (API keys,
	// model settings). It inherits the parent's active tools minus the
	// subagent tool (no recursion) and does not load extensions. The
	// child's session is persisted by default so it can be inspected or
	// replayed; set config.NoSession for ephemeral runs.
	//
	// When config.Blocking is true, blocks until completion and returns the
	// result directly (handle is nil). When false (default), the subagent
	// runs in a background goroutine and SpawnSubagent returns immediately
	// with a non-nil handle (result is nil); OnComplete and OnEvent fire
	// asynchronously.
	//
	// Example — blocking call:
	//
	//   _, result, err := ctx.SpawnSubagent(ext.SubagentConfig{
	//       Prompt:   "Research authentication patterns in this codebase",
	//       Blocking: true,
	//       Timeout:  2 * time.Minute,
	//   })
	//   if err != nil {
	//       ctx.PrintError("spawn failed: " + err.Error())
	//       return
	//   }
	//   ctx.PrintInfo("Subagent result:\n" + result.Response)
	//
	// Example — background spawn with callbacks:
	//
	//   handle, _, _ := ctx.SpawnSubagent(ext.SubagentConfig{
	//       Prompt: "Write unit tests for UserService",
	//       OnOutput: func(chunk string) {
	//           // Live assistant text streaming
	//       },
	//       OnComplete: func(result ext.SubagentResult) {
	//           ctx.SendMessage("Subagent finished:\n" + result.Response)
	//       },
	//   })
	//   // handle.Kill() to cancel, handle.Wait() to block, handle.Done() to select
	SpawnSubagent func(SubagentConfig) (*SubagentHandle, *SubagentResult, error)

	// GetTreeNode returns a node by ID with full metadata and children.
	// Returns nil if entry not found.
	GetTreeNode func(entryID string) *TreeNode

	// GetCurrentBranch returns the path from root to current leaf.
	// Each node contains full metadata (unlike GetMessages which flattens).
	GetCurrentBranch func() []TreeNode

	// GetChildren returns direct child IDs of an entry.
	GetChildren func(entryID string) []string

	// NavigateTo branches/forks the session to the specified entry ID.
	// Equivalent to SDK's Branch() but for extensions.
	NavigateTo func(entryID string) TreeNavigationResult

	// SummarizeBranch uses LLM to summarize a branch range.
	// Returns summary text or error string (empty if success).
	SummarizeBranch func(fromID, toID string) string

	// CollapseBranch replaces a branch range with a summary entry.
	// This is the "fresh context" primitive for context window management.
	CollapseBranch func(fromID, toID, summary string) TreeNavigationResult

	// LoadSkill loads a single skill file from path.
	// Parses YAML frontmatter, returns skill with content ready for injection.
	LoadSkill func(path string) (*Skill, string)

	// LoadSkillsFromDir discovers and loads all skills from a directory.
	LoadSkillsFromDir func(dir string) SkillLoadResult

	// DiscoverSkills finds skills in standard locations.
	// Checks ~/.agents/skills/, ~/.config/kit/skills/, <project>/.agents/skills/,
	// and <project>/.kit/skills/.
	DiscoverSkills func() SkillLoadResult

	// InjectSkillAsContext sends a skill's content as a system message.
	// Looks up skill by name from discovered skills.
	InjectSkillAsContext func(skillName string) string

	// InjectRawSkillAsContext loads and immediately injects a skill file.
	InjectRawSkillAsContext func(path string) string

	// GetAvailableSkills returns all currently loaded/discovered skills.
	GetAvailableSkills func() []Skill

	// ParseTemplate extracts {{variables}} from template content.
	ParseTemplate func(name, content string) PromptTemplate

	// RenderTemplate substitutes variables into template content.
	RenderTemplate func(tpl PromptTemplate, vars map[string]string) string

	// ParseArguments parses command-line style arguments.
	ParseArguments func(input string, pattern ArgumentPattern) ParseResult

	// SimpleParseArguments parses $1, $2, $@ style arguments.
	// Returns slice where [0]=full input, [1]=$1, [2]=$2, ... [n]=$@
	SimpleParseArguments func(input string, count int) []string

	// EvaluateModelConditional checks if condition matches current model.
	// Condition supports wildcards: * matches any, ? matches single char.
	EvaluateModelConditional func(condition string) bool

	// RenderWithModelConditionals processes <if-model> blocks in content.
	RenderWithModelConditionals func(content string) string

	// ResolveModelChain attempts each model in order until one is available.
	ResolveModelChain func(preferences []string) ModelResolutionResult

	// GetModelCapabilities returns capabilities for a specific model,
	// including its context/output limits and token pricing. Pass an empty
	// string for the model currently in use. The second return value is an
	// error message, empty on success.
	GetModelCapabilities func(model string) (ModelCapabilities, string)

	// CheckModelAvailable verifies if a model string is valid.
	CheckModelAvailable func(model string) bool

	// GetCurrentProvider returns just the provider part of current model.
	GetCurrentProvider func() string

	// GetCurrentModelID returns just the model ID part of current model.
	GetCurrentModelID func() string

	// GetTerminalSize returns the current terminal width and height in columns
	// and rows. Both are 0 outside the interactive TUI (headless, ACP, script
	// mode), so guard before dividing or subtracting.
	//
	// Content passed to SetFooter, SetHeader and SetWidget is rendered at full
	// terminal width with no truncation: a wider line wraps and silently
	// consumes an extra row of scrollback. Measure with this before handing
	// text to those calls.
	//
	// This is a function, not a field, so that it reports the live size. A
	// long-lived goroutine that captured a Context still observes resizes,
	// whereas a struct field would freeze at the value copied when the
	// handler was invoked.
	GetTerminalSize func() (int, int)

	// GetThinkingLevel returns the active extended-thinking effort level:
	// "off", "none", "minimal", "low", "medium", or "high". Models that do
	// not support reasoning report "off".
	//
	// Pair with GetModelCapabilities("").Reasoning to tell "reasoning is
	// switched off" apart from "this model cannot reason at all".
	GetThinkingLevel func() string
}

Context provides runtime information to handlers about the current session.

type ContextMessage added in v0.3.0

type ContextMessage struct {
	// Index is the position of this message in the original context array
	// (0-based). When returning messages from a ContextPrepareResult,
	// messages with Index >= 0 reuse the original LLM message at that
	// position (preserving tool calls, reasoning, and other complex parts).
	// Set Index to -1 for newly injected messages (created from Role + Content).
	Index int

	// Role is the message role: "user", "assistant", "system", or "tool".
	Role string

	// Content is the text content of the message. For assistant messages
	// with tool calls, this includes a text summary of the calls.
	Content string
}

ContextMessage represents a single message in the LLM context window. Used by OnContextPrepare to let extensions inspect and modify the messages that will be sent to the LLM.

type ContextPrepareEvent added in v0.3.0

type ContextPrepareEvent struct {
	// Messages is the current context window that will be sent to the LLM.
	// Each ContextMessage includes an Index field that maps back to the
	// position in the original message array (for identity-preserving edits).
	Messages []ContextMessage
}

ContextPrepareEvent fires after the context window is built from the session tree and before the messages are sent to the LLM. Handlers can inspect the messages and return a modified set to filter, reorder, or inject context.

func (ContextPrepareEvent) Type added in v0.3.0

func (e ContextPrepareEvent) Type() EventType

type ContextPrepareResult added in v0.3.0

type ContextPrepareResult struct {
	// Messages replaces the entire context window. Each entry with a
	// non-negative Index reuses the original message at that position
	// (preserving tool calls, reasoning, etc.); entries with Index < 0
	// are created fresh from Role + Content.
	Messages []ContextMessage
}

ContextPrepareResult allows extensions to replace the context window. Return nil to leave the context unchanged.

type ContextStats added in v0.3.0

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-window usage information. Extensions can poll this via ctx.GetContextStats() to build usage meters, auto-compaction triggers, etc.

type EditorConfig added in v0.2.0

type EditorConfig struct {
	// HandleKey intercepts key presses before they reach the built-in editor.
	// It receives the key name (e.g., "a", "enter", "alt+p", "backspace")
	// and the editor's current text content. Return an EditorKeyAction to
	// control how the key is handled.
	//
	// Unlike RegisterShortcut handlers, this is called synchronously on the
	// TUI event loop: a blocking call here freezes the whole interface. Keep
	// it fast, and dispatch slow work to a goroutine.
	//
	// The interceptor is the last hook before the editor, so it never sees
	// keys an earlier stage consumed — among them "ctrl+c", any registered
	// extension shortcut, "esc" while a turn is running, "ctrl+x" and its
	// chord suffix, and the scrollback bindings such as "pgup".
	//
	// If nil, all keys pass through to the built-in editor unchanged.
	HandleKey func(key string, currentText string) EditorKeyAction

	// Render wraps the built-in editor's rendered output. It receives the
	// available width and the default-rendered content (including title,
	// textarea, popup, and help text). Return the modified content to display.
	//
	// If nil, the default rendering is used unchanged.
	Render func(width int, defaultContent string) string
}

EditorConfig defines an editor interceptor/decorator that wraps the built-in input editor. Extensions can intercept key events (remap, consume, or force submit) and/or modify the rendered output (add mode indicators, apply visual effects).

Uses concrete function fields instead of interfaces for Yaegi safety.

IMPORTANT (Yaegi limitation — forward references lose their bodies): If you reference a function BY NAME from inside a function literal, and that function is declared LATER in the file, Yaegi builds the wrapper before the function is compiled. The field then holds a callable that does nothing and returns zero values — no panic, no error. This affects every Kit API taking a function, and also direct arguments such as api.OnToolCall(fn) and api.RegisterShortcut(def, fn).

// BROKEN — myHandler is declared below this closure:
api.OnAgentStart(func(e ext.AgentStartEvent, ctx ext.Context) {
    ctx.SetEditor(ext.EditorConfig{HandleKey: myHandler})
})
func myHandler(k, t string) ext.EditorKeyAction { ... }

Any one of these fixes it:

  1. Declare helpers ABOVE the code that references them (simplest).
  2. Wrap in an anonymous closure: HandleKey: func(k string, t string) ext.EditorKeyAction { return myHandler(k, t) }
  3. Assign to a local first: f := myHandler; ...{HandleKey: f}

Verified against yaegi v0.12.0-v0.16.1; not fixed upstream.

type EditorKeyAction added in v0.2.0

type EditorKeyAction struct {
	// Type determines the action taken.
	Type EditorKeyActionType

	// RemappedKey is the target key name for EditorKeyRemap. Must be a
	// recognized key name (e.g., "left", "right", "up", "down", "backspace",
	// "delete", "enter", "tab", "home", "end", "esc", "space", or a single
	// printable character).
	RemappedKey string

	// SubmitText is the text to submit for EditorKeySubmit. If empty, the
	// editor's current content is submitted instead.
	SubmitText string
}

EditorKeyAction is returned by an editor interceptor's HandleKey function to indicate how a key press should be handled.

type EditorKeyActionType added in v0.2.0

type EditorKeyActionType string

EditorKeyActionType defines the outcome of an editor key interception.

const (
	// EditorKeyPassthrough lets the built-in editor handle the key normally.
	EditorKeyPassthrough EditorKeyActionType = "passthrough"

	// EditorKeyConsumed means the extension handled the key. The editor
	// should re-render but not process the key further.
	EditorKeyConsumed EditorKeyActionType = "consumed"

	// EditorKeyRemap transforms the key into a different key before passing
	// it to the built-in editor. Use RemappedKey to specify the target
	// (e.g., "left", "right", "up", "down", "backspace", "delete", "enter",
	// "tab", "home", "end", or a single character like "a").
	EditorKeyRemap EditorKeyActionType = "remap"

	// EditorKeySubmit forces immediate text submission. The SubmitText field
	// specifies the text to submit (empty = use editor's current text).
	EditorKeySubmit EditorKeyActionType = "submit"
)

type ErrorEvent added in v0.60.0

type ErrorEvent struct {
	Error string
}

ErrorEvent fires when an agent-level error occurs during streaming. Uses string instead of error because Yaegi cannot handle the error interface reliably across the interpreter boundary.

func (ErrorEvent) Type added in v0.60.0

func (e ErrorEvent) Type() EventType

type Event

type Event interface {
	Type() EventType
}

Event is the interface satisfied by all event types internally.

type EventType

type EventType string

EventType identifies a point in KIT's lifecycle where extensions can hook in.

const (
	// ToolCall fires before a tool executes. Handlers can block execution.
	ToolCall EventType = "tool_call"

	// ToolCallInputStart fires when the LLM begins generating tool call
	// arguments. The tool name is known but the full argument JSON is still
	// being streamed.
	ToolCallInputStart EventType = "tool_call_input_start"

	// ToolCallInputDelta fires for each streamed fragment of tool call
	// arguments as they arrive from the LLM.
	ToolCallInputDelta EventType = "tool_call_input_delta"

	// ToolCallInputEnd fires when tool argument streaming is complete,
	// before the tool call is parsed and execution begins.
	ToolCallInputEnd EventType = "tool_call_input_end"

	// ToolExecutionStart fires when a tool begins executing.
	ToolExecutionStart EventType = "tool_execution_start"

	// ToolExecutionEnd fires when a tool finishes executing.
	ToolExecutionEnd EventType = "tool_execution_end"

	// ToolOutput fires when a tool produces streaming output chunks.
	ToolOutput EventType = "tool_output"

	// ToolResult fires after a tool executes. Handlers can modify the result.
	ToolResult EventType = "tool_result"

	// Input fires when user input is received. Handlers can transform or handle it.
	Input EventType = "input"

	// BeforeAgentStart fires before the agent loop begins for a prompt.
	BeforeAgentStart EventType = "before_agent_start"

	// AgentStart fires when the agent loop begins processing.
	AgentStart EventType = "agent_start"

	// AgentEnd fires when the agent finishes responding.
	AgentEnd EventType = "agent_end"

	// MessageStart fires when a new assistant message begins.
	MessageStart EventType = "message_start"

	// MessageUpdate fires for each streaming text chunk.
	MessageUpdate EventType = "message_update"

	// MessageEnd fires when the assistant message is complete.
	MessageEnd EventType = "message_end"

	// SessionStart fires when a session is loaded or created.
	SessionStart EventType = "session_start"

	// SessionShutdown fires when the application is closing.
	SessionShutdown EventType = "session_shutdown"

	// ModelChange fires after the active model is changed via ctx.SetModel().
	ModelChange EventType = "model_change"

	// ThinkingLevelChange fires after the extended-thinking effort level is
	// changed, whether by the user, an extension, or an automatic downgrade
	// when switching to a model that does not support the current level.
	ThinkingLevelChange EventType = "thinking_level_change"

	// TerminalResize fires when the terminal dimensions change, and once at
	// startup with the initial size. Interactive TUI only.
	TerminalResize EventType = "terminal_resize"

	// TurnStateChange fires when the UI moves between its idle and working
	// states. Unlike AgentStart/AgentEnd this also covers work that never
	// reaches the agent loop, such as shell commands. Interactive TUI only.
	TurnStateChange EventType = "turn_state_change"

	// ContextPrepare fires after context is built from the session tree and
	// before the messages are sent to the LLM. Handlers can filter, reorder,
	// or inject messages into the context window.
	ContextPrepare EventType = "context_prepare"

	// BeforeFork fires before the session tree is branched to a different
	// entry point. Handlers can cancel the fork by returning Cancel=true.
	BeforeFork EventType = "before_fork"

	// BeforeSessionSwitch fires before the session is switched to a new
	// branch (e.g. /new command). Handlers can cancel by returning Cancel=true.
	BeforeSessionSwitch EventType = "before_session_switch"

	// BeforeCompact fires before context compaction runs. Handlers can
	// cancel compaction by returning Cancel=true.
	BeforeCompact EventType = "before_compact"

	// SubagentStart fires when a subagent tool call begins executing.
	// Carries the tool call ID and the task description.
	SubagentStart EventType = "subagent_start"

	// SubagentChunk fires for each real-time event emitted by a running
	// subagent: text chunks, tool calls, tool results, etc.
	SubagentChunk EventType = "subagent_chunk"

	// SubagentEnd fires when a subagent tool call completes (success
	// or error). Carries the final response and any error message.
	SubagentEnd EventType = "subagent_end"

	// StepStart fires when a new LLM call begins within a multi-step
	// agent turn.
	StepStart EventType = "step_start"

	// StepFinish fires when a step completes, providing step number,
	// finish reason, and token usage.
	StepFinish EventType = "step_finish"

	// ReasoningStart fires when the LLM begins reasoning/thinking.
	ReasoningStart EventType = "reasoning_start"

	// Warnings fires when the LLM provider returns warnings.
	Warnings EventType = "warnings"

	// Source fires when the LLM references a source (e.g. web search).
	Source EventType = "source"

	// Error fires when an agent-level error occurs during streaming.
	Error EventType = "error"

	// Retry fires when the LLM provider request is retried after a
	// transient error.
	Retry EventType = "retry"

	// PrepareStep fires between steps within a multi-step agent turn,
	// after steering messages are injected and before messages are sent
	// to the LLM. Handlers can replace the context window for this step.
	PrepareStep EventType = "prepare_step"

	// LLMUsage fires after each LLM provider call with the token and cost
	// deltas for that single call. Extensions use it to attribute usage to
	// specific calls/models and to drive budget enforcement between calls.
	LLMUsage EventType = "llm_usage"
)

func AllEventTypes

func AllEventTypes() []EventType

AllEventTypes returns every supported event type.

func (EventType) IsValid

func (e EventType) IsValid() bool

IsValid returns true if the event type is a recognised lifecycle event.

type ExtensionEntry added in v0.3.0

type ExtensionEntry struct {
	// ID is the unique entry identifier.
	ID string
	// EntryType is the extension-defined type string (e.g. "plan-mode:state").
	EntryType string
	// Data is the extension-defined payload (JSON or plain text).
	Data string
	// Timestamp is the RFC3339-formatted creation time.
	Timestamp string
}

ExtensionEntry represents persisted extension data stored in the session. Extensions use AppendEntry to save custom state and GetEntries to retrieve it on session resume.

type ExtensionPreview added in v0.14.0

type ExtensionPreview struct {
	// Path is the relative path from the package root (e.g., "./git/main.go")
	Path string `json:"path"`
	// Name is a display name for the extension (derived from path or metadata)
	Name string `json:"name"`
	// Description is an optional description (could be extracted from comments)
	Description string `json:"description,omitempty"`
	// IsMain indicates if this is a main.go in a subdirectory
	IsMain bool `json:"is_main"`
}

ExtensionPreview represents a discovered extension in a package before installation.

func ScanForExtensions added in v0.14.0

func ScanForExtensions(dir string) ([]ExtensionPreview, error)

ScanForExtensions discovers all extensions in a directory using opinionated conventions. Extensions are ONLY recognized in these specific locations:

  1. Root-level *.go files
  2. Files in examples/extensions/ or examples/ext/ subdirectories
  3. Files in any top-level ext/ directory
  4. Files in any subdirectory that ends in -ext/ or -extensions/

Everything else (cmd/, internal/, pkg/, etc.) is ignored.

type FilePart added in v0.38.0

type FilePart struct {
	// Filename is the name of the file (e.g. "photo.jpg").
	Filename string
	// Data is the raw file content.
	Data []byte
	// MediaType is the MIME type (e.g. "image/jpeg", "application/pdf").
	MediaType string
}

FilePart describes a file attachment for multimodal messages. Extensions use this with SendMultimodalMessage to attach images or documents.

type GitSource added in v0.14.0

type GitSource struct {
	Repo   string // Clone URL (e.g., https://github.com/user/repo.git)
	Host   string // Host (e.g., github.com)
	Path   string // Path (e.g., user/repo)
	Ref    string // Optional ref (tag, branch, commit)
	Pinned bool   // Whether a specific ref is pinned
}

GitSource represents a parsed git repository URL.

func ParseGitSource added in v0.14.0

func ParseGitSource(source string) (*GitSource, error)

ParseGitSource parses a git source string into a GitSource. Supports formats like:

func (GitSource) Identity added in v0.14.0

func (g GitSource) Identity() string

Identity returns a normalized identity string for deduplication.

func (GitSource) String added in v0.14.0

func (g GitSource) String() string

String returns the canonical string representation.

type HandlerFunc

type HandlerFunc func(event Event, ctx Context) Result

HandlerFunc is the internal handler signature used by the runner.

type HeaderFooterConfig added in v0.2.0

type HeaderFooterConfig struct {
	// Content describes what to render.
	Content WidgetContent

	// Style configures the appearance.
	Style WidgetStyle
}

HeaderFooterConfig describes a custom header or footer region that replaces or augments the default TUI chrome. Extensions use ctx.SetHeader/SetFooter to place one; only one header and one footer can be active at a time (the latest call wins). Reuses WidgetContent and WidgetStyle for consistency.

type InputEvent

type InputEvent struct {
	Text   string
	Source string // "interactive", "cli", "script", "queue"
}

InputEvent fires when user input is received.

func (InputEvent) Type

func (e InputEvent) Type() EventType

type InputResult

type InputResult struct {
	Action string
	Text   string // replacement text when Action="transform"
}

InputResult controls what happens with user input.

Action: "continue" (default), "transform", "handled"

type InstallScope added in v0.14.0

type InstallScope string

InstallScope defines where a package should be installed.

const (
	ScopeGlobal  InstallScope = "global"
	ScopeProject InstallScope = "project"
)

type Installer added in v0.14.0

type Installer struct {
	// contains filtered or unexported fields
}

Installer handles installing, updating, and removing git-based extensions.

func NewInstaller added in v0.14.0

func NewInstaller(projectDir string) *Installer

NewInstaller creates a new Installer.

func (*Installer) Install added in v0.14.0

func (i *Installer) Install(source *GitSource, scope InstallScope) error

Install clones a git repository to the appropriate scope.

func (*Installer) InstallWithInclude added in v0.14.0

func (i *Installer) InstallWithInclude(source *GitSource, scope InstallScope, includePaths []string) error

InstallWithInclude clones a repo and installs only the specified extensions. includePaths are relative paths like "./git/main.go" - if empty, installs all.

func (*Installer) IsInstalled added in v0.14.0

func (i *Installer) IsInstalled(source *GitSource) (InstallScope, bool)

IsInstalled checks if a package is installed in either scope. Returns (scope, true) if installed, ("", false) otherwise.

func (*Installer) PreviewExtensions added in v0.14.0

func (i *Installer) PreviewExtensions(source *GitSource) ([]ExtensionPreview, string, error)

PreviewExtensions clones a repo to a temporary directory and scans for extensions. Returns the preview list and the temp directory path (caller should clean up).

func (*Installer) Uninstall added in v0.14.0

func (i *Installer) Uninstall(source *GitSource, scope InstallScope) error

Uninstall removes an installed package.

func (*Installer) Update added in v0.14.0

func (i *Installer) Update(source *GitSource, scope InstallScope) error

Update fetches and resets a git package to the latest. For pinned packages, this does nothing.

type LLMUsageEvent added in v0.75.0

type LLMUsageEvent struct {
	// InputTokens is the number of input tokens for this call.
	InputTokens int
	// OutputTokens is the number of output tokens generated by this call.
	OutputTokens int
	// CacheReadTokens is the number of cache-hit input tokens (provider-specific).
	CacheReadTokens int
	// CacheWriteTokens is the number of cache-write tokens.
	CacheWriteTokens int
	// Cost is the USD cost of this call computed from the model's per-token
	// pricing. Zero when pricing is unknown or OAuth credentials are in use.
	Cost float64
	// Model is the model identifier used for this call (e.g. "claude-sonnet-4-5-20250929").
	Model string
	// Provider is the provider identifier (e.g. "anthropic", "openai").
	Provider string
	// RequestID is an optional correlation id for the underlying provider
	// call. May be empty when the provider does not surface one.
	RequestID string
	// StepNumber is the zero-based step index within the current agent turn.
	StepNumber int
	// FinishReason mirrors the provider's finish reason for this call
	// (e.g. "stop", "tool_calls", "length"). May be empty.
	FinishReason string
}

LLMUsageEvent fires after each LLM provider call with the per-call token and cost deltas. Use this for accurate budget tracking, cost dashboards, and any logic that needs to react between LLM calls within a single agent turn (rather than only at turn boundaries).

A single agent turn typically produces multiple LLMUsageEvents (one per tool-loop iteration). The Model and Provider fields reflect the model used for that specific call, which may differ from earlier calls if the extension switched models mid-turn via ctx.SetModel().

func (LLMUsageEvent) Type added in v0.75.0

func (e LLMUsageEvent) Type() EventType

type LoadedExtension

type LoadedExtension struct {
	Path                string
	Handlers            map[EventType][]HandlerFunc
	Tools               []ToolDef
	Commands            []CommandDef
	ToolRenderers       []ToolRenderConfig
	MessageRenderers    []MessageRendererConfig   // named message renderers
	CustomEventHandlers map[string][]func(string) // inter-extension event bus
	Options             []OptionDef               // registered configuration options
	Shortcuts           []ShortcutEntry           // global keyboard shortcuts
}

LoadedExtension represents a single extension that has been discovered, loaded, and initialised. It holds the registered handlers and any custom tools, commands, or tool renderers the extension provided.

func LoadExtensions

func LoadExtensions(extraPaths []string) ([]LoadedExtension, error)

LoadExtensions discovers and loads extensions from standard locations and any extra paths. Each extension is loaded into its own Yaegi interpreter for isolation. Extensions that fail to load are logged and skipped.

func LoadExtensionsScoped added in v0.99.0

func LoadExtensionsScoped(extraPaths []string, bare bool) ([]LoadedExtension, error)

LoadExtensionsScoped is LoadExtensions with control over discovery. When bare is true no directory is scanned — system, user and project locations are all skipped — and only extraPaths load. Use it so that running Kit inside a directory does not silently execute that directory's extensions.

type Manifest added in v0.14.0

type Manifest struct {
	Packages []ManifestEntry `json:"packages"`
}

Manifest tracks installed git packages.

type ManifestEntry added in v0.14.0

type ManifestEntry struct {
	// Source is the canonical string representation (e.g., "git:github.com/user/repo@v1.0.0")
	Source string `json:"source"`
	// Repo is the clone URL
	Repo string `json:"repo"`
	// Host is the git host (e.g., github.com)
	Host string `json:"host"`
	// Path is the path on the host (e.g., user/repo)
	Path string `json:"path"`
	// Ref is the optional pinned ref (tag/branch/commit)
	Ref string `json:"ref,omitempty"`
	// Pinned indicates if the ref is pinned
	Pinned bool `json:"pinned"`
	// Scope is where the package is installed (global or project)
	Scope InstallScope `json:"scope"`
	// Installed is when the package was first installed
	Installed time.Time `json:"installed"`
	// Updated is when the package was last updated (only for unpinned, zero time means never updated)
	Updated time.Time `json:"updated,omitzero"`
	// Include is a list of relative paths to extensions that should be loaded.
	// If empty, all extensions in the package are loaded.
	// Paths are relative to the package root (e.g., "./git/main.go", "./weather.go")
	Include []string `json:"include,omitempty"`
}

ManifestEntry represents a single installed package.

func (ManifestEntry) Identity added in v0.14.0

func (e ManifestEntry) Identity() string

Identity returns the normalized identity for deduplication.

type MessageEndEvent

type MessageEndEvent struct {
	Content string
}

MessageEndEvent fires when the assistant message is complete.

func (MessageEndEvent) Type

func (e MessageEndEvent) Type() EventType

type MessageRendererConfig added in v0.3.0

type MessageRendererConfig struct {
	// Name uniquely identifies this renderer. Used by ctx.RenderMessage
	// to look it up at call time. Should be namespaced to avoid collisions
	// (e.g. "myext:build-status").
	Name string

	// Render produces the styled output string from raw content. Receives
	// the content and the terminal width in columns.
	//
	// The returned string is NOT emitted verbatim: in interactive mode Kit
	// re-wraps it to the content width and nests it inside a system message
	// block (gutter glyph plus indent), so box drawing that assumes full
	// terminal width will be wrapped a second time. Size output to roughly
	// width-4 and prefer inline styling over full-width frames. For output
	// Kit uses as-is, use a widget with a Render callback instead.
	Render func(content string, width int) string
}

MessageRendererConfig provides a named rendering function that extensions can invoke via ctx.RenderMessage(name, content). Unlike tool renderers (which hook into the automatic tool result display), message renderers are invoked explicitly by extension code for branded status updates, progress reports, or any custom visual output.

Example:

api.RegisterMessageRenderer(ext.MessageRendererConfig{
    Name: "build-status",
    Render: func(content string, width int) string {
        border := strings.Repeat("─", width-4)
        return "╭" + border + "╮\n│ " + content + "\n╰" + border + "╯"
    },
})

type MessageStartEvent

type MessageStartEvent struct{}

MessageStartEvent fires when a new assistant message begins.

func (MessageStartEvent) Type

func (e MessageStartEvent) Type() EventType

type MessageUpdateEvent

type MessageUpdateEvent struct {
	Chunk string
}

MessageUpdateEvent fires for each streaming text chunk.

func (MessageUpdateEvent) Type

func (e MessageUpdateEvent) Type() EventType

type ModelCapabilities added in v0.28.0

type ModelCapabilities struct {
	// Provider is the provider ID (e.g., "anthropic").
	Provider string
	// ModelID is the model identifier (e.g., "claude-sonnet-4-20250929").
	ModelID string
	// ContextLimit is the maximum context window in tokens.
	ContextLimit int
	// OutputLimit is the maximum output tokens.
	OutputLimit int
	// Reasoning indicates if the model supports reasoning/thinking.
	Reasoning bool
	// Streaming indicates if the model supports streaming.
	Streaming bool
	// Pricing holds the model's per-million-token costs. Pricing.Known is
	// false when the registry has no cost data for the model.
	Pricing ModelPricing
}

ModelCapabilities describes what a model supports.

type ModelChangeEvent added in v0.3.0

type ModelChangeEvent struct {
	// NewModel is the model string that was set (e.g. "anthropic/claude-sonnet-4-5-20250929").
	NewModel string
	// PreviousModel is the model string before the change.
	PreviousModel string
	// Source indicates what triggered the change: "extension" for ctx.SetModel(),
	// "user" for interactive model selection.
	Source string
}

ModelChangeEvent fires after the active model is changed via ctx.SetModel().

func (ModelChangeEvent) Type added in v0.3.0

func (e ModelChangeEvent) Type() EventType

type ModelConditional added in v0.28.0

type ModelConditional struct {
	// Condition is the model pattern (e.g., "claude-*", "anthropic/*").
	Condition string
	// Content is rendered if condition matches.
	Content string
	// Else is rendered if condition doesn't match.
	Else string
}

ModelConditional represents an <if-model> block for evaluation.

type ModelInfoEntry added in v0.3.0

type ModelInfoEntry struct {
	// Provider is the provider ID (e.g. "anthropic", "openai").
	Provider string
	// ModelID is the model identifier (e.g. "claude-sonnet-4-5-20250929").
	ModelID string
	// Name is the human-readable model name.
	Name string
	// ContextLimit is the maximum context window in tokens (0 if unknown).
	ContextLimit int
	// OutputLimit is the maximum output tokens (0 if unknown).
	OutputLimit int
	// Reasoning is true if the model supports extended thinking.
	Reasoning bool
	// Pricing holds the model's per-million-token costs. Pricing.Known is
	// false when the registry has no cost data for the model.
	Pricing ModelPricing
}

ModelInfoEntry represents a known model from the registry. Used by GetAvailableModels to let extensions discover which models are available.

type ModelPricing added in v0.91.0

type ModelPricing struct {
	// Input is the cost per million input (prompt) tokens.
	Input float64
	// Output is the cost per million output (completion) tokens.
	Output float64
	// CacheRead is the cost per million tokens read from the prompt cache.
	// Only meaningful when HasCacheRead is true.
	CacheRead float64
	// CacheWrite is the cost per million tokens written to the prompt cache.
	// Only meaningful when HasCacheWrite is true.
	CacheWrite float64
	// HasCacheRead is true when the model publishes a cache-read rate.
	// When false, the provider either does not support prompt caching or the
	// registry has no rate for it — do not assume CacheRead is 0.
	HasCacheRead bool
	// HasCacheWrite is true when the model publishes a cache-write rate.
	HasCacheWrite bool
	// Known is true when the registry supplied pricing for this model. When
	// false every other field is zero and costs cannot be computed; this is
	// normal for local models and custom OpenAI-compatible endpoints.
	Known bool
}

ModelPricing describes a model's token costs, expressed in US dollars per one million tokens (the unit used by the models.dev registry). Extensions use it to compute costs or savings that Kit does not report directly — for example the value of prompt-cache reads:

caps, _ := ctx.GetModelCapabilities("")
usage := ctx.GetSessionUsage()
if caps.Pricing.Known && caps.Pricing.HasCacheRead {
    saved := float64(usage.TotalCacheReadTokens) *
        (caps.Pricing.Input - caps.Pricing.CacheRead) / 1_000_000
}

Costs for a raw token count are therefore tokens * rate / 1_000_000.

type ModelResolutionResult added in v0.28.0

type ModelResolutionResult struct {
	// Model is the selected model in "provider/model" format.
	Model string
	// Capabilities describes the selected model.
	Capabilities ModelCapabilities
	// Attempted lists models tried before success.
	Attempted []string
	// Error describes resolution failures (empty if success).
	Error string
}

ModelResolutionResult reports model chain resolution outcome.

type OptionDef added in v0.3.0

type OptionDef struct {
	// Name is the option identifier. Used as:
	//   - Env var: KIT_OPT_<NAME> (uppercased, dashes → underscores)
	//   - Config key: options.<name> in .kit.yml
	Name string
	// Description explains what the option controls.
	Description string
	// Default is the fallback value if not set via env or config.
	Default string
}

OptionDef describes a configuration option that an extension can register. Options are resolved from env vars, config file, or default value.

type OverlayAnchor added in v0.2.0

type OverlayAnchor string

OverlayAnchor determines the vertical position of an overlay dialog within the TUI view.

const (
	// OverlayCenter positions the dialog in the vertical center.
	OverlayCenter OverlayAnchor = "center"

	// OverlayTopCenter positions the dialog near the top of the view.
	OverlayTopCenter OverlayAnchor = "top-center"

	// OverlayBottomCenter positions the dialog near the bottom of the view.
	OverlayBottomCenter OverlayAnchor = "bottom-center"
)

type OverlayConfig added in v0.2.0

type OverlayConfig struct {
	// Title is displayed at the top of the dialog. Empty means no title.
	Title string

	// Content describes what to render inside the dialog body. The Text
	// field is required; set Markdown=true to render as styled markdown.
	Content WidgetContent

	// Style configures the appearance.
	Style OverlayStyle

	// Width is the dialog width in columns. 0 = 60% of terminal width.
	// Clamped to [30, termWidth-4].
	Width int

	// MaxHeight limits the dialog height in lines. 0 = 80% of terminal
	// height. Content exceeding this height becomes scrollable.
	MaxHeight int

	// Anchor determines vertical positioning. Default is "center".
	Anchor OverlayAnchor

	// Actions, if non-empty, shows selectable action buttons at the
	// bottom of the dialog. The user navigates with left/right arrows
	// and selects with Enter. The selected action's text and index are
	// returned in OverlayResult.
	//
	// If empty, the dialog is a simple info panel dismissed with ESC
	// or Enter (result.Cancelled=false, result.Action="", result.Index=-1).
	Actions []string
}

OverlayConfig fully describes a modal overlay dialog. Extensions call ctx.ShowOverlay(config) to display the dialog and block until the user dismisses it or selects an action. The dialog renders as a bordered box positioned within the TUI, with optional scrollable content and action buttons.

Example:

result := ctx.ShowOverlay(ext.OverlayConfig{
    Title:   "Build Results",
    Content: ext.WidgetContent{Text: "All 42 tests passed."},
    Style:   ext.OverlayStyle{BorderColor: "#a6e3a1"},
    Width:   60,
    Actions: []string{"Continue", "Show Details"},
})

type OverlayResult added in v0.2.0

type OverlayResult struct {
	// Action is the text of the selected action, or "" if no actions
	// were configured or the dialog was dismissed without selection.
	Action string

	// Index is the zero-based index of the selected action, or -1 if
	// no action was selected.
	Index int

	// Cancelled is true if the user dismissed the dialog with ESC.
	Cancelled bool
}

OverlayResult is the response from a ShowOverlay call.

type OverlayStyle added in v0.2.0

type OverlayStyle struct {
	// BorderColor is a hex color (e.g. "#89b4fa") for the dialog border.
	// Empty uses a default blue accent.
	BorderColor string

	// Background is a hex color (e.g. "#1e1e2e") for the dialog background.
	// Empty means no explicit background (inherits terminal default).
	Background string
}

OverlayStyle configures the visual appearance of an overlay dialog.

type ParseResult added in v0.28.0

type ParseResult struct {
	// Vars maps variable names to values for positional args.
	Vars map[string]string
	// Flags maps flag names to values.
	Flags map[string]string
	// Rest is remaining unparsed text.
	Rest string
	// Error describes parsing failures (empty if success).
	Error string
}

ParseResult reports argument parsing outcome.

type PrepareStepEvent added in v0.60.0

type PrepareStepEvent struct {
	// StepNumber is the zero-based step index within the current turn.
	StepNumber int
	// Messages is the current context window that will be sent to the LLM.
	Messages []ContextMessage
}

PrepareStepEvent fires between steps within a multi-step agent turn, after steering messages are injected and before messages are sent to the LLM. Handlers can inspect and replace the context window.

func (PrepareStepEvent) Type added in v0.60.0

func (e PrepareStepEvent) Type() EventType

type PrepareStepResult added in v0.60.0

type PrepareStepResult struct {
	// Messages replaces the entire context window for this step. If nil,
	// the original messages are used unchanged. Messages with a non-negative
	// Index reuse the original message at that position; messages with
	// Index < 0 are created fresh from Role + Content.
	Messages []ContextMessage
}

PrepareStepResult allows extensions to replace the context window between steps. Return nil Messages to leave the context unchanged.

type PrintBlockOpts

type PrintBlockOpts struct {
	// Text is the main content to display.
	Text string
	// BorderColor is a hex color string (e.g. "#a6e3a1") for the left border.
	// Defaults to the theme's system color if empty.
	BorderColor string
	// Subtitle is optional text shown below the content in muted style
	// (e.g. extension name, timestamp). Empty means no subtitle line.
	Subtitle string
}

PrintBlockOpts configures a custom styled block for PrintBlock.

type PromptConfirmConfig added in v0.2.0

type PromptConfirmConfig struct {
	// Message is the question displayed to the user.
	Message string
	// DefaultValue is the pre-selected answer (true = Yes).
	DefaultValue bool
}

PromptConfirmConfig configures a yes/no confirmation prompt.

type PromptConfirmResult added in v0.2.0

type PromptConfirmResult struct {
	// Value is true for "Yes", false for "No".
	Value bool
	// Cancelled is true if the user dismissed the prompt.
	Cancelled bool
}

PromptConfirmResult is the response from a confirmation prompt.

type PromptInputConfig added in v0.2.0

type PromptInputConfig struct {
	// Message is the question displayed to the user.
	Message string
	// Placeholder is ghost text shown when the input is empty.
	Placeholder string
	// Default is the pre-filled value in the input field.
	Default string
}

PromptInputConfig configures a free-form text input prompt.

type PromptInputResult added in v0.2.0

type PromptInputResult struct {
	// Value is the text the user entered.
	Value string
	// Cancelled is true if the user dismissed the prompt.
	Cancelled bool
}

PromptInputResult is the response from a text input prompt.

type PromptMultiSelectConfig added in v0.14.0

type PromptMultiSelectConfig struct {
	// Message is the question or instruction displayed to the user.
	Message string
	// Options is the list of choices the user can select from.
	Options []string
	// DefaultSelected contains indices of options that should be
	// pre-selected when the prompt appears. If nil, all options are selected.
	DefaultSelected []int
}

PromptMultiSelectConfig configures a multi-selection prompt that allows the user to toggle multiple options and confirm their selection.

type PromptMultiSelectResult added in v0.14.0

type PromptMultiSelectResult struct {
	// Values contains the text of selected options.
	Values []string
	// Indices contains the zero-based indices of selected options.
	Indices []int
	// Cancelled is true if the user dismissed the prompt (ESC) or
	// the prompt was unavailable (non-interactive mode).
	Cancelled bool
}

PromptMultiSelectResult is the response from a multi-selection prompt.

type PromptSelectConfig added in v0.2.0

type PromptSelectConfig struct {
	// Message is the question or instruction displayed to the user.
	Message string
	// Options is the list of choices the user can select from.
	Options []string
}

PromptSelectConfig configures a selection prompt that presents the user with a list of options to choose from.

type PromptSelectResult added in v0.2.0

type PromptSelectResult struct {
	// Value is the text of the selected option.
	Value string
	// Index is the zero-based index of the selected option.
	Index int
	// Cancelled is true if the user dismissed the prompt (ESC) or
	// the prompt was unavailable (non-interactive mode).
	Cancelled bool
}

PromptSelectResult is the response from a selection prompt.

type PromptTemplate added in v0.28.0

type PromptTemplate struct {
	// Name is the template identifier.
	Name string
	// Content is the original template content.
	Content string
	// Variables are the extracted {{variable}} names.
	Variables []string
}

PromptTemplate represents a parsed template with variable placeholders.

type ReasoningStartEvent added in v0.60.0

type ReasoningStartEvent struct {
	ID string
}

ReasoningStartEvent fires when the LLM begins reasoning/thinking.

func (ReasoningStartEvent) Type added in v0.60.0

func (e ReasoningStartEvent) Type() EventType

type Result

type Result interface {
	// contains filtered or unexported methods
}

Result is the interface satisfied by all result types internally.

type RetryEvent added in v0.60.0

type RetryEvent struct {
	// Attempt is the retry number, starting at 1 for each model request.
	Attempt int
	Error   string
	Delay   time.Duration
}

RetryEvent fires when the LLM provider request is retried after a transient error.

func (RetryEvent) Type added in v0.60.0

func (e RetryEvent) Type() EventType

type Runner

type Runner struct {
	// contains filtered or unexported fields
}

Runner manages loaded extensions and dispatches events to their handlers sequentially. Handlers execute in extension load order; for cancellable events the first blocking result wins.

Each extension has a dedicated reentrant mutex so that handlers for the same extension are serialized (preventing data races on shared package-level state), while handlers for different extensions may execute concurrently.

func NewRunner

func NewRunner(exts []LoadedExtension) *Runner

NewRunner creates a Runner from a set of loaded extensions.

func (*Runner) DeleteState added in v0.75.0

func (r *Runner) DeleteState(key string)

DeleteState removes a key from the state store. No-op if the key is missing. Thread-safe. Saver invocations are serialized via saverMu — see SetState for the rationale.

func (*Runner) Emit

func (r *Runner) Emit(event Event) (Result, error)

Emit dispatches an event to all matching handlers sequentially. It returns the accumulated result from all handlers, or nil if no handler responded.

For blocking events (ToolCall, Input), the first blocking result short-circuits:

  • ToolCallResult{Block: true} stops iteration and returns immediately.
  • InputResult{Action: "handled"} stops iteration and returns immediately.

For chainable events (ToolResult), each handler sees the accumulated result from previous handlers. The final merged result is returned.

Panics in handlers are recovered and logged; they do not crash the process.

func (*Runner) EmitCustomEvent added in v0.3.0

func (r *Runner) EmitCustomEvent(name, data string)

EmitCustomEvent dispatches a named event to all handlers registered via api.OnCustomEvent. Handlers run synchronously in extension load order. Panics are recovered and logged. Thread-safe.

func (*Runner) Extensions

func (r *Runner) Extensions() []LoadedExtension

Extensions returns the loaded extensions for inspection (e.g. CLI list).

func (*Runner) GetContext

func (r *Runner) GetContext() Context

GetContext returns a snapshot of the current runtime context. Thread-safe.

func (*Runner) GetEditor added in v0.2.0

func (r *Runner) GetEditor() *EditorConfig

GetEditor returns the current editor interceptor, or nil if none is set. Thread-safe. Returns a shallow copy — function fields are reference types so the copy is safe.

func (*Runner) GetFooter added in v0.2.0

func (r *Runner) GetFooter() *HeaderFooterConfig

GetFooter returns the current custom footer, or nil if none is set. Thread-safe.

func (*Runner) GetHeader added in v0.2.0

func (r *Runner) GetHeader() *HeaderFooterConfig

GetHeader returns the current custom header, or nil if none is set. Thread-safe.

func (*Runner) GetMessageRenderer added in v0.3.0

func (r *Runner) GetMessageRenderer(name string) *MessageRendererConfig

GetMessageRenderer returns the named message renderer, or nil if no extension registered a renderer with that name. If multiple extensions register the same name, the last one (by load order) wins.

func (*Runner) GetOption added in v0.3.0

func (r *Runner) GetOption(name string) string

GetOption resolves a named option value in priority order:

  1. Runtime override (via SetOption)
  2. Environment variable: KIT_OPT_<NAME> (uppercased, dashes → underscores)
  3. Viper config: options.<name>
  4. Default value from RegisterOption

Returns empty string if the option was never registered. Thread-safe.

func (*Runner) GetShortcutHandlers added in v0.95.0

func (r *Runner) GetShortcutHandlers() map[string]func()

GetShortcutHandlers returns the key → handler map used by the TUI, with each handler already bound to the runner's live context. The binding closure resolves the context at fire time, so the cache stays valid across session and model changes. Thread-safe.

func (*Runner) GetShortcuts added in v0.3.0

func (r *Runner) GetShortcuts() map[string]ShortcutEntry

GetShortcuts returns all registered keyboard shortcuts as a map of key binding → handler. Keys are normalized (see NormalizeShortcutKey). If multiple extensions register the same key, the last registration wins.

The result is cached and rebuilt only when the extension set changes, since this is called on every key press. The returned map is shared and must not be mutated by callers. Thread-safe.

func (*Runner) GetState added in v0.75.0

func (r *Runner) GetState(key string) (string, bool)

GetState returns the value previously stored via SetState, plus a bool indicating whether the key was present. Thread-safe.

func (*Runner) GetStatusEntries added in v0.3.0

func (r *Runner) GetStatusEntries() []StatusBarEntry

GetStatusEntries returns all status bar entries, sorted by priority (ascending). Thread-safe.

func (*Runner) GetTerminalSize added in v0.91.0

func (r *Runner) GetTerminalSize() (int, int)

GetTerminalSize returns the last recorded terminal dimensions, or 0, 0 when running without a TUI.

func (*Runner) GetToolRenderer added in v0.2.0

func (r *Runner) GetToolRenderer(toolName string) *ToolRenderConfig

GetToolRenderer returns the custom renderer for the named tool, or nil when no extension registered one. If several extensions register renderers for the same tool, the last one by load order wins.

func (*Runner) GetUIVisibility added in v0.3.0

func (r *Runner) GetUIVisibility() *UIVisibility

GetUIVisibility returns the current UI visibility overrides, or nil if none have been set (meaning show everything). Thread-safe.

func (*Runner) GetWidgets added in v0.2.0

func (r *Runner) GetWidgets(placement WidgetPlacement) []WidgetConfig

GetWidgets returns all widgets matching the given placement, sorted by priority (ascending). Thread-safe.

func (*Runner) HasHandlers

func (r *Runner) HasHandlers(event EventType) bool

HasHandlers returns true if any loaded extension has at least one handler registered for the given event type.

func (*Runner) IsToolDisabled added in v0.3.0

func (r *Runner) IsToolDisabled(toolName string) bool

IsToolDisabled returns true if the tool has been disabled via SetActiveTools. Thread-safe.

func (*Runner) ListState added in v0.75.0

func (r *Runner) ListState() []string

ListState returns all keys currently in the state store, in unspecified order. Thread-safe.

func (*Runner) LoadStateFromFile added in v0.75.0

func (r *Runner) LoadStateFromFile(path string) error

LoadStateFromFile reads a JSON map from path and replaces the in-memory state store with its contents. Missing or empty files are treated as "no prior state": the in-memory store is replaced with an empty map so callers can safely switch sessions without leaking keys from a prior session into a new one. Malformed JSON returns the parse error without touching the existing store. Thread-safe.

func (*Runner) RegisteredCommands

func (r *Runner) RegisteredCommands() []CommandDef

RegisteredCommands returns all slash commands registered by loaded extensions.

func (*Runner) RegisteredOptions added in v0.3.0

func (r *Runner) RegisteredOptions() []OptionDef

RegisteredOptions returns all option definitions from all loaded extensions.

func (*Runner) RegisteredShortcuts added in v0.3.0

func (r *Runner) RegisteredShortcuts() []ShortcutEntry

RegisteredShortcuts returns the effective shortcut bindings across all loaded extensions, sorted by source file then key. Used by /shortcuts. Thread-safe.

func (*Runner) RegisteredTools

func (r *Runner) RegisteredTools() []ToolDef

RegisteredTools returns all custom tools registered by loaded extensions.

func (*Runner) Reload added in v0.3.0

func (r *Runner) Reload(exts []LoadedExtension)

Reload replaces the loaded extensions with a fresh set and clears all dynamic state (widgets, status, header/footer, editor, visibility, disabled tools, custom event subscriptions). Option overrides are preserved across reloads since they represent user intent.

The caller is responsible for emitting SessionShutdown before calling Reload and SessionStart after.

func (*Runner) RemoveFooter added in v0.2.0

func (r *Runner) RemoveFooter()

RemoveFooter removes the custom footer. No-op if none is set. Thread-safe.

func (*Runner) RemoveHeader added in v0.2.0

func (r *Runner) RemoveHeader()

RemoveHeader removes the custom header. No-op if none is set. Thread-safe.

func (*Runner) RemoveStatusEntry added in v0.3.0

func (r *Runner) RemoveStatusEntry(key string)

RemoveStatusEntry removes a status bar entry by key. Thread-safe.

func (*Runner) RemoveWidget added in v0.2.0

func (r *Runner) RemoveWidget(id string)

RemoveWidget removes a widget by ID. No-op if the ID does not exist. Thread-safe.

func (*Runner) ResetEditor added in v0.2.0

func (r *Runner) ResetEditor()

ResetEditor removes the active editor interceptor and restores the default built-in editor behavior. No-op if no interceptor is set. Thread-safe.

func (*Runner) SaveStateToFile added in v0.75.0

func (r *Runner) SaveStateToFile(path string) error

SaveStateToFile writes the current state store to path as JSON, creating parent directories as needed. An empty store writes an empty object so that consumers can distinguish "loaded but empty" from "never saved". Writes are atomic via a tmp-file-and-rename sequence. Thread-safe.

func (*Runner) SetActiveTools added in v0.3.0

func (r *Runner) SetActiveTools(names []string)

SetActiveTools restricts the tool set to the named tools. All tools not in the list are disabled. Passing nil or an empty slice re-enables all tools. Thread-safe.

func (*Runner) SetConfigStore added in v0.71.0

func (r *Runner) SetConfigStore(v *viper.Viper)

SetConfigStore sets the per-instance configuration store used by GetOption to resolve "options.<name>" config values. When unset (nil), GetOption falls back to the process-global viper store. Threading a per-Kit store keeps extension option resolution isolated between Kit instances.

func (*Runner) SetContext

func (r *Runner) SetContext(ctx Context)

SetContext updates the runtime context (session ID, model, etc.) that is passed to every handler invocation. Nil function fields are replaced with safe no-ops so extension handlers never panic on a missing callback. Thread-safe.

func (*Runner) SetEditor added in v0.2.0

func (r *Runner) SetEditor(config EditorConfig)

SetEditor installs an editor interceptor that wraps the built-in input editor. Only one interceptor is active at a time; calling SetEditor replaces any previous interceptor. Thread-safe.

func (*Runner) SetFooter added in v0.2.0

func (r *Runner) SetFooter(config HeaderFooterConfig)

SetFooter places or replaces the custom footer. Thread-safe.

func (*Runner) SetHeader added in v0.2.0

func (r *Runner) SetHeader(config HeaderFooterConfig)

SetHeader places or replaces the custom header. Thread-safe.

func (*Runner) SetOption added in v0.3.0

func (r *Runner) SetOption(name, value string)

SetOption stores a runtime override for a named option. This takes highest priority over env vars, config, and defaults. Thread-safe.

func (*Runner) SetState added in v0.75.0

func (r *Runner) SetState(key, value string)

SetState records a key-value pair in the runner's session-scoped extension state store. The store is in-memory; callers wire SetStateSaver to persist changes to a sidecar file. Thread-safe.

When a saver is installed, concurrent SetState/DeleteState invocations are serialized through saverMu so that overlapping snapshot-and-rename writes cannot interleave (which would otherwise race on the shared tmp file and risk persisting an older snapshot after a newer one).

func (*Runner) SetStateSaver added in v0.75.0

func (r *Runner) SetStateSaver(saver func())

SetStateSaver installs an optional persistence hook invoked after each mutation to the state store (SetState / DeleteState / LoadStateFromFile). Pass nil to disable persistence. Thread-safe.

func (*Runner) SetStatusEntry added in v0.3.0

func (r *Runner) SetStatusEntry(entry StatusBarEntry)

func (*Runner) SetTerminalSize added in v0.91.0

func (r *Runner) SetTerminalSize(width, height int)

SetStatusEntry places or updates a keyed status bar entry. Thread-safe. SetTerminalSize records the current terminal dimensions. The TUI calls this on every resize so that GetTerminalSize reports live values to handlers, including long-lived goroutines that captured a Context earlier.

func (*Runner) SetUIVisibility added in v0.3.0

func (r *Runner) SetUIVisibility(v UIVisibility)

SetUIVisibility updates the UI visibility overrides. Thread-safe.

func (*Runner) SetWidget added in v0.2.0

func (r *Runner) SetWidget(config WidgetConfig)

SetWidget places or updates a persistent widget. The widget is identified by config.ID; calling SetWidget with the same ID replaces the previous content. Thread-safe.

func (*Runner) SnapshotState added in v0.75.0

func (r *Runner) SnapshotState() map[string]string

SnapshotState returns a copy of the current state store as a fresh map. Useful for persisting to disk without holding the lock. Thread-safe.

type SearchPath added in v0.97.0

type SearchPath struct {
	// Dir is the resolved directory path.
	Dir string
	// Scope labels the directory: "system", "user" or "project".
	Scope string
}

SearchPath is one directory that extension auto-discovery scans, paired with a short scope label for display in diagnostics.

func AuthoredSearchPaths added in v0.97.0

func AuthoredSearchPaths() []SearchPath

AuthoredSearchPaths returns the directories that auto-discovery scans for hand-written extensions, in load order, with their scope labels. Entries are returned whether or not the directory exists, because the list describes where an extension may be placed rather than what is installed.

The system scope expands to however many directories $KIT_SYSTEM_EXTENSIONS_DIR configures, and to none at all when it is disabled, so callers must not assume a fixed length.

Git package roots are deliberately excluded: those are managed by "kit install" rather than authored by hand.

type SessionMessage added in v0.3.0

type SessionMessage struct {
	// ID is the unique entry identifier in the session tree.
	ID string
	// ParentID links this entry to its parent in the tree.
	ParentID string
	// Role is the message role: "user", "assistant", "tool", or "system".
	Role string
	// Content is the text content of the message (tool calls and results
	// are serialized as text summaries).
	Content string
	// Model is the model that generated this message (empty for user messages).
	Model string
	// Provider is the provider used (empty for user messages).
	Provider string
	// Timestamp is the RFC3339-formatted creation time.
	Timestamp string
}

SessionMessage represents a conversation message exposed to extensions. This is a simplified, read-only view of the internal message structures.

type SessionShutdownEvent

type SessionShutdownEvent struct{}

SessionShutdownEvent fires when the application is closing.

func (SessionShutdownEvent) Type

type SessionStartEvent

type SessionStartEvent struct {
	SessionID string
}

SessionStartEvent fires when a session is loaded or created.

func (SessionStartEvent) Type

func (e SessionStartEvent) Type() EventType

type SessionUsage added in v0.38.0

type SessionUsage struct {
	// TotalInputTokens is the sum of input tokens across all requests.
	TotalInputTokens int
	// TotalOutputTokens is the sum of output tokens across all requests.
	TotalOutputTokens int
	// TotalCacheReadTokens is the sum of cache read tokens.
	TotalCacheReadTokens int
	// TotalCacheWriteTokens is the sum of cache write tokens.
	TotalCacheWriteTokens int
	// TotalCost is the total cost in USD across all requests.
	// Always 0 when IsOAuth is true, and also 0 when the active model has no
	// pricing in the registry — check IsOAuth to tell the two apart.
	TotalCost float64
	// RequestCount is the number of LLM requests made in this session.
	RequestCount int
	// IsOAuth is true when the active provider credential is an OAuth token
	// (e.g. a Claude subscription) rather than a per-token billed API key.
	// Under OAuth the user is not charged per request, so TotalCost is
	// deliberately reported as 0. Extensions that render cost should check
	// this flag to distinguish "free under subscription" from "$0.00 spent".
	IsOAuth bool
}

SessionUsage contains aggregated token usage and cost statistics for the current session. Extensions use this with GetSessionUsage() to report usage information.

type ShortcutDef added in v0.3.0

type ShortcutDef struct {
	// Key is the key binding (e.g., "ctrl+p", "alt+t", "f1", "ctrl+shift+s").
	// Normalized at registration: modifier order and casing do not matter.
	Key string
	// Description explains what the shortcut does (shown in /shortcuts).
	Description string
}

ShortcutDef describes a global keyboard shortcut registered by an extension. Shortcuts fire across all app states except modal prompts/overlays. Use modifier combinations (e.g., "ctrl+p", "alt+t", "f1") — avoid bare characters like "a" or "x" which conflict with text input.

type ShortcutEntry added in v0.3.0

type ShortcutEntry struct {
	Def     ShortcutDef
	Handler func(Context)
	// Source is the file name of the registering extension, used to attribute
	// bindings in the /shortcuts listing.
	Source string
}

ShortcutEntry pairs a shortcut definition with its handler.

type Skill added in v0.28.0

type Skill struct {
	// Name is the human-readable identifier.
	Name string
	// Description summarizes what this skill provides.
	Description string
	// Content is the markdown body (frontmatter stripped).
	Content string
	// Path is the absolute filesystem path.
	Path string
	// License is an optional SPDX license identifier (agentskills.io field).
	License string
	// Compatibility is an optional note describing targeted environments
	// (agentskills.io field).
	Compatibility string
	// Metadata is an optional bag of arbitrary string key/value pairs
	// (agentskills.io field).
	Metadata map[string]string
	// AllowedTools optionally restricts which tools the skill may use
	// (experimental agentskills.io field).
	AllowedTools string
	// DisableModelInvocation hides the skill from the model-facing catalog
	// while keeping it available via explicit activation (agentskills.io field).
	DisableModelInvocation bool
	// Tags are optional labels for categorization. Kit extension.
	Tags []string
	// When controls automatic inclusion: "always", "on-demand", or file-glob.
	// Kit extension.
	When string
}

Skill represents a loaded skill file with parsed YAML frontmatter.

type SkillLoadResult added in v0.28.0

type SkillLoadResult struct {
	// Skills is the list of loaded skills.
	Skills []Skill
	// Error describes loading failures (empty if success).
	Error string
}

SkillLoadResult reports skills loaded from a directory.

type SourceEvent added in v0.60.0

type SourceEvent struct {
	SourceType string
	ID         string
	URL        string
	Title      string
}

SourceEvent fires when the LLM references a source (e.g. from web search).

func (SourceEvent) Type added in v0.60.0

func (e SourceEvent) Type() EventType

type StatusBarEntry added in v0.3.0

type StatusBarEntry struct {
	// Key uniquely identifies this entry (e.g. "myext:git-branch").
	Key string
	// Text is the rendered content shown in the status bar.
	Text string
	// Priority controls ordering. Lower values render further left.
	// Built-in entries (model, usage) have implicit priority 100-110.
	Priority int
}

StatusBarEntry represents a keyed entry in the TUI status bar. Extensions can set multiple independent entries that render alongside the built-in model name and token usage display.

type StepFinishEvent added in v0.60.0

type StepFinishEvent struct {
	StepNumber       int
	HasToolCalls     bool
	FinishReason     string
	InputTokens      int64
	OutputTokens     int64
	CacheReadTokens  int64
	CacheWriteTokens int64
}

StepFinishEvent fires when a step completes, providing step metadata and token usage. Usage fields are plain int64 (not LLMUsage) because Yaegi cannot handle fantasy types across the interpreter boundary.

func (StepFinishEvent) Type added in v0.60.0

func (e StepFinishEvent) Type() EventType

type StepStartEvent added in v0.60.0

type StepStartEvent struct {
	StepNumber int
}

StepStartEvent fires when a new LLM call begins within a multi-step agent turn.

func (StepStartEvent) Type added in v0.60.0

func (e StepStartEvent) Type() EventType

type SubagentChunkEvent added in v0.24.0

type SubagentChunkEvent struct {
	// ToolCallID matches the SubagentStartEvent.ToolCallID for this subagent.
	ToolCallID string
	// Task is the task description (repeated for convenience).
	Task string
	// ChunkType identifies the event kind:
	//   "text"                 — LLM text chunk (read Content)
	//   "reasoning"            — reasoning/thinking delta (read Content)
	//   "tool_call"            — subagent called a tool (read ToolName, ToolArgs)
	//   "tool_result"          — tool returned a result (read ToolName, ToolResult, IsError)
	//   "tool_execution_start" — tool began executing (read ToolName)
	//   "tool_execution_end"   — tool finished executing (read ToolName)
	//   "turn_start"           — subagent turn began
	//   "turn_end"             — subagent turn ended
	ChunkType string
	// Content carries text for "text" and "reasoning" chunk types.
	Content string
	// ToolName is set on tool-related chunk types.
	ToolName string
	// ToolArgs is the JSON-encoded tool arguments for "tool_call" chunks.
	ToolArgs string
	// ToolResult is the tool output for "tool_result" chunks.
	ToolResult string
	// IsError is true when a "tool_result" chunk represents an error.
	IsError bool
}

SubagentChunkEvent fires for each real-time event from a running subagent. Type field indicates the kind of event; read the relevant fields accordingly.

func (SubagentChunkEvent) Type added in v0.24.0

func (e SubagentChunkEvent) Type() EventType

type SubagentConfig added in v0.9.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.
	// Empty string uses the default system prompt.
	SystemPrompt string

	// Timeout limits execution time. Zero means 5 minute default.
	Timeout time.Duration

	// OnOutput streams the subagent's assistant text chunks as it runs.
	// It is a convenience alternative to OnEvent for callers that only
	// care about text output. May be called from a goroutine; must be
	// safe for concurrent use.
	OnOutput func(chunk string)

	// OnEvent receives real-time events from the subagent's execution:
	// text chunks, tool calls, tool results, reasoning deltas, etc.
	// Called synchronously from the subagent's event loop.
	OnEvent func(SubagentEvent)

	// OnComplete is called when the subagent finishes (success or error).
	// For background spawns (Blocking false) it is called from the
	// subagent's goroutine; must be safe for concurrent use. For blocking
	// spawns it is called before SpawnSubagent returns.
	OnComplete func(result SubagentResult)

	// Blocking, when true, makes SpawnSubagent wait for completion and
	// return the result directly (handle is nil). When false (default),
	// the subagent runs in a background goroutine and SpawnSubagent
	// returns immediately with a non-nil handle for monitoring and
	// cancellation (result is nil; use OnComplete or handle.Wait()).
	Blocking bool

	// NoSession, when true, runs the subagent without persisting a session
	// file. By default (false), subagent sessions are persisted so they can
	// be loaded for replay/inspection. Set to true for ephemeral tasks
	// where session history is not needed.
	NoSession bool

	// ParentSessionID links the subagent's session to the parent (optional).
	// When set, the subagent's session header includes a parent reference
	// so viewers can navigate the session tree. When empty, the host Kit's
	// active persisted session ID is recorded automatically.
	ParentSessionID string

	// SessionID resumes an existing subagent session instead of creating a
	// new one. Set it to the SessionID of a previous SubagentResult so
	// follow-up prompts reuse the subagent's accumulated context instead of
	// re-establishing it from scratch. Mutually exclusive with NoSession.
	// An unknown ID is an error.
	SessionID string
}

--------------------------------------------------------------------------- Subagent types --------------------------------------------------------------------------- SubagentConfig configures a subagent spawn.

type SubagentEndEvent added in v0.24.0

type SubagentEndEvent struct {
	// ToolCallID matches the SubagentStartEvent.ToolCallID for this subagent.
	ToolCallID string
	// Task is the task description.
	Task string
	// Response is the subagent's final text response (empty on error).
	Response string
	// ErrorMsg is non-empty when the subagent failed.
	ErrorMsg string
}

SubagentEndEvent fires when a subagent tool call completes.

func (SubagentEndEvent) Type added in v0.24.0

func (e SubagentEndEvent) Type() EventType

type SubagentEvent added in v0.12.1

type SubagentEvent struct {
	// Type identifies the event: "text", "reasoning", "tool_call",
	// "tool_result", "tool_execution_start", "tool_execution_end",
	// "turn_start", "turn_end".
	Type string

	// Content carries text for "text" and "reasoning" events.
	Content string

	// ToolCallID is set on tool_call, tool_result, tool_execution_start,
	// and tool_execution_end events.
	ToolCallID string
	// ToolName is set on tool-related events.
	ToolName string
	// ToolKind is set on tool-related events.
	ToolKind string
	// ToolArgs is set on tool_call events (JSON-encoded).
	ToolArgs string
	// ToolResult is set on tool_result events.
	ToolResult string
	// IsError is set on tool_result events.
	IsError bool
}

SubagentEvent carries a real-time event from a running subagent. Extensions use the Type field to determine what happened and read the relevant fields. This is a concrete struct (not an interface) for Yaegi compatibility.

type SubagentHandle added in v0.9.0

type SubagentHandle struct {
	// ID is a unique identifier for this subagent instance.
	ID string
	// contains filtered or unexported fields
}

SubagentHandle provides control over a background (non-blocking) subagent. The subagent runs in-process in a goroutine; the handle exposes cancellation and completion signalling.

func NewSubagentHandle added in v0.85.0

func NewSubagentHandle(id string, cancel func()) *SubagentHandle

NewSubagentHandle creates a handle for a background subagent run. cancel, when non-nil, is invoked by Kill to abort the run. The host (extension bridge) must call Complete exactly once when the run finishes. Extensions receive handles from SpawnSubagent and should not construct their own.

func (*SubagentHandle) Complete added in v0.85.0

func (h *SubagentHandle) Complete(result SubagentResult)

Complete records the final result and signals Done/Wait. Called by the host when the background run finishes; subsequent calls are no-ops. Extensions should not call this.

func (*SubagentHandle) Done added in v0.9.0

func (h *SubagentHandle) Done() <-chan struct{}

Done returns a channel that closes when the subagent completes.

func (*SubagentHandle) Kill added in v0.9.0

func (h *SubagentHandle) Kill() error

Kill cancels the running subagent. The run terminates with a context cancellation error, delivered via OnComplete/Wait as usual. Calling Kill after completion is a no-op.

func (*SubagentHandle) Wait added in v0.9.0

func (h *SubagentHandle) Wait() SubagentResult

Wait blocks until the subagent completes and returns the result.

type SubagentResult added in v0.9.0

type SubagentResult struct {
	// Response is the subagent's final text response.
	Response string

	// Error is set if the subagent failed (nil on success).
	Error error

	// ExitCode is 0 on success and 1 on failure. The subagent runs
	// in-process (not as a subprocess); this field mirrors Error for
	// callers that prefer a numeric status.
	ExitCode int

	// Elapsed is the total execution time.
	Elapsed time.Duration

	// Usage contains token usage if available.
	Usage *SubagentUsage

	// SessionID is the subagent's session identifier, if available.
	// Populated when the subagent persists its session (requires running
	// without --no-session). Empty for ephemeral sessions.
	SessionID string
}

SubagentResult contains the outcome of a subagent execution.

type SubagentStartEvent added in v0.24.0

type SubagentStartEvent struct {
	// ToolCallID is the LLM-assigned ID of the subagent tool call.
	// Use this to correlate SubagentChunkEvent and SubagentEndEvent.
	ToolCallID string
	// Task is the task description passed to the subagent.
	Task string
}

SubagentStartEvent fires when a subagent tool call begins executing.

func (SubagentStartEvent) Type added in v0.24.0

func (e SubagentStartEvent) Type() EventType

type SubagentUsage added in v0.9.0

type SubagentUsage struct {
	InputTokens  int64
	OutputTokens int64
}

SubagentUsage contains token usage from the subagent's run.

type TerminalResizeEvent added in v0.91.0

type TerminalResizeEvent struct {
	// Width is the new terminal width in columns.
	Width int
	// Height is the new terminal height in rows.
	Height int
}

TerminalResizeEvent fires when the terminal is resized, and once at startup with the initial dimensions so a handler can lay out without waiting for the user to resize. Interactive TUI only.

The same values are available through Context.GetTerminalSize(); this event exists so extensions can re-render chrome immediately instead of polling.

func (TerminalResizeEvent) Type added in v0.91.0

func (e TerminalResizeEvent) Type() EventType

type ThemeColor added in v0.15.0

type ThemeColor struct {
	Light string
	Dark  string
}

ThemeColor is an adaptive color pair with light and dark hex values. Either field may be empty to inherit from the default theme.

type ThemeColorConfig added in v0.15.0

type ThemeColorConfig struct {
	Primary     ThemeColor
	Secondary   ThemeColor
	Success     ThemeColor
	Warning     ThemeColor
	Error       ThemeColor
	Info        ThemeColor
	Text        ThemeColor
	Muted       ThemeColor
	VeryMuted   ThemeColor
	Background  ThemeColor
	Border      ThemeColor
	MutedBorder ThemeColor
	System      ThemeColor
	Tool        ThemeColor
	Accent      ThemeColor
	Highlight   ThemeColor

	// Markdown/syntax highlighting overrides.
	MdHeading ThemeColor
	MdLink    ThemeColor
	MdKeyword ThemeColor
	MdString  ThemeColor
	MdNumber  ThemeColor
	MdComment ThemeColor
}

ThemeColorConfig defines a complete color theme that extensions can register programmatically via ctx.RegisterTheme(). Uses plain hex strings (not color.Color) so the type is safe to pass across the Yaegi boundary.

type ThemeColors added in v0.96.0

type ThemeColors struct {
	// Name is the active theme's name, e.g. "catppuccin".
	Name string
	// Dark is true when the resolved colors are the dark variants.
	Dark bool

	Primary     string
	Secondary   string
	Success     string
	Warning     string
	Error       string
	Info        string
	Text        string
	Muted       string
	VeryMuted   string
	Background  string
	Border      string
	MutedBorder string
	System      string
	Tool        string
	Accent      string
	Highlight   string

	// Markdown/syntax highlighting colors.
	MdHeading string
	MdLink    string
	MdKeyword string
	MdString  string
	MdNumber  string
	MdComment string
}

ThemeColors holds the active theme's colors as "#rrggbb" hex strings, with the light/dark variants already resolved for the terminal's appearance. Returned by ctx.GetTheme().

It is the read counterpart to ThemeColorConfig: that type describes a theme being registered (light and dark for each slot), this one reports the colors actually in effect right now.

func (ThemeColors) ANSI added in v0.96.0

func (t ThemeColors) ANSI(hexColor, text string) string

ANSI wraps text in a truecolor foreground escape for the given theme hex color and resets afterwards. An empty or malformed color returns text unchanged, so a partially-defined theme degrades to plain output rather than leaking escape codes.

Widget Render output is used verbatim, so this is how an extension paints arbitrary UI in the user's theme.

func (ThemeColors) ANSIBold added in v0.96.0

func (t ThemeColors) ANSIBold(hexColor, text string) string

ANSIBold is ANSI with the bold attribute set.

type ThinkingLevelChangeEvent added in v0.91.0

type ThinkingLevelChangeEvent struct {
	// NewLevel is the level now in effect: "off", "none", "minimal", "low",
	// "medium", or "high".
	NewLevel string
	// PreviousLevel is the level before the change.
	PreviousLevel string
	// Source indicates what triggered the change:
	//   "user"           — the /thinking command or the shift+tab shortcut
	//   "model_fallback" — an automatic downgrade because the newly selected
	//                      model does not support the previous level
	Source string
}

ThinkingLevelChangeEvent fires after the extended-thinking effort level changes. Handlers that display the level should re-read it here rather than caching a value from session start.

func (ThinkingLevelChangeEvent) Type added in v0.91.0

type ToolCallEvent

type ToolCallEvent struct {
	ToolName   string
	ToolCallID string
	ToolKind   string         // Tool classification: "execute", "edit", "read", "search", "agent"
	Input      string         // JSON-encoded tool parameters
	ParsedArgs map[string]any // Pre-parsed arguments for convenience (nil on parse failure)
	// Source indicates who initiated the tool call.
	// Currently always "llm" (all tool calls originate from the LLM agent loop).
	// Future user-initiated tool features may set this to "user".
	Source string
}

ToolCallEvent fires before a tool executes.

func (ToolCallEvent) Type

func (e ToolCallEvent) Type() EventType

type ToolCallInputDeltaEvent added in v0.58.0

type ToolCallInputDeltaEvent struct {
	ToolCallID string
	Delta      string // JSON fragment of tool arguments
}

ToolCallInputDeltaEvent fires for each streamed fragment of tool call arguments as they arrive from the LLM.

func (ToolCallInputDeltaEvent) Type added in v0.58.0

type ToolCallInputEndEvent added in v0.58.0

type ToolCallInputEndEvent struct {
	ToolCallID string
}

ToolCallInputEndEvent fires when tool argument streaming is complete, before the tool call is parsed and execution begins.

func (ToolCallInputEndEvent) Type added in v0.58.0

type ToolCallInputStartEvent added in v0.58.0

type ToolCallInputStartEvent struct {
	ToolCallID string
	ToolName   string
	ToolKind   string // Tool classification: "execute", "edit", "read", "search", "agent"
}

ToolCallInputStartEvent fires when the LLM begins generating tool call arguments. The tool name is known but the full argument JSON is still being streamed.

func (ToolCallInputStartEvent) Type added in v0.58.0

type ToolCallResult

type ToolCallResult struct {
	Block  bool
	Reason string
}

ToolCallResult controls whether the tool call proceeds.

type ToolContext added in v0.3.0

type ToolContext struct {
	// IsCancelled returns true when the tool's execution has been cancelled
	// (e.g. the user interrupted the agent or the request timed out).
	// Long-running tools should poll this periodically and return early.
	IsCancelled func() bool
	// OnProgress sends a progress message that is displayed in the TUI
	// while the tool is executing. Useful for long-running operations
	// that want to show incremental status.
	OnProgress func(text string)
}

ToolContext provides runtime context to a tool's ExecuteWithContext handler. It allows tools to check for cancellation and report progress while running.

type ToolDef

type ToolDef struct {
	Name        string
	Description string
	Parameters  string // JSON Schema string
	// Execute is the simple handler — receives JSON input, returns text result.
	// Use this for tools that don't need cancellation or progress reporting.
	Execute func(input string) (string, error)
	// ExecuteWithContext is the rich handler — receives JSON input plus a
	// ToolContext that provides cancellation checking and progress reporting.
	// If both Execute and ExecuteWithContext are set, ExecuteWithContext wins.
	ExecuteWithContext func(input string, tc ToolContext) (string, error)
}

ToolDef describes a custom tool registered by an extension.

type ToolExecutionEndEvent

type ToolExecutionEndEvent struct {
	ToolCallID string
	ToolName   string
	ToolKind   string
}

ToolExecutionEndEvent fires when a tool finishes executing.

func (ToolExecutionEndEvent) Type

type ToolExecutionStartEvent

type ToolExecutionStartEvent struct {
	ToolCallID string
	ToolName   string
	ToolKind   string
}

ToolExecutionStartEvent fires when a tool begins executing.

func (ToolExecutionStartEvent) Type

type ToolInfo added in v0.3.0

type ToolInfo struct {
	// Name is the tool's unique identifier.
	Name string
	// Description is the tool's human-readable description.
	Description string
	// Source indicates where the tool came from: "core", "mcp", or "extension".
	Source string
	// Enabled is true if the tool is currently active.
	Enabled bool
}

ToolInfo provides read-only information about a tool available to the agent. Used by GetAllTools to let extensions inspect and filter the tool set.

type ToolOutputEvent added in v0.20.0

type ToolOutputEvent struct {
	ToolCallID string
	ToolName   string
	ToolKind   string
	Chunk      string // Output text chunk
	IsStderr   bool   // Whether this chunk came from stderr
}

ToolOutputEvent fires when a tool produces streaming output chunks. This is primarily used for long-running tools like the shell tool to show output in real-time as it arrives, before the tool completes.

func (ToolOutputEvent) Type added in v0.20.0

func (e ToolOutputEvent) Type() EventType

type ToolRenderConfig added in v0.2.0

type ToolRenderConfig struct {
	// ToolName is the name of the tool this renderer applies to. Must match
	// the tool's registered name exactly (e.g. "shell", "read", "my-tool").
	// The one exception is the core shell tool, which is also found under
	// the name it had before its shell became configurable, "bash". A
	// renderer naming a tool exactly always wins over that fallback, so a
	// custom tool of your own named "bash" keeps its own renderer.
	ToolName string

	// DisplayName, if non-empty, replaces the auto-capitalized tool name
	// shown in the header line (e.g. "Shell" instead of "Bash").
	DisplayName string

	// BorderColor, if non-empty, overrides the default border color for
	// the tool result block. Accepts a hex color string (e.g. "#89b4fa").
	// By default, the border is green for success and red for error.
	BorderColor string

	// Background, if non-empty, sets a background color for the entire
	// tool result block. Accepts a hex color string (e.g. "#1e1e2e").
	// By default, no background is applied.
	Background string

	// BodyMarkdown, when true, passes the RenderBody output through the
	// glamour markdown renderer before display. This lets extensions return
	// markdown-formatted text without needing access to Kit's internal
	// rendering functions. Ignored when RenderBody is nil or returns empty.
	BodyMarkdown bool

	// RenderHeader, if non-nil, replaces the default parameter formatting
	// in the tool header line. Receives the JSON-encoded arguments and the
	// maximum width in columns. Return a short summary string for display
	// after the tool name, or empty string to fall back to default formatting.
	RenderHeader func(toolArgs string, width int) string

	// RenderBody, if non-nil, replaces the default tool result body rendering.
	// Receives the result text, error flag, and available width in columns.
	// Return the full styled body content, or empty string to fall back to
	// the builtin renderer (or default).
	RenderBody func(toolResult string, isError bool, width int) string
}

ToolRenderConfig provides custom rendering functions for a tool's display in the TUI. Extensions register tool renderers via API.RegisterToolRenderer() during Init. Both render functions are optional — if nil or if they return an empty string, the builtin renderer (or default) is used as a fallback.

Example:

api.RegisterToolRenderer(ext.ToolRenderConfig{
    ToolName: "my-tool",
    RenderHeader: func(toolArgs string, width int) string {
        // Parse args and return a compact summary for the header
        return "my-tool: doing something"
    },
    RenderBody: func(toolResult string, isError bool, width int) string {
        // Return custom formatted result body
        if isError {
            return "ERROR: " + toolResult
        }
        return "Result: " + toolResult
    },
})

type ToolResultEvent

type ToolResultEvent struct {
	ToolCallID string
	ToolName   string
	ToolKind   string
	Input      string
	Content    string
	IsError    bool
	Metadata   string // Optional JSON-encoded structured metadata (e.g. file diffs)
}

ToolResultEvent fires after tool execution with the output.

func (ToolResultEvent) Type

func (e ToolResultEvent) Type() EventType

type ToolResultResult

type ToolResultResult struct {
	Content *string // nil = unchanged
	IsError *bool   // nil = unchanged
}

ToolResultResult can modify the tool's output before it reaches the LLM.

type TreeNavigationResult added in v0.28.0

type TreeNavigationResult struct {
	// Success is true if the operation completed.
	Success bool
	// Error describes what went wrong (empty if success).
	Error string
}

TreeNavigationResult reports success or failure of tree operations.

type TreeNode added in v0.28.0

type TreeNode struct {
	// ID is the unique entry identifier.
	ID string
	// ParentID links this entry to its parent (empty if root).
	ParentID string
	// Type is the entry type: "message", "branch_summary", "model_change", "extension_data", "tool_execution".
	Type string
	// Role is the message role for message entries: "user", "assistant", "system", "tool".
	Role string
	// Content is the text content or summary.
	Content string
	// Model is the model that generated this (for assistant messages).
	Model string
	// Provider is the provider used.
	Provider string
	// Timestamp is the RFC3339-formatted creation time.
	Timestamp string
	// Children is the list of child entry IDs for tree traversal.
	Children []string
}

TreeNode represents a node in the session tree for navigation. Extensions use this to traverse conversation history and implement features like "fresh context" loops and branch summarization.

type TurnStateChangeEvent added in v0.91.0

type TurnStateChangeEvent struct {
	// State is the state just entered: "working" or "idle".
	State string
	// Previous is the state left behind, using the same vocabulary.
	Previous string
}

TurnStateChangeEvent fires when the UI enters or leaves its working state.

This is a superset of AgentStart/AgentEnd: it also covers work that never reaches the agent loop (shell commands run with "!"), and it fires on every path back to idle, including cancellation and error. Use it for UI that must track whether Kit is busy — a spinner or a turn timer — and use AgentStart/AgentEnd when you specifically care about agent turns and their token usage.

Interactive TUI only.

func (TurnStateChangeEvent) Type added in v0.91.0

type UIVisibility added in v0.3.0

type UIVisibility struct {
	HideStartupMessage bool // Hide the "Model loaded..." startup block
	HideStatusBar      bool // Hide the "provider · model  Tokens: ..." line
	HideSeparator      bool // Hide the "────────" divider between stream and input
	// HideInputHint is retained for compatibility and has no effect. The
	// submit hint is no longer a separate line below the composer; it lives
	// in the placeholder and disappears as soon as the user types.
	HideInputHint bool
}

UIVisibility controls which built-in TUI chrome elements are visible. The zero value shows everything (backward compatible). Extensions call ctx.SetUIVisibility to customise the layout — for example, a "minimal" theme can hide the startup banner, status bar, and input hint and replace them with a single custom footer.

type WarningsEvent added in v0.60.0

type WarningsEvent struct {
	Warnings []string
}

WarningsEvent fires when the LLM provider returns warnings about the request.

func (WarningsEvent) Type added in v0.60.0

func (e WarningsEvent) Type() EventType

type Watcher added in v0.35.0

type Watcher = watcher.ContentWatcher

Watcher monitors extension directories for .go file changes and triggers a reload callback when changes are detected. It is implemented in terms of the general-purpose internal/watcher.ContentWatcher.

Type-aliasing here lets existing call sites (cmd/root.go and the watcher_test.go suite) keep using `extensions.NewWatcher` / `*Watcher` without knowing about the underlying implementation.

func NewWatcher added in v0.35.0

func NewWatcher(dirs []string, onReload func()) (*Watcher, error)

NewWatcher creates a file watcher that monitors the given directories for .go file changes. When a change is detected (after debouncing), onReload is called. The watcher must be started with Start() and stopped with Close().

type WidgetConfig added in v0.2.0

type WidgetConfig struct {
	// ID uniquely identifies this widget. Must be non-empty.
	ID string

	// Placement determines where the widget appears (above or below input).
	Placement WidgetPlacement

	// Content describes what to render.
	Content WidgetContent

	// Style configures the appearance.
	Style WidgetStyle

	// Priority controls ordering within a placement slot. Lower values
	// render first. Widgets with equal priority are ordered by insertion
	// time.
	Priority int
}

WidgetConfig fully describes a widget for placement in the TUI. Extensions identify widgets by ID; calling SetWidget with the same ID replaces the previous widget. IDs should be descriptive to avoid collisions across extensions (e.g. "myext:token-counter").

type WidgetContent added in v0.2.0

type WidgetContent struct {
	// Text is the content to display. Ignored when Render is non-nil.
	Text string

	// Markdown, when true, renders Text as styled markdown instead of
	// plain text. Ignored when Render is non-nil — a Render function is
	// expected to do its own styling.
	Markdown bool

	// Render, if non-nil, produces the widget body on every frame. It
	// receives the width in columns available for content (the gutter and
	// padding are already subtracted) and returns the string to display,
	// which Kit uses verbatim. Returning an empty string hides the widget.
	//
	// Because it runs on every frame it must be cheap and must not block:
	// no network calls, no locks held across the call. Compute in an event
	// handler or goroutine, store the result, and format it here.
	//
	// IMPORTANT (Yaegi): assign an anonymous closure, or declare the target
	// function ABOVE this code. A bare reference to a function declared
	// later in the file silently renders nothing. See the extension docs.
	Render func(width int) string

	// RefreshHz requests continuous repainting for an animated widget.
	//
	// Kit's animation clock is demand-driven: it runs while the startup logo
	// or the activity spinner needs it and stops otherwise, so an idle
	// session costs nothing. A widget that only reads state repaints
	// whenever something else already caused a render, which when idle means
	// roughly twice a second (the input cursor blink). That is fine for a
	// counter and visibly choppy for a spinner or a sweeping gradient.
	//
	// Set RefreshHz to the rate the widget wants (1..30) and Kit keeps the
	// shared clock alive and calls Render at approximately that rate. Zero
	// (the default) means static: no clock is held open.
	//
	// This is a real cost. A non-zero value means the app never idles, so
	// ask for the lowest rate that looks right — 4-8Hz for a status pulse,
	// 10-15Hz for a spinner, 30 only for smooth motion.
	RefreshHz int
}

WidgetContent describes what to render in a widget slot.

Content is resolved in priority order: Render (if non-nil), then Text. Render gives the extension the terminal width and takes whatever string it returns verbatim, so it can emit arbitrary ANSI, box drawing, sparklines, or per-frame animation. Text is the simple declarative form.

type WidgetPlacement added in v0.2.0

type WidgetPlacement string

WidgetPlacement determines where a widget appears in the TUI layout relative to the input area.

const (
	// WidgetAbove places the widget above the input area, between the
	// separator and queued messages.
	WidgetAbove WidgetPlacement = "above"

	// WidgetBelow places the widget below the input area, between the
	// input and the status bar.
	WidgetBelow WidgetPlacement = "below"
)

type WidgetStyle added in v0.2.0

type WidgetStyle struct {
	// BorderColor is a hex color (e.g. "#a6e3a1") for the left border.
	// Empty uses the theme's default accent color.
	BorderColor string

	// NoBorder disables the left border entirely.
	NoBorder bool
}

WidgetStyle configures the visual appearance of a widget.

Jump to

Keyboard shortcuts

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