app

package
v0.96.3 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultNewSessionIdleWait = 10 * time.Minute

DefaultNewSessionIdleWait bounds how long RequestNewSessionFromExtension will block waiting for the agent to settle. It needs to be generous enough to cover real-world post-turn tooling (project formatters, on-save linters, hidden tool calls) which routinely hold the busy flag for seconds and occasionally minutes — yet still short enough to surface a wedged agent.

Issue #63 reported workloads where the busy window regularly exceeded 6 seconds; ten minutes is the same bound the workaround in that issue used.

Variables

View Source
var ErrAgentBusy = extensions.ErrAgentBusy

ErrAgentBusy is returned when an operation cannot proceed because the agent is still processing a turn (including any post-turn extension hooks) and did not become idle before the operation's deadline.

This is an alias for extensions.ErrAgentBusy so the extension API and the app layer share a single sentinel value — callers can detect the condition with errors.Is(err, app.ErrAgentBusy) without substring-matching the error message.

View Source
var ErrNoSession = errors.New("no tree session active")

ErrNoSession is returned by session mutation methods when no tree session is active. Callers that only need to know whether a session exists should prefer the ok result of SessionSnapshot.

View Source
var ErrSessionNotPersisted = errors.New("session is not persisted to disk")

ErrSessionNotPersisted is returned by operations that need the session's backing file when the active session exists only in memory.

Functions

This section is empty.

Types

type App

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

App is the application-layer orchestrator. It owns the agentic loop, conversation history (via MessageStore), and queue management. It is designed to be created once per session and reused across multiple prompts.

In interactive mode the caller creates a tea.Program and registers it via SetProgram; App then sends events to it as agent work progresses.

In non-interactive mode the caller uses RunOnce, which writes the response directly to an io.Writer.

App satisfies the ui.AppController interface defined in internal/ui/model.go:

Run(prompt string) int
CancelCurrentStep()
QueueLength() int
ClearQueue()
ClearMessages()

func New

func New(opts Options, initialMessages []kit.LLMMessage) *App

New creates a new App with the provided options and pre-loaded messages. initialMessages may be nil or empty for a fresh session.

func (*App) Abort added in v0.38.0

func (a *App) Abort()

Abort cancels the current agent step (if running) and clears the queue. Unlike InterruptAndSend, no new message is injected — the agent simply stops. Safe to call when idle (no-op).

func (*App) AddContextMessage added in v0.5.0

func (a *App) AddContextMessage(text string)

AddContextMessage adds a user-role message to the conversation history without triggering an LLM response. Used by the ! shell command prefix to inject command output into context so the LLM can reference it in subsequent turns.

Satisfies ui.AppController.

func (*App) CancelCurrentStep

func (a *App) CancelCurrentStep()

CancelCurrentStep cancels the currently executing agent step. Safe to call even when no step is running (it is a no-op in that case).

Satisfies ui.AppController.

func (*App) ClearMessages

func (a *App) ClearMessages()

ClearMessages empties the conversation history. When a tree session is active the leaf pointer is reset to the root, creating an implicit branch.

Satisfies ui.AppController.

func (*App) ClearQueue

func (a *App) ClearQueue()

ClearQueue discards all queued prompts. The caller is responsible for updating any UI state (e.g. queue badge) — ClearQueue does NOT send events to the program, because it may be called synchronously from within Bubble Tea's Update loop where prog.Send would deadlock.

Satisfies ui.AppController.

func (*App) Close

func (a *App) Close()

Close signals all background goroutines to stop and waits for them to finish. After Close() returns it is safe to call Kit.Close() / agent.Close().

func (*App) CompactAsync added in v0.38.0

func (a *App) CompactAsync(customInstructions string, onComplete func(), onError func(string)) error

CompactAsync is like CompactConversation but calls onComplete/onError callbacks instead of sending TUI events. Used by the extension API's ctx.Compact() which needs callback-based notification.

Like CompactConversation, any prompts/steer messages received during compaction are flushed automatically once compaction finishes.

func (*App) CompactConversation

func (a *App) CompactConversation(customInstructions string) error

CompactConversation summarises older messages to free context space. It returns an error synchronously if compaction cannot start (agent busy or app closed). The actual compaction runs in a background goroutine and delivers CompactCompleteEvent or CompactErrorEvent through the registered tea.Program. customInstructions is optional text appended to the summary prompt (e.g. "Focus on the API design decisions").

Any prompts queued via Run/RunWithFiles or steering messages injected via Steer/SteerWithFiles while compaction is running are flushed automatically once compaction completes (see releaseBusyAfterCompact).

Satisfies ui.AppController.

func (*App) DeleteSession added in v0.94.0

func (a *App) DeleteSession(path string) error

DeleteSession removes a session file from disk. Deleting the file backing the active session is permitted: the session keeps running in memory and simply stops being discoverable.

func (*App) ExportSession added in v0.94.0

func (a *App) ExportSession(dstPath string) (string, int, error)

ExportSession copies the active session's JSONL file to dstPath. When dstPath is empty, a name is derived from the session's display name (or a short form of its ID when unnamed) and written to the process's working directory.

It returns the path written and the number of bytes copied. Returns ErrNoSession when no tree session is active, and ErrSessionNotPersisted when the session exists only in memory and so has nothing to copy.

func (*App) ForkSession added in v0.94.0

func (a *App) ForkSession(cwd, targetID string) error

ForkSession creates a new session in cwd containing the history up to and including targetID, then switches to it. The original session is left untouched on disk. Returns ErrNoSession when no tree session is active.

func (*App) GetTreeSession

func (a *App) GetTreeSession() *session.TreeManager

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

func (*App) InterruptAndSend added in v0.24.0

func (a *App) InterruptAndSend(prompt string)

InterruptAndSend cancels the current agent step (if running), clears the queue, and sends a new message that will execute as soon as the current step finishes cancelling. If the agent is idle, the message executes immediately. This is the hard-cancel delivery mode used by extensions' CancelAndSend.

func (*App) IsBusy added in v0.38.0

func (a *App) IsBusy() bool

IsBusy returns true when the agent is currently processing a turn.

func (*App) ListAllSessions added in v0.94.0

func (a *App) ListAllSessions() ([]SessionSummary, error)

ListAllSessions returns summaries of every session across all working directories, newest first.

func (*App) ListSessions added in v0.94.0

func (a *App) ListSessions(cwd string) ([]SessionSummary, error)

ListSessions returns summaries of the sessions recorded for cwd, newest first. An empty cwd yields no sessions rather than an error, so callers can pass through an unknown working directory unconditionally.

func (*App) NewSession added in v0.94.0

func (a *App) NewSession(cwd string) error

NewSession replaces the active tree session with a brand new one created in cwd, closing and flushing the old session. The in-memory message store is reset to the (empty) new session.

Returns ErrNoSession when no tree session is active — callers that want to support the session-less mode should check SessionSnapshot first and clear their own state instead.

func (*App) NotifyContentReload added in v0.41.0

func (a *App) NotifyContentReload()

NotifyContentReload sends a ContentReloadEvent to the TUI so it refreshes prompt templates and skills from their provider callbacks. Called by file watchers when .md/.txt files change in prompt or skill directories. In non-interactive mode this is a no-op.

func (*App) NotifyMCPServerLoaded added in v0.41.2

func (a *App) NotifyMCPServerLoaded(serverName string, toolCount int, err error)

NotifyMCPServerLoaded sends an MCPServerLoadedEvent to the TUI so it can display a system message when a single MCP server finishes loading. Called per server as background MCP tool loading progresses.

func (*App) NotifyMCPToolsReady added in v0.41.2

func (a *App) NotifyMCPToolsReady()

NotifyMCPToolsReady sends an MCPToolsReadyEvent to the TUI so it refreshes tool names and MCP tool count from provider callbacks. Called when background MCP tool loading completes. In non-interactive mode this is a no-op.

func (*App) NotifyModelChanged added in v0.3.0

func (a *App) NotifyModelChanged(provider, model string)

NotifyModelChanged sends a ModelChangedEvent to the TUI so it updates the model name in the status bar and message attribution.

func (*App) NotifyThemeChange added in v0.93.0

func (a *App) NotifyThemeChange()

NotifyThemeChange sends a ThemeChangedEvent to the TUI so components holding theme-derived styling repaint. Called after the active theme is replaced from outside the TUI, such as by an extension's ctx.SetTheme. In non-interactive mode this is a no-op.

func (*App) NotifyWidgetUpdate added in v0.2.0

func (a *App) NotifyWidgetUpdate()

NotifyWidgetUpdate sends a WidgetUpdateEvent to the TUI so it re-renders extension widgets. Called from the extension context's SetWidget/RemoveWidget closures. In non-interactive mode this is a no-op (widgets are TUI-only).

Coalescing (leading + trailing edge): the first call in an idle period fires immediately for responsiveness. Subsequent calls within a ~16 ms debounce window are batched into a single trailing event delivered at the end of the window. The trailing send is essential for correctness: extensions routinely make tight SetWidget→RemoveWidget pairs (e.g. on SubagentEnd) and silently dropping the second call would leave the TUI's layout stuck on stale widget dimensions until some other event happens to trigger a re-render.

func (*App) PopLastUserMessage added in v0.74.0

func (a *App) PopLastUserMessage() (string, []kit.LLMFilePart, error)

PopLastUserMessage truncates the tree session back to the parent of the most recent user message on the current branch, syncs the in-memory message store, and returns the user prompt text plus any image file parts so the caller can resubmit via Run/RunWithFiles.

This is the building block for /retry: the user message and any orphaned assistant/tool entries produced by a failed turn become unreachable on the current branch (they remain in the session file under a different leaf) and are excluded from the next LLM context.

Returns an error when:

  • the agent is currently working (busy)
  • the app has been closed
  • no tree session is active (sessions disabled via --no-session)
  • no user message exists on the current branch

Satisfies ui.AppController.

func (*App) PrintBlockFromExtension

func (a *App) PrintBlockFromExtension(opts extensions.PrintBlockOpts)

PrintBlockFromExtension outputs a custom styled block from an extension.

func (*App) PrintFromExtension

func (a *App) PrintFromExtension(level, text string)

PrintFromExtension outputs text from an extension to the user. The level controls styling: "" for plain text, "info" for a system message block, "error" for an error block. In interactive mode it sends an ExtensionPrintEvent through the program so the TUI can render it with the appropriate renderer. In non-interactive mode it falls back to stderr with a level prefix so errors are distinguishable from plain output.

func (*App) QueueLength

func (a *App) QueueLength() int

QueueLength returns the number of prompts currently waiting in the queue.

Satisfies ui.AppController.

func (*App) QuitFromExtension added in v0.3.0

func (a *App) QuitFromExtension()

QuitFromExtension triggers a graceful shutdown. In interactive mode it sends a tea.QuitMsg to the program so the TUI exits cleanly. In non-interactive mode it cancels the root context, stopping any in-flight step. Safe to call from any goroutine; idempotent.

func (*App) ReloadMessagesFromTree added in v0.30.0

func (a *App) ReloadMessagesFromTree()

ReloadMessagesFromTree clears the in-memory message store and reloads it from the tree session's current branch. Unlike ClearMessages, this does NOT reset the tree session's leaf pointer. Used after Branch() to sync the store with the new branch position.

func (*App) RequestNewSessionFromExtension added in v0.79.0

func (a *App) RequestNewSessionFromExtension(initialPrompt string) error

RequestNewSessionFromExtension sends a NewSessionRequestEvent to the TUI to end the current session and start a fresh one. If initialPrompt is non-empty it is submitted as the first user turn of the new session.

If the agent is currently busy (e.g. the caller is an OnAgentEnd hook that fires before drainQueue clears the busy flag, or there are queued prompts still being processed) the call blocks until the agent becomes idle, up to DefaultNewSessionIdleWait. If that deadline elapses, ErrAgentBusy is returned and callers can detect it with errors.Is. This wait-then-send behavior fixes the v0.79.0 phase-handoff race documented in issue #63.

Returns an error when running headless (no TUI attached), when the wait for idle times out (ErrAgentBusy), when the app is shutting down, or when a BeforeSessionSwitch extension hook cancels the switch.

This is the implementation behind ctx.NewSession(prompt) for the interactive TUI. It blocks the caller until the TUI processes the switch, so it must be invoked from a goroutine outside Update().

func (*App) Run

func (a *App) Run(prompt string) int

Run queues a prompt for execution. If the app is idle the prompt is executed immediately in a background goroutine; otherwise it is appended to the queue.

Returns the current queue depth after the operation: 0 means the prompt was started immediately (or the app is closed), >0 means it was queued. The caller is responsible for updating any UI state (e.g. queue badge) based on the returned value — Run does NOT send events to the program, because it may be called synchronously from within Bubble Tea's Update loop where prog.Send would deadlock.

Satisfies ui.AppController.

func (*App) RunOnce

func (a *App) RunOnce(ctx context.Context, prompt string) error

RunOnce executes a single agent step synchronously and prints the final response text to stdout. No intermediate events are emitted. Blocks until the step completes or ctx is cancelled.

func (*App) RunOnceResult added in v0.3.0

func (a *App) RunOnceResult(ctx context.Context, prompt string) (*kit.TurnResult, error)

RunOnceResult executes a single agent step synchronously and returns the full TurnResult without printing anything. This is used by --json mode to capture structured output for serialization.

func (*App) RunOnceResultWithFiles added in v0.51.0

func (a *App) RunOnceResultWithFiles(ctx context.Context, prompt string, files []kit.LLMFilePart) (*kit.TurnResult, error)

RunOnceResultWithFiles executes a single agent step synchronously with optional multimodal file attachments and returns the full TurnResult.

func (*App) RunOnceWithDisplay

func (a *App) RunOnceWithDisplay(ctx context.Context, prompt string, eventFn func(Event)) error

RunOnceWithDisplay executes a single agent step synchronously, sending intermediate display events (spinner, tool calls, streaming chunks, etc.) to eventFn. This is the non-TUI equivalent of the interactive Run() path — used by non-interactive --prompt mode when output is needed.

The eventFn receives the same event types as the Bubble Tea TUI (SpinnerEvent, ToolCallStartedEvent, StreamChunkEvent, StepCompleteEvent, etc.) and is responsible for rendering them.

Blocks until the step completes or ctx is cancelled.

func (*App) RunOnceWithDisplayAndFiles added in v0.51.0

func (a *App) RunOnceWithDisplayAndFiles(ctx context.Context, prompt string, eventFn func(Event), files []kit.LLMFilePart) error

RunOnceWithDisplayAndFiles executes a single agent step synchronously with optional multimodal file attachments, sending intermediate display events.

func (*App) RunOnceWithFiles added in v0.51.0

func (a *App) RunOnceWithFiles(ctx context.Context, prompt string, files []kit.LLMFilePart) error

RunOnceWithFiles executes a single agent step synchronously with optional multimodal file attachments. Prints the response to stdout and returns.

func (*App) RunWithFiles added in v0.7.0

func (a *App) RunWithFiles(prompt string, files []kit.LLMFilePart) int

RunWithFiles queues a multimodal prompt (text + image files) for execution. If the app is idle the prompt executes immediately; otherwise it is queued. Returns the current queue depth (0 = started immediately, >0 = queued).

Satisfies ui.AppController.

func (*App) SendOverlayRequest added in v0.2.0

func (a *App) SendOverlayRequest(evt OverlayRequestEvent)

SendOverlayRequest sends an OverlayRequestEvent to the TUI so the user can interact with a modal overlay dialog. In non-interactive mode (no program registered) it immediately responds with a cancelled result via the channel, ensuring the calling extension goroutine never blocks indefinitely.

func (*App) SendPromptRequest added in v0.2.0

func (a *App) SendPromptRequest(evt PromptRequestEvent)

SendPromptRequest sends a PromptRequestEvent to the TUI so the user can respond interactively. In non-interactive mode (no program registered) it immediately responds with a cancelled result via the channel, ensuring the calling extension goroutine never blocks indefinitely.

func (*App) SendUIMessage added in v0.94.0

func (a *App) SendUIMessage(msg tea.Msg)

SendUIMessage forwards a display-layer message straight to the registered program. Safe to call from any goroutine; a no-op when no program is registered.

Unlike the app's own Event fan-out, this is a transport escape hatch for the UI to re-inject its own internal messages (goroutine results that must reach the Bubble Tea Update loop without going through a stalling tea.Cmd). The app treats the payload as opaque and does not interpret it.

Satisfies ui.AppController.

func (*App) SessionHistory added in v0.94.0

func (a *App) SessionHistory() []message.Message

SessionHistory returns the conversation messages on the session's current branch, oldest first. Entries that are not messages, and messages that fail to decode, are skipped. Returns nil when no tree session is active.

This is what the UI replays to rebuild the transcript after resuming or forking a session.

func (*App) SessionSnapshot added in v0.94.0

func (a *App) SessionSnapshot() (SessionSnapshot, bool)

SessionSnapshot returns a value snapshot of the active tree session's metadata. ok is false when no tree session is configured, in which case the returned snapshot is the zero value.

func (*App) SessionTree added in v0.94.0

func (a *App) SessionTree() []TreeNodeView

SessionTree returns the session's entry tree projected into value nodes, rooted at the entries with no parent. Returns nil when no tree session is active.

The projection is a deep copy taken under the session's read lock, so the result is safe to hold and walk while the session keeps mutating.

func (*App) SetEditorTextFromExtension added in v0.3.0

func (a *App) SetEditorTextFromExtension(text string)

SetEditorTextFromExtension sends an EditorTextSetEvent to the TUI to pre-fill the input editor. In non-interactive mode this is a no-op.

func (*App) SetProgram

func (a *App) SetProgram(p *tea.Program)

SetProgram registers the Bubble Tea program used to send events in interactive mode. Must be called before Run() in interactive mode.

func (*App) SetSessionName added in v0.94.0

func (a *App) SetSessionName(name string) error

SetSessionName sets the session's display name, persisting it as a session_info entry. Returns ErrNoSession when no tree session is active.

func (*App) Steer added in v0.3.0

func (a *App) Steer(prompt string) int

Steer injects a steering message into the currently running agent turn. If the agent is in a multi-step tool loop, the message is delivered after the current tool execution finishes but before the next LLM call (graceful mid-turn injection via Fantasy's PrepareStep). If the agent is streaming a text-only response (no pending tool calls), the message waits until the response completes and then executes as the next turn.

If the agent is idle, the message starts executing immediately (same as Run).

Returns the number of pending steer/queue items (0 = started immediately, >0 = injected/queued). The caller must update UI state based on the return value — Steer does NOT send events to the program to avoid deadlocking when called from within Update().

Satisfies ui.AppController.

func (*App) SteerWithFiles added in v0.36.0

func (a *App) SteerWithFiles(prompt string, files []kit.LLMFilePart) int

SteerWithFiles injects a steering message with optional file attachments (e.g. pasted images) into the currently running agent turn. Behaves like Steer but includes file parts alongside the text.

Satisfies ui.AppController.

func (*App) SuspendTUI added in v0.3.0

func (a *App) SuspendTUI(callback func()) error

SuspendTUI temporarily releases the terminal from the TUI, runs the callback (which may spawn interactive subprocesses), and then restores the TUI. In non-interactive mode (no program registered) the callback runs directly with no terminal state changes.

Safe to call from any goroutine (extension command handlers run in goroutines). Blocks until the callback returns.

func (*App) SwitchTreeSession added in v0.16.0

func (a *App) SwitchTreeSession(ts *session.TreeManager)

SwitchTreeSession replaces the active tree session with a new one and reloads the in-memory message store from the new session's messages. The old tree session is closed. Used by /resume to switch sessions.

func (*App) WaitForIdle added in v0.79.1

func (a *App) WaitForIdle(timeout time.Duration) error

WaitForIdle blocks until the agent is idle, the given timeout elapses, or the app shuts down. Returns nil on idle, ErrAgentBusy on timeout, or the rootCtx error if the app is closing.

A non-positive timeout disables the deadline and waits indefinitely (until idle or app shutdown). Safe to call from any goroutine, but never from inside the Bubble Tea Update() loop — it blocks.

Idiomatic use from extensions:

if err := app.WaitForIdle(0); err != nil { /* shutdown */ }

The loop guards against the agent re-arming itself between wakeups: if another prompt is queued (or a steer message lands) while we're waiting, setBusyLocked allocates a fresh idleCh and we wait again.

func (*App) WriteShareableSession added in v0.94.0

func (a *App) WriteShareableSession(systemPrompt, fallbackModelID string) (string, error)

WriteShareableSession writes a shareable copy of the active session to a temporary file and returns its path. The copy is the session's JSONL with a system-prompt entry inserted directly after the header, so whoever reads the shared file can see the system prompt and model the conversation ran under. fallbackModelID is used when the session records no model of its own.

The caller owns the returned file and is responsible for removing it. On error no file is left behind. Returns ErrNoSession when no tree session is active and ErrSessionNotPersisted when the session is in-memory.

type CompactCompleteEvent

type CompactCompleteEvent struct {
	// Summary is the LLM-generated structured summary of the compacted messages.
	Summary string
	// OriginalTokens is the estimated token count before compaction.
	OriginalTokens int
	// CompactedTokens is the estimated token count after compaction.
	CompactedTokens int
	// MessagesRemoved is the number of messages that were summarised away.
	MessagesRemoved int
}

CompactCompleteEvent is sent when a /compact operation finishes successfully. It carries the summary text and before/after statistics.

type CompactErrorEvent

type CompactErrorEvent struct {
	// Err is the error that caused compaction to fail.
	Err error
}

CompactErrorEvent is sent when a /compact operation fails.

type ContentReloadEvent added in v0.41.0

type ContentReloadEvent struct{}

ContentReloadEvent is sent when prompt templates or skills are reloaded from disk (e.g. by a file watcher detecting changes). The TUI refreshes its autocomplete entries and internal state from the provider callbacks.

type EditorTextSetEvent added in v0.3.0

type EditorTextSetEvent struct {
	Text string
}

EditorTextSetEvent is sent when an extension calls ctx.SetEditorText to pre-fill the input editor with text. The TUI handles this by setting the textarea content and moving the cursor to the end.

type EntryKind added in v0.94.0

type EntryKind string

EntryKind classifies a session tree entry without exposing the concrete persistence types from internal/session.

Presentation layers switch on EntryKind instead of type-switching on *session.MessageEntry and friends, so the on-disk entry schema can evolve without breaking every consumer. Unrecognised entries carry EntryKindUnknown; consumers should always handle it.

const (
	// EntryKindUnknown is used for entries the app layer does not recognise.
	EntryKindUnknown EntryKind = ""
	// EntryKindMessage is a conversation message (user, assistant or tool).
	EntryKindMessage EntryKind = "message"
	// EntryKindModelChange records a provider/model switch.
	EntryKindModelChange EntryKind = "model_change"
	// EntryKindBranchSummary carries a summary of an abandoned branch.
	EntryKindBranchSummary EntryKind = "branch_summary"
	// EntryKindLabel bookmarks another entry with a user-defined label.
	EntryKindLabel EntryKind = "label"
	// EntryKindSessionInfo records the session's display name.
	EntryKindSessionInfo EntryKind = "session_info"
	// EntryKindExtensionData holds extension-defined persisted state.
	EntryKindExtensionData EntryKind = "extension_data"
	// EntryKindCompaction records an LLM-generated summary of older messages.
	EntryKindCompaction EntryKind = "compaction"
	// EntryKindSystemPrompt captures the system prompt used for a session.
	EntryKindSystemPrompt EntryKind = "system_prompt"
)

type Event added in v0.94.0

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

Event is the sealed union of all events the app layer emits toward a display (the Bubble Tea TUI, the non-interactive CLI handler, or any future transport). Every event type defined in this file implements Event via an unexported marker method. Because that marker is unexported, only types declared in this package can satisfy Event — the union is closed to external implementations.

Note that Go does not check type-switch exhaustiveness for this pattern: adding a new Event variant will not produce a compile error at downstream switches, so those switches should keep a default case (or the package a sum-type linter) to stay safe.

Keeping the fan-out typed as Event (rather than Bubble Tea's untyped tea.Msg) means the app package no longer needs to speak the TUI's message vocabulary to describe its own events. The concrete transport (prog.Send, a CLI callback) adapts Event at the boundary; the event-producing code stays TUI-agnostic.

Note that some events still carry a response channel (PasswordPromptEvent, PromptRequestEvent, OverlayRequestEvent, NewSessionRequestEvent). Those are not yet serialisable across a process boundary; converting them to a request-id correlation scheme is deferred until an actual out-of-process transport exists.

type ExtensionPrintEvent

type ExtensionPrintEvent struct {
	// Text is the content the extension wants to display to the user.
	Text string
	// Level controls the rendering style:
	//   ""      — plain text (no styling)
	//   "info"  — system message block (bordered, themed)
	//   "error" — error block (red border, bold text)
	//   "block" — custom block with BorderColor and Subtitle
	Level string
	// BorderColor is a hex color (e.g. "#a6e3a1") for Level="block".
	BorderColor string
	// Subtitle is optional muted text below the content for Level="block".
	Subtitle string
}

ExtensionPrintEvent is sent when an extension calls ctx.Print, ctx.PrintInfo, ctx.PrintError, or ctx.PrintBlock. The TUI renders it via the appropriate renderer and tea.Println (scrollback); the CLI handler uses DisplayInfo/DisplayError or plain fmt.Println. This exists because BubbleTea captures stdout, so plain fmt.Println inside extensions would be swallowed.

type MCPServerLoadedEvent added in v0.41.2

type MCPServerLoadedEvent struct {
	ServerName string
	ToolCount  int
	Error      error // nil on success
}

MCPServerLoadedEvent is sent when a single MCP server finishes loading (successfully or with error). The TUI displays a system message so users see real-time progress as each server initializes.

type MCPToolsReadyEvent added in v0.41.2

type MCPToolsReadyEvent struct{}

MCPToolsReadyEvent is sent when background MCP tool loading completes. The TUI refreshes its tool names and MCP tool count from provider callbacks so that /tools and the startup info bar reflect the loaded MCP tools.

type MessageCreatedEvent

type MessageCreatedEvent struct {
	// Message is the message that was added to the store.
	Message kit.LLMMessage
}

MessageCreatedEvent is sent when a new message is added to the message store. This allows the TUI to stay in sync with the conversation history.

type MessageStore

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

MessageStore is a thread-safe in-memory store for the conversation history. On-disk persistence is handled by the TreeManager at the app/SDK layer.

func NewMessageStoreWithMessages

func NewMessageStoreWithMessages(msgs []kit.LLMMessage) *MessageStore

NewMessageStoreWithMessages creates a MessageStore pre-populated with the given messages. This is used when loading an existing session at startup.

func (*MessageStore) Add

func (s *MessageStore) Add(msg kit.LLMMessage)

Add appends a single message to the store.

func (*MessageStore) Clear

func (s *MessageStore) Clear()

Clear removes all messages from the store.

func (*MessageStore) GetAll

func (s *MessageStore) GetAll() []kit.LLMMessage

GetAll returns a snapshot copy of the current message slice. The returned slice is safe to modify without affecting the store.

func (*MessageStore) Len

func (s *MessageStore) Len() int

Len returns the number of messages currently in the store.

func (*MessageStore) Replace

func (s *MessageStore) Replace(msgs []kit.LLMMessage)

Replace replaces the entire message history with the given slice. This is used after an agent step returns the full updated conversation (including tool calls and results).

type ModelChangedEvent added in v0.3.0

type ModelChangedEvent struct {
	// ProviderName is the new provider (e.g. "anthropic").
	ProviderName string
	// ModelName is the new model ID (e.g. "claude-3-5-haiku-20241022").
	ModelName string
}

ModelChangedEvent is sent when an extension changes the active model via ctx.SetModel. The TUI updates the model name shown in the status bar and message attribution.

type NewSessionRequestEvent added in v0.79.0

type NewSessionRequestEvent struct {
	// InitialPrompt, when non-empty, is the first user turn to submit
	// after the session switch. @file references are expanded.
	InitialPrompt string
	// ResponseCh receives the outcome (nil error on success). Must be
	// buffered (cap >= 1) so the TUI never blocks. May be nil if the
	// caller does not need the result.
	ResponseCh chan<- error
}

NewSessionRequestEvent is sent when an extension calls ctx.NewSession to end the current session and start a fresh one. The TUI routes this into the same /new code path (including the BeforeSessionSwitch hook and any @file expansion in InitialPrompt). ResponseCh, when non-nil, receives a single result so the extension goroutine can observe success or failure.

type Options

type Options struct {
	// Kit is the SDK instance. executeStep() delegates to kit.PromptResult()
	// and events flow through SDK subscriptions. Required in production;
	// tests may use PromptFunc instead.
	Kit *kit.Kit

	// PromptFunc overrides Kit.PromptResult for testing. When set,
	// executeStep calls this directly, bypassing SDK event subscription
	// and usage tracking. Must not be set in production.
	PromptFunc func(ctx context.Context, prompt string) (*kit.TurnResult, error)

	// TreeSession is the tree-structured JSONL session manager. When non-nil,
	// conversation history is persisted as an append-only JSONL tree and tree
	// navigation (/tree, /fork) is enabled.
	TreeSession *session.TreeManager

	// MCPConfig is the full MCP configuration used for session continuation and
	// slash command resolution.
	MCPConfig *config.Config

	// ModelName is the display name of the model (e.g. "claude-sonnet-4-5").
	ModelName string

	// ServerNames holds the names of loaded MCP servers, used for slash command
	// autocomplete.
	ServerNames []string

	// ToolNames holds the names of available tools, used for slash command
	// autocomplete.
	ToolNames []string

	// StreamingEnabled controls whether the agent uses streaming responses.
	StreamingEnabled bool

	// Quiet suppresses all output except the final response (non-interactive mode).
	Quiet bool

	// Debug enables verbose debug logging.
	Debug bool

	// UsageTracker is an optional callback for recording token usage after each
	// agent step. When non-nil, the app layer calls UpdateUsage (or
	// EstimateAndUpdateUsage as a fallback) using the usage data returned by the
	// agent. Satisfied by *ui.UsageTracker; wired in cmd/root.go.
	UsageTracker UsageUpdater
}

Options configures an App instance.

type OverlayRequestEvent added in v0.2.0

type OverlayRequestEvent struct {
	// Title is displayed at the top of the dialog. Empty means no title.
	Title string
	// Content is the text to render inside the dialog body.
	Content string
	// Markdown, when true, renders Content as styled markdown.
	Markdown bool
	// BorderColor is a hex color for the dialog border. Empty uses default.
	BorderColor string
	// Background is a hex color for the dialog background. Empty = none.
	Background string
	// Width is the dialog width in columns. 0 = auto (60% of terminal).
	Width int
	// MaxHeight limits dialog height. 0 = auto (80% of terminal).
	MaxHeight int
	// Anchor is the vertical positioning: "center", "top-center", "bottom-center".
	Anchor string
	// Actions lists the action button labels. Empty = simple dismiss dialog.
	Actions []string
	// ResponseCh receives the user's response. Must have buffer size >= 1.
	ResponseCh chan<- OverlayResponse
}

OverlayRequestEvent is sent when an extension requests a modal overlay dialog. The TUI enters an overlay state, renders the dialog, and sends a single OverlayResponse through ResponseCh when the user dismisses or selects an action.

The extension goroutine blocks on the read side of ResponseCh until the TUI sends a response. The channel must have buffer size >= 1.

type OverlayResponse added in v0.2.0

type OverlayResponse struct {
	// Action is the text of the selected action button, 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 overlay (ESC) or the
	// overlay could not be shown (e.g. non-interactive mode).
	Cancelled bool
}

OverlayResponse carries the user's answer to a modal overlay dialog. The TUI sends exactly one OverlayResponse through the channel embedded in OverlayRequestEvent when the user completes or cancels the overlay.

type PasswordPromptEvent added in v0.53.0

type PasswordPromptEvent struct {
	// Prompt is the message to display to the user.
	Prompt string
	// ResponseCh receives the password from the TUI.
	// The TUI must send exactly one value.
	ResponseCh chan<- PasswordPromptResponse
}

PasswordPromptEvent is sent when a sudo command needs a password. The TUI should display a password prompt overlay and send the result back.

type PasswordPromptResponse added in v0.53.0

type PasswordPromptResponse struct {
	// Password is the entered password.
	Password string
	// Cancelled is true if the user cancelled the prompt.
	Cancelled bool
}

PasswordPromptResponse carries the user's password input.

type PromptRequestEvent added in v0.2.0

type PromptRequestEvent struct {
	// PromptType is "select", "multiselect", "confirm", or "input".
	PromptType string
	// Message is the question displayed to the user.
	Message string
	// Options lists the choices for select and multiselect prompts.
	Options []string
	// DefaultSelected holds the indices pre-selected when a multiselect
	// prompt opens. A nil slice selects every option.
	DefaultSelected []int
	// Default is the pre-filled value: "true"/"false" for confirm prompts,
	// or the initial text for input prompts.
	Default string
	// Placeholder is the ghost text for input prompts.
	Placeholder string
	// ResponseCh receives the user's answer. The TUI must send exactly one
	// value. The channel must be buffered (cap >= 1) so sending never
	// blocks inside Update().
	ResponseCh chan<- PromptResponse
}

PromptRequestEvent is sent when an extension requests an interactive prompt from the user (select, multiselect, confirm, or text input). The TUI enters a modal prompt state, renders the prompt, and sends a single PromptResponse through ResponseCh when the user completes or cancels.

The extension goroutine blocks on the read side of ResponseCh until the TUI sends a response. The channel must have buffer size >= 1.

type PromptResponse added in v0.2.0

type PromptResponse struct {
	// Value is the response text — the selected option (select), or the
	// entered text (input). Unused for confirm prompts.
	Value string
	// Index is the zero-based index of the selected option (select only).
	Index int
	// Values holds the text of every selected option (multiselect only).
	Values []string
	// Indices holds the zero-based index of every selected option
	// (multiselect only).
	Indices []int
	// Confirmed is the boolean answer for confirm prompts.
	Confirmed bool
	// Cancelled is true if the user dismissed the prompt (ESC) or the
	// prompt could not be shown (e.g. app shutting down).
	Cancelled bool
}

PromptResponse carries the user's answer to an interactive prompt. The TUI sends exactly one PromptResponse through the channel embedded in PromptRequestEvent when the user completes or cancels the prompt.

type QueueUpdatedEvent

type QueueUpdatedEvent struct {
	// Length is the current number of messages waiting in the queue.
	Length int
}

QueueUpdatedEvent is sent whenever the message queue length changes. The TUI uses this to update the queue badge display.

type ReasoningChunkEvent added in v0.7.0

type ReasoningChunkEvent struct {
	// Delta is the incremental reasoning text from the streaming response.
	Delta string
}

ReasoningChunkEvent is sent when a streaming reasoning/thinking delta arrives from the LLM. Thinking content is rendered separately from regular text.

type ReasoningCompleteEvent added in v0.35.0

type ReasoningCompleteEvent struct{}

ReasoningCompleteEvent is sent when reasoning/thinking is finished, after the last reasoning token has been processed. The TUI uses this to freeze the reasoning duration counter.

type ResponseCompleteEvent

type ResponseCompleteEvent struct {
	// Content is the complete final response text.
	Content string
}

ResponseCompleteEvent is sent when the LLM produces a final (non-streaming) response. In streaming mode, this may be empty if all content was delivered via StreamChunkEvents.

type SessionSnapshot added in v0.94.0

type SessionSnapshot struct {
	// ID is the session UUID.
	ID string
	// Name is the user-defined display name, empty if unnamed.
	Name string
	// FilePath is the JSONL file backing the session, empty when in-memory.
	FilePath string
	// Cwd is the working directory the session was created in.
	Cwd string
	// Created is the session creation timestamp.
	Created time.Time
	// LeafID is the current position in the entry tree.
	LeafID string
	// EntryCount is the total number of entries in the session.
	EntryCount int
	// MessageCount is the number of message entries in the session.
	MessageCount int
	// Persisted reports whether the session is backed by a file on disk.
	Persisted bool
}

SessionSnapshot is a point-in-time value view of the active tree session's metadata. It is a copy: mutating it has no effect on the session, and it does not go stale in a way that can corrupt state — callers re-read it whenever they need current values.

type SessionSummary added in v0.94.0

type SessionSummary struct {
	// Path is the absolute path to the JSONL file backing the session.
	Path string
	// ID is the session UUID.
	ID string
	// Name is the user-defined display name, empty if unnamed.
	Name string
	// Cwd is the working directory the session was created in.
	Cwd string
	// Created is the session creation timestamp.
	Created time.Time
	// Modified is the timestamp of the most recent activity.
	Modified time.Time
	// MessageCount is the number of message entries in the session.
	MessageCount int
	// FirstMessage is a preview of the first user message, empty when the
	// session holds no user messages.
	FirstMessage string
}

SessionSummary is an immutable value description of a session stored on disk. It carries what a session picker needs to identify, search, sort and render a session without opening the file or knowing the JSONL schema.

It is deliberately narrower than the on-disk metadata: fields are added here as presentation layers need them, so the persistence format stays free to change.

type SpinnerEvent

type SpinnerEvent struct {
	// Show is true to display the spinner and false to hide it.
	Show bool
}

SpinnerEvent is sent to show or hide the spinner animation in the stream component. The spinner is shown before the first streaming chunk arrives and hidden once content begins flowing or the step completes.

type SteerConsumedEvent added in v0.24.0

type SteerConsumedEvent struct{}

SteerConsumedEvent is sent when one or more steering messages have been consumed — either injected mid-turn via PrepareStep, or drained into the queue after a turn completes. The TUI uses this to clear the steering badge from the display.

type StepCancelledEvent

type StepCancelledEvent struct{}

StepCancelledEvent is sent when an agent step is cancelled by the user (e.g. via double-ESC). The TUI should flush any partially streamed content, cut off the agent message where it was, and return to input state without displaying an error.

type StepCompleteEvent

type StepCompleteEvent struct {
	// ResponseText is the final assistant response text.
	ResponseText string
}

StepCompleteEvent is sent when an agent step finishes successfully.

type StepErrorEvent

type StepErrorEvent struct {
	// Err is the error that caused the step to fail.
	Err error
}

StepErrorEvent is sent when an agent step fails with an error. The TUI should display the error inline and transition back to input state.

type StreamChunkEvent

type StreamChunkEvent struct {
	// Content is the incremental text delta from the streaming response.
	Content string
}

StreamChunkEvent is sent by the app layer when a streaming text delta arrives from the LLM. Each chunk contains an incremental portion of the response.

type ThemeChangedEvent added in v0.93.0

type ThemeChangedEvent struct{}

ThemeChangedEvent is sent when the active color theme is replaced from outside the TUI's own /theme command — an extension calling ctx.SetTheme, for instance. Components that memoize theme-derived styling repaint themselves when they see it.

type ToolCallContentEvent

type ToolCallContentEvent struct {
	// Content is the assistant text that accompanies one or more tool calls.
	Content string
}

ToolCallContentEvent is sent when a step includes text content alongside tool calls. This allows the TUI to display assistant commentary that accompanies tool usage.

type ToolCallInputDeltaEvent added in v0.58.0

type ToolCallInputDeltaEvent struct {
	// ToolCallID is the stable identifier for correlating tool lifecycle events.
	ToolCallID string
	// Delta is a JSON fragment of tool call arguments.
	Delta string
}

ToolCallInputDeltaEvent is sent for each streamed fragment of tool call arguments as they arrive from the LLM. Useful for live-previewing content or showing a progress indicator with byte count.

type ToolCallInputEndEvent added in v0.58.0

type ToolCallInputEndEvent struct {
	// ToolCallID is the stable identifier for correlating tool lifecycle events.
	ToolCallID string
}

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

type ToolCallInputStartEvent added in v0.58.0

type ToolCallInputStartEvent struct {
	// ToolCallID is the stable identifier for correlating tool lifecycle events.
	ToolCallID string
	// ToolName is the name of the tool being called.
	ToolName string
	// ToolKind classifies the tool: "execute", "edit", "read", "search", "agent".
	ToolKind string
}

ToolCallInputStartEvent is sent when the LLM begins generating tool call arguments. The tool name is known but the full argument JSON is still being streamed. UIs can use this to show a "running" indicator immediately instead of waiting for the full argument JSON to finish streaming.

type ToolCallStartedEvent

type ToolCallStartedEvent struct {
	// ToolCallID is the stable identifier for correlating tool lifecycle events.
	ToolCallID string
	// ToolName is the name of the tool being called.
	ToolName string
	// ToolArgs is the JSON-encoded arguments for the tool call.
	ToolArgs string
}

ToolCallStartedEvent is sent when a tool call has been parsed and is about to execute. It carries the tool name and its arguments for display purposes.

type ToolExecutionEvent

type ToolExecutionEvent struct {
	// ToolCallID is the stable identifier for correlating tool lifecycle events.
	ToolCallID string
	// ToolName is the name of the tool being executed.
	ToolName string
	// ToolArgs is the JSON-encoded arguments for the tool call (only set when IsStarting is true).
	ToolArgs string
	// IsStarting is true when execution is beginning, false when it is complete.
	IsStarting bool
}

ToolExecutionEvent is sent when a tool starts or finishes executing. The IsStarting flag distinguishes between the start and end of execution.

type ToolOutputEvent added in v0.20.0

type ToolOutputEvent struct {
	// ToolCallID is the stable identifier for the tool call producing output.
	ToolCallID string
	// ToolName is the name of the tool producing output.
	ToolName string
	// Chunk is a piece of the tool's output text.
	Chunk string
	// IsStderr indicates whether this chunk came from stderr.
	IsStderr bool
}

ToolOutputEvent is sent when a tool produces streaming output chunks (e.g., bash output). This allows the TUI to display tool output as it arrives, before the tool completes.

type ToolResultEvent

type ToolResultEvent struct {
	// ToolCallID is the stable identifier for correlating tool lifecycle events.
	ToolCallID string
	// ToolName is the name of the tool that was executed.
	ToolName string
	// ToolArgs is the JSON-encoded arguments that were passed to the tool.
	ToolArgs string
	// Result is the text output from the tool execution.
	Result string
	// IsError indicates whether the tool returned an error result.
	IsError bool
}

ToolResultEvent is sent after a tool execution completes with its result.

type TreeNodeView added in v0.94.0

type TreeNodeView struct {
	// ID is the entry ID.
	ID string
	// ParentID is the parent entry ID, empty for root entries.
	ParentID string
	// Kind classifies the entry.
	Kind EntryKind
	// Role is the message role ("user", "assistant", "tool") for
	// EntryKindMessage nodes and empty for every other kind.
	Role string
	// Text is the kind-appropriate plain-text payload: message text for
	// messages, "provider/model" for model changes, the summary for branch
	// summaries and compactions, the label text for labels and the session
	// name for session info. Empty for kinds with no textual payload.
	//
	// Text is never truncated or collapsed — formatting is the caller's job.
	Text string
	// Label is the user-defined label bookmarking this entry, or empty.
	Label string
	// Children are the node's child entries, in insertion order.
	Children []TreeNodeView
}

TreeNodeView is an immutable value projection of a single node in the session entry tree. It carries everything a presentation layer needs to filter, search and render the node without reaching back into the session store or knowing the entry schema.

func (TreeNodeView) IsUserMessage added in v0.94.0

func (n TreeNodeView) IsUserMessage() bool

IsUserMessage reports whether the node is a message authored by the user.

type UsageUpdatedEvent added in v0.62.0

type UsageUpdatedEvent struct{}

UsageUpdatedEvent is sent after each completed LLM step to notify the TUI that token counts and costs have changed. The UsageTracker is updated in-place before this event is sent; the TUI just needs to re-render to reflect the new values in the status bar.

type UsageUpdater

type UsageUpdater interface {
	// UpdateUsage records actual token counts returned by the provider.
	// The counts come from fantasy's TotalUsage (aggregate across all steps
	// in a multi-step tool-calling run) and are used for session cost tracking.
	UpdateUsage(inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens int)
	// EstimateAndUpdateUsage falls back to text-based token estimation when
	// the provider does not return exact counts.
	EstimateAndUpdateUsage(inputText, outputText string)
	// SetContextTokens records the approximate current context window fill
	// level. This should be the sum of ALL token categories from the last
	// API call: InputTokens + CacheReadTokens + CacheCreationTokens +
	// OutputTokens. With Anthropic prompt caching, InputTokens can be
	// near-zero while CacheReadTokens holds the bulk of the context.
	SetContextTokens(tokens int)
	// SetUsageUnreported records whether the active provider failed to
	// report token usage on the most recent turn (e.g. an OpenAI-compatible
	// proxy that omits `usage` from the final streaming chunk). When true,
	// the UI shows an honest "⚠ usage not reported by provider" notice
	// instead of a misleading bare zero. Called once per turn from
	// updateUsageFromTurnResult.
	SetUsageUnreported(unreported bool)
	// StartTurn marks a turn boundary, clearing the per-turn usage
	// accumulator while preserving session totals. A turn issues one LLM
	// request per tool-loop iteration and UpdateUsage sums them, so this
	// must be called before dispatching a prompt or the previous turn's
	// tokens leak into the next one.
	StartTurn()
}

UsageUpdater is the interface the app layer uses to record token usage after each agent step. It is satisfied by *ui.UsageTracker (which lives in internal/ui) without creating an import cycle — the concrete type is wired in cmd/root.go, which can import both packages.

type WidgetUpdateEvent added in v0.2.0

type WidgetUpdateEvent struct{}

WidgetUpdateEvent is sent when an extension adds, updates, or removes a widget via ctx.SetWidget or ctx.RemoveWidget. The TUI re-reads widget state from its WidgetProvider on the next render cycle.

Jump to

Keyboard shortcuts

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