extensions

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package extensions implements a Pi-style 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.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExtensionToolsAsFantasy

func ExtensionToolsAsFantasy(defs []ToolDef) []fantasy.AgentTool

ExtensionToolsAsFantasy converts ToolDef values registered by extensions into fantasy.AgentTool implementations so the LLM can invoke them.

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. Interfaces (Event, Result) and the HandlerFunc type are NOT exported because Yaegi cannot generate interface wrappers for them. Instead, extensions use event-specific methods like api.OnToolCall() which accept concrete function signatures.

func WrapToolsWithExtensions

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

WrapToolsWithExtensions wraps each tool so that ToolCall and ToolResult events are emitted through the extension runner before and after execution. This is the Go equivalent of Pi's wrapper.ts pattern.

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 (*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) 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) 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) 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) 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.

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

func (a *API) RegisterCommand(cmd CommandDef)

RegisterCommand adds a slash command available in interactive mode.

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

AgentEndEvent fires when the agent finishes responding.

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

type CommandDef struct {
	Name        string
	Description string
	Execute     func(args string, ctx Context) (string, error)
}

CommandDef describes a slash command registered by an extension.

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)

	// 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: main"},
	//       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

	// 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()
}

Context provides runtime information to handlers about the current session.

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", "ctrl+c", "backspace")
	// and the editor's current text content. Return an EditorKeyAction to
	// control how the key is handled.
	//
	// 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).

This follows Pi's extension editor pattern (modal editor, rainbow editor) but uses concrete function fields instead of interfaces for Yaegi safety.

IMPORTANT (Yaegi limitation): Function fields MUST be set using anonymous function literals (closures), NOT bare function references. Yaegi does not correctly propagate return values from named function references assigned to struct fields. Wrap any named function in a closure:

// WRONG — Yaegi returns zero values:
ctx.SetEditor(ext.EditorConfig{HandleKey: myHandler, Render: myRender})

// CORRECT — closure wrapper works:
ctx.SetEditor(ext.EditorConfig{
    HandleKey: func(k string, t string) ext.EditorKeyAction { return myHandler(k, t) },
    Render:    func(w int, c string) string { return myRender(w, c) },
})

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

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

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

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

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

type LoadedExtension struct {
	Path          string
	Handlers      map[EventType][]HandlerFunc
	Tools         []ToolDef
	Commands      []CommandDef
	ToolRenderers []ToolRenderConfig
}

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.

type MessageEndEvent

type MessageEndEvent struct {
	Content string
}

MessageEndEvent fires when the assistant message is complete.

func (MessageEndEvent) Type

func (e MessageEndEvent) Type() EventType

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

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

Result is the interface satisfied by all result types internally.

type Runner

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

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

func NewRunner

func NewRunner(exts []LoadedExtension) *Runner

NewRunner creates a Runner from a set of loaded extensions.

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) 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 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) GetToolRenderer added in v0.2.0

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

GetToolRenderer returns the custom renderer for the named tool, or nil if no extension registered a renderer for it. If multiple extensions register renderers for the same tool, the last one (by load order) wins. Thread-safe (extensions are immutable after loading).

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

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

RegisteredCommands returns all slash commands registered by loaded extensions.

func (*Runner) RegisteredTools

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

RegisteredTools returns all custom tools registered by loaded extensions.

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

func (r *Runner) SetContext(ctx Context)

SetContext updates the runtime context (session ID, model, etc.) that is passed to every handler invocation. 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) 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.

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 ToolCallEvent

type ToolCallEvent struct {
	ToolName   string
	ToolCallID string
	Input      string // JSON-encoded tool parameters
}

ToolCallEvent fires before a tool executes.

func (ToolCallEvent) Type

func (e ToolCallEvent) Type() EventType

type ToolCallResult

type ToolCallResult struct {
	Block  bool
	Reason string
}

ToolCallResult controls whether the tool call proceeds.

type ToolDef

type ToolDef struct {
	Name        string
	Description string
	Parameters  string // JSON Schema string
	Execute     func(input string) (string, error)
}

ToolDef describes a custom tool registered by an extension.

type ToolExecutionEndEvent

type ToolExecutionEndEvent struct {
	ToolName string
}

ToolExecutionEndEvent fires when a tool finishes executing.

func (ToolExecutionEndEvent) Type

type ToolExecutionStartEvent

type ToolExecutionStartEvent struct {
	ToolName string
}

ToolExecutionStartEvent fires when a tool begins executing.

func (ToolExecutionStartEvent) Type

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. "bash", "read", "my-tool").
	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 {
	ToolName string
	Input    string
	Content  string
	IsError  bool
}

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 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.
	Text string

	// Markdown, when true, renders Text as styled markdown instead of
	// plain text.
	Markdown bool
}

WidgetContent describes what to render in a widget slot.

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