tui

package
v0.9.11 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 39 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package tui is the CLI's interactive session: the prompt with its history and completion, the slash commands, streamed Markdown output, approvals and questions answered at the terminal, and Ctrl+C to stop a turn. It drives an api.Backend, so it works the same on a local workspace and on one held by the service (spec_019_tui).

Index

Constants

View Source
const (
	Reset   = "\033[0m"
	Bold    = "\033[1m"
	Dim     = "\033[2m"
	Red     = "\033[31m"
	Green   = "\033[32m"
	Yellow  = "\033[33m"
	Blue    = "\033[34m"
	Magenta = "\033[35m"
	Cyan    = "\033[36m"
	White   = "\033[37m"
	BgBlack = "\033[40m"
	BgBlue  = "\033[44m"
)

ANSI color codes

Variables

View Source
var ErrExit = errors.New("exit")

ErrExit is returned by HandleCommand when the user asks to quit.

View Source
var ErrPickCancelled = errors.New("cancelled")

ErrPickCancelled is returned when the user leaves a picker without choosing (Esc, or an empty answer).

View Source
var ErrRewindKey = errors.New("rewind requested")

ErrRewindKey is what ReadInput returns when Esc Esc was pressed at an empty prompt: the REPL opens /rewind.

WorkspaceSearchSources are /search's (and blitz search --in's) words for what to search: a source, or all of them.

Functions

func AskTrust

func AskTrust(ctx context.Context, in Input, w io.Writer, dir string, p api.ProjectSettings) string

AskTrust shows what p's settings would do and asks whether to trust them: "trust", "decline", or "" when the question went unanswered (Ctrl+C, end of input). [s] shows the files first.

func ConfirmExit

func ConfirmExit(ctx context.Context, in Input, pm api.Processes, interrupts <-chan os.Signal, opts ExitPrompt) bool

ConfirmExit decides whether Blitz may exit while background processes or tasks are running. Nothing is left running either way: the user chooses to kill them now or wait for them to finish, and a further Ctrl+C (or EOF) at the prompt or while waiting force-quits, killing them. Returns false only when the user cancels the exit.

func CostBreakdown added in v0.9.2

func CostBreakdown(t api.Totals) []string

CostBreakdown is a session's usage by model, and by purpose when it had more than one (spec_056 CA-125): nothing for a single model's turns.

func DataMentions added in v0.9.7

func DataMentions(conns []api.DataConnection) []string

DataMentions are the @db: mentions conns offer, without the @ (DAT-40): each one a chat may use, and its saved queries that take no parameters (a mention can't fill them).

func DecideTrust

func DecideTrust(ctx context.Context, in Input, w io.Writer, b ProjectTruster, p api.ProjectSettings)

DecideTrust asks about p and records the answer through b, and says what came of it.

func FormatCitations added in v0.9.2

func FormatCitations(cites []api.Citation) string

FormatCitations renders the sources an answer cites under it, one a line, numbered (spec_056 CA-84).

func FormatTasks

func FormatTasks(tasks []api.Task) string

FormatTasks renders the agent's task list as a checklist.

func FormatToolCall

func FormatToolCall(toolName string, args map[string]any) string

FormatToolCall renders an invocation badge for a tool.

func FormatToolResult

func FormatToolResult(toolName string, success bool, summary string) string

FormatToolResult renders a completed tool badge.

func HandleCommand

func HandleCommand(ctx context.Context, input string, app *App) (bool, error)

HandleCommand processes slash commands. Returns true if input was a slash command.

func LicenseText

func LicenseText(which, command string) (string, error)

LicenseText is what `license` shows for which: "" (the NOTICE and where to find the rest), "full" (the Apache License) or "third-party" (the notices of the software Blitz includes). command is how the caller is invoked, for the pointers in the summary.

func NeedsTrustDecision

func NeedsTrustDecision(p api.ProjectSettings) bool

NeedsTrustDecision reports whether p's settings wait for a first or new decision.

func NewApprover

func NewApprover(in Input, diffLines int) api.Approver

NewApprover returns an api.Approver that asks on the terminal, showing the proposed diff (truncated to diffLines; "d" shows it all). Anything other than an explicit yes is a denial.

func NewUserPrompter

func NewUserPrompter(in Input) api.UserPromptFunc

NewUserPrompter returns an api.UserPromptFunc backed by the terminal. A numeric answer selects the matching option when options are offered. For a multi-select question it takes several, separated by commas.

func Page

func Page(out io.Writer, text string) error

Page writes text to out, through $PAGER (else less) when out is a terminal and the text is taller than it.

func ParseNotifyMode added in v0.9.1

func ParseNotifyMode(s string) (mode string, ok bool)

ParseNotifyMode is ui.notify as a mode, in any case: both, bell, desktop or off. Anything else isn't ok, and is both, the default (N26 cli-2#8).

func PrintBanner

func PrintBanner(version, agent, model string)

PrintBanner prints the session's first lines: the app's name (the organization's, spec_053 EN-51) and Blitz's version, the agent and model in use, and how to get help or stop.

func PrintDataConnections added in v0.9.7

func PrintDataConnections(out io.Writer, conns []api.DataConnection)

PrintDataConnections prints conns, each with what keeps it from a chat (off, not trusted, a problem) and its saved queries, then how to use them (/data, blitz data list).

func PrintRecap

func PrintRecap(msgs []api.Message, n int)

PrintRecap shows the last n messages of a resumed session.

func PrintSearchHits added in v0.3.0

func PrintSearchHits(out io.Writer, hits []api.SearchHit)

PrintSearchHits writes workspace search's hits: where each is (path:line for files, the title for a chat), its section, and its passage.

func PrintSearchStatus added in v0.3.0

func PrintSearchStatus(out io.Writer, s api.SearchStatus)

PrintSearchStatus writes how the workspace's search index is.

func ProcessLine added in v0.8.5

func ProcessLine(p api.ProcessInfo) string

ProcessLine is a process on one line: "[3] pnpm dev · 4m12s · 98% CPU · 310 MB — busy, left running (idle 2h0m)".

func ProjectItem

func ProjectItem(it api.ProjectItem) string

ProjectItem is one project setting in words: "hook stop runs ./scripts/stop.sh".

func ProjectNotice

func ProjectNotice(p api.ProjectSettings) string

ProjectNotice is the line the REPL prints at start about the project's settings, or "": what applies, and what waits for trust.

func ProjectReason

func ProjectReason(reason string) string

ProjectReason is why a project setting was ignored, in words.

func RenderDiff

func RenderDiff(diff string, maxLines int) (string, bool)

RenderDiff colourises a unified diff for the terminal, keeping at most maxLines lines (0 = all). It reports whether lines were cut.

func RunREPL

func RunREPL(ctx context.Context, app *App) error

RunREPL runs the interactive REPL prompt loop until /exit, EOF, or ctx is cancelled.

func ShowProject

func ShowProject(w io.Writer, p api.ProjectSettings)

ShowProject writes p: its files, what is in force, what needs trust and its state, and what was ignored.

func StdinIsTerminal

func StdinIsTerminal() bool

StdinIsTerminal reports whether stdin is interactive.

func SummarizeToolResponse

func SummarizeToolResponse(resp map[string]any) (summary string, success bool)

SummarizeToolResponse picks a short summary from a function response and reports whether it represents success.

func TaskLine

func TaskLine(t api.TaskInfo) string

TaskLine is a task on one line: "[task-3] qa · running · 1m20s · $0.02 — review the cart".

func UsageLine

func UsageLine(before, after api.Usage) string

UsageLine summarises a turn's usage: tokens in/out, context size and cost.

func WaitIndexed added in v0.3.0

func WaitIndexed(ctx context.Context, b api.Backend, since time.Time, limit time.Duration) error

WaitIndexed waits until the workspace's index has finished a scan after since (a workspace just opened here scans it; the service's is kept current, so any scan will do), for up to limit or until ctx ends.

Types

type App

type App struct {
	// Workspace is the program behind the REPL: every command and turn goes
	// through it. It runs here or in the Blitz service.
	Workspace api.Backend

	Version string
	Input   Input
	// Attached means the workspace runs in the Blitz service (/status).
	Attached bool
	// ConfigDir is where the user's settings live ("" for the default),
	// for /config --save.
	ConfigDir string
	// Notify tells you when a long turn ends or waits for you.
	Notify Notifier
	// StatusLine is ui.status_line: "default", a command, or "" for none.
	StatusLine string
	// Follow, when set, shows a background run until it ends before the
	// first prompt (blitz attach), answering what it asks; FollowID names
	// it.
	Follow   func(ctx context.Context, on func(api.Event)) (api.TurnResult, error)
	FollowID string
	// FirstPrompt, when set, is sent as the first prompt once the banner
	// is up, as if typed (blitz -i "prompt"); the session stays open.
	FirstPrompt string
	// Printer configures output rendering.
	Printer PrinterOptions
	// Locales are the interface's translation catalogs (nil: the built-in
	// ones). The interface language is the front end's own.
	Locales *i18n.Bundle
	// Attachments are images to send with the next prompt (/attach, /paste,
	// --image).
	Attachments []*images.Image
	// TerminalTitle shows the session's name in the terminal window title.
	TerminalTitle bool
	// DiffLines caps the diff shown with a background task's approval
	// request, as with the turn's own.
	DiffLines int
	// Cd opens the workspace in dir for /cd, asking about its project
	// settings as at start; commit makes it the one the program closes at
	// exit. Nil: /cd isn't available.
	Cd func(ctx context.Context, dir string) (next api.Backend, locales *i18n.Bundle, commit func(), err error)

	// Interrupts delivers Ctrl+C. If nil, RunREPL subscribes to os.Interrupt
	// itself. At the prompt an interrupt starts exit (confirming if background
	// processes run); during a turn it cancels only that turn.
	Interrupts <-chan os.Signal
	// contains filtered or unexported fields
}

App is the REPL's state: the workspace it drives and the terminal.

func (*App) ListTasks

func (app *App) ListTasks() []api.TaskInfo

ListTasks and StopTask are the current workspace's (it changes with /cd): App is the exit prompt's TaskControl.

func (*App) StopTask

func (app *App) StopTask(id string) (api.TaskInfo, error)

StopTask stops one of the current workspace's tasks.

type Completer

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

Completer completes slash commands, their arguments, and @path references to files in the workspace.

func NewCompleter

func NewCompleter(workspace string) *Completer

NewCompleter creates a completer rooted at workspace.

func (*Completer) Command

func (c *Completer) Command(name string, args ...string)

Command registers a slash command (without "/") and static argument choices.

func (*Completer) Do

func (c *Completer) Do(line []rune, pos int) ([][]rune, int)

Do implements readline.AutoCompleter: it returns candidate suffixes for the word before the cursor and the length of that word.

func (*Completer) Dynamic

func (c *Completer) Dynamic(name string, f func() []string)

Dynamic registers a function supplying argument choices for a command.

func (*Completer) Mentions added in v0.9.7

func (c *Completer) Mentions(f func() []string)

Mentions registers a function supplying @db: references beside the workspace's paths, without the @; it's asked only when what's typed could be one (@, @d, @db:…).

func (*Completer) SetWorkspace

func (c *Completer) SetWorkspace(dir string)

SetWorkspace makes completions of paths relative to dir (after /cd).

type ExitPrompt

type ExitPrompt struct {
	// CanPrompt is false when stdin can't answer (EOF, not a terminal); running
	// processes are then killed without asking.
	CanPrompt bool
	// AllowCancel offers "cancel" to return to the REPL instead of exiting.
	AllowCancel bool
	// Tasks are the background tasks to account for too (nil: none).
	Tasks TaskControl
}

ExitPrompt configures ConfirmExit.

type Input

type Input interface {
	// Ask reads a one-off answer (approvals, questions); not saved to history.
	Ask(ctx context.Context, text string) (string, error)
	// ReadInput reads a REPL entry, which may span lines: end a line with
	// "\\" to continue it, or enclose a block between lines of """.
	ReadInput(ctx context.Context, prompt string) (string, error)
}

Input reads user input. LineReader serves pipes and tests; TerminalInput adds line editing, history and completion on a TTY.

type KeyBindings

type KeyBindings struct {
	Editor    rune // 0: none
	CycleMode rune
	// Commands are sent as the entry when their key is pressed at an empty
	// prompt.
	Commands map[rune]string
}

KeyBindings are the REPL's keys (spec_027_parity PAR-UI-09), from ~/.blitz/keybindings.toml:

editor = "ctrl+g"          # edit the line in $EDITOR
cycle_mode = "shift+tab"   # next permission mode
[commands]
"ctrl+t" = "/tasks"        # run a command at an empty prompt

A key is ctrl+<letter>, shift+tab or "none". Binding a key the line editor uses (ctrl+a, ctrl+r, …) takes it over.

func DefaultKeyBindings

func DefaultKeyBindings() KeyBindings

DefaultKeyBindings are the keys without a keybindings file.

func LoadKeyBindings

func LoadKeyBindings(path string) (KeyBindings, error)

LoadKeyBindings reads path over the defaults; a missing file is the defaults.

type LineReader

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

LineReader is the single buffered reader over stdin. The REPL, approval prompts and ask_user_question must all share it: separate bufio readers on the same fd each buffer ahead and steal each other's input.

Reads are cancellable. A read abandoned by cancellation stays in flight and its line is delivered to the next caller, so no input is lost.

func NewLineReader

func NewLineReader(in io.Reader, out io.Writer) *LineReader

NewLineReader wraps in, echoing prompts to out.

func (*LineReader) Ask

func (l *LineReader) Ask(ctx context.Context, text string) (string, error)

Ask prints text and reads one line, returning early with ctx.Err() if ctx is cancelled. Concurrent callers are serialised so their output and input don't interleave.

func (*LineReader) ReadInput

func (l *LineReader) ReadInput(ctx context.Context, prompt string) (string, error)

ReadInput implements Input.

type Notifier

type Notifier struct {
	After time.Duration // 0: never
	Mode  string        // both, bell, desktop, off
}

Notifier sends the REPL's notifications.

func (Notifier) Approving

func (n Notifier) Approving(a api.Approver) api.Approver

Approving wraps an approver to notify when a request waits during a long turn.

func (Notifier) Asking

Asking wraps a question prompter the same way.

func (Notifier) Send

func (n Notifier) Send(body string)

Send rings the bell and shows a notification, as the mode says.

type PickItem

type PickItem struct {
	Label  string // shown, and matched by typing
	Detail string // shown dim after the label, and matched too
	// Key selects the item at once when typed before any filter text (the
	// approval answers y, s, a, n). 0 for none.
	Key rune
}

PickItem is one choice in a picker.

type Picker

type Picker interface {
	// Pick shows items under title with current selected, and returns the
	// index chosen.
	Pick(ctx context.Context, title string, items []PickItem, current int) (int, error)
}

Picker is an Input that can show a menu: an arrow-key, type-to-filter list inside the terminal's normal flow (decision §12.4 of the parity spec: no full-screen views).

type Printer

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

Printer renders agent events: model text (optionally as Markdown), tool activity, and a spinner while waiting.

func NewPrinter

func NewPrinter(o PrinterOptions) *Printer

NewPrinter creates a Printer; Markdown falls back to plain text on error.

func (*Printer) Begin

func (p *Printer) Begin()

Begin marks the start of a turn.

func (*Printer) End

func (p *Printer) End()

End flushes buffered output at the end of a turn.

func (*Printer) Handle

func (p *Printer) Handle(ev api.Event)

Handle renders a turn's event.

func (*Printer) Pause

func (p *Printer) Pause()

Pause holds back output (e.g. while the user types a steer message) until Resume, which prints what arrived meanwhile.

func (*Printer) Resume

func (p *Printer) Resume()

Resume prints held-back output and continues normally. The spinner comes back only if it was showing: restarting it mid-sentence would erase the partly printed line.

type PrinterOptions

type PrinterOptions struct {
	Out      io.Writer
	Markdown bool // render Markdown (requires a terminal)
	Theme    string
	Width    int
	Spinner  bool
}

PrinterOptions configure a Printer.

type ProjectTruster

type ProjectTruster interface {
	Dir() string
	ProjectSettings() api.ProjectSettings
	TrustProject(hash string, trusted bool) error
}

ProjectTruster is where project settings are read and trusted: a workspace (api.Backend), or blitz trust's.

type PromptKeys

type PromptKeys struct {
	// CycleMode switches to the next permission mode (Shift+Tab) and
	// returns the new prompt, or "" to leave it.
	CycleMode func() string
}

PromptKeys are what REPL-only keys do at the main prompt.

type Spinner

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

Spinner shows an animated status line while waiting. It is a no-op when disabled (e.g. output is not a terminal). Start and Stop may be called in any order and repeatedly.

func NewSpinner

func NewSpinner(out io.Writer, enabled bool) *Spinner

NewSpinner returns a spinner writing to out.

func (*Spinner) Running

func (s *Spinner) Running() bool

Running reports whether the spinner is showing.

func (*Spinner) Start

func (s *Spinner) Start(label string)

Start shows label with an elapsed-time counter until Stop.

func (*Spinner) Stop

func (s *Spinner) Stop()

Stop clears the spinner line.

type StatusState

type StatusState struct {
	Version        string  `json:"version"`
	Workspace      string  `json:"workspace"`
	Attached       bool    `json:"attached"`
	SessionID      string  `json:"session_id,omitempty"`
	SessionName    string  `json:"session_name,omitempty"`
	Agent          string  `json:"agent"`
	Model          string  `json:"model"`
	Provider       string  `json:"provider,omitempty"`
	Mode           string  `json:"permission_mode"`
	Effort         string  `json:"effort,omitempty"`
	Style          string  `json:"style,omitempty"`
	ContextTokens  int64   `json:"context_tokens"`
	ContextPercent float64 `json:"context_percent"` // of the compaction threshold; 0 without one
	CostUSD        float64 `json:"cost_usd"`
	Priced         bool    `json:"priced"`
}

StatusState is what a status line command reads on stdin.

type TaskControl

type TaskControl interface {
	ListTasks() []api.TaskInfo
	StopTask(id string) (api.TaskInfo, error)
}

TaskControl lists and stops background tasks: the workspace (api.Backend).

type TerminalInput

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

TerminalInput is an Input backed by a line editor: arrow-key editing, persistent history, reverse search (Ctrl+R) and tab completion. Every terminal read goes through it so prompts never compete for stdin.

func NewTerminalInput

func NewTerminalInput(o TerminalOptions) (*TerminalInput, error)

NewTerminalInput creates the line editor on stdin/stdout.

func (*TerminalInput) Ask

func (t *TerminalInput) Ask(ctx context.Context, text string) (string, error)

Ask prints text (which may span lines) and reads one answer without recording it in history.

func (*TerminalInput) AskSecret added in v0.9.6

func (t *TerminalInput) AskSecret(ctx context.Context, text string) (string, error)

AskSecret prints text and reads one answer typed hidden, kept out of history: a secret's value (spec_060_blitz_tools DRV-05).

func (*TerminalInput) AskSteer

func (t *TerminalInput) AskSteer(ctx context.Context, prompt, prefill string) (string, error)

AskSteer reads a steer message pre-filled with what the user already typed. It is called from the key watcher, which has handed over the terminal, so it doesn't pause the watcher itself.

func (*TerminalInput) Close

func (t *TerminalInput) Close() error

Close restores the terminal.

func (*TerminalInput) Pick

func (t *TerminalInput) Pick(ctx context.Context, title string, items []PickItem, current int) (int, error)

Pick implements Picker on the terminal: arrow keys (or Ctrl+P/N) move, typing filters, Enter chooses, Esc clears the filter or cancels, and Ctrl+C cancels (and interrupts a running turn). Without a terminal it asks for a number instead.

func (*TerminalInput) ReadInput

func (t *TerminalInput) ReadInput(ctx context.Context, prompt string) (string, error)

ReadInput reads a REPL entry (multi-line aware) and saves it to history.

func (*TerminalInput) SetInterruptHandler

func (t *TerminalInput) SetInterruptHandler(f func())

SetInterruptHandler sets what Ctrl+C does while a prompt is shown during a turn (e.g. an approval). The terminal is in raw mode then, so Ctrl+C is a keypress rather than SIGINT; the REPL uses this to cancel the turn.

func (*TerminalInput) SetNextInput

func (t *TerminalInput) SetNextInput(text string)

SetNextInput puts text in the next REPL prompt's line, to edit or send (a rewound prompt).

func (*TerminalInput) SetPromptKeys

func (t *TerminalInput) SetPromptKeys(k PromptKeys)

SetPromptKeys sets what the REPL's own keys do at the main prompt.

func (*TerminalInput) WatchKeys

func (t *TerminalInput) WatchKeys(onKey func(prefill string)) (stop func())

WatchKeys lets the user steer the running turn: typing (or Ctrl+T) calls onKey with the typed text, from a watcher goroutine. Prompts during the turn pause the watcher automatically. Call stop when the turn ends; it waits for an open steer prompt to be finished.

type TerminalOptions

type TerminalOptions struct {
	HistoryFile string
	HistorySize int
	Completer   readline.AutoCompleter
	// Vim edits the line vi-style (ui.editor = "vim"): Esc for normal
	// mode, so Esc Esc does nothing.
	Vim bool
	// Keys are the REPL's keys (nil: the defaults).
	Keys *KeyBindings
}

TerminalOptions configure a TerminalInput.

Jump to

Keyboard shortcuts

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