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
- Variables
- func AskTrust(ctx context.Context, in Input, w io.Writer, dir string, p api.ProjectSettings) string
- func ConfirmExit(ctx context.Context, in Input, pm api.Processes, interrupts <-chan os.Signal, ...) bool
- func CostBreakdown(t api.Totals) []string
- func DecideTrust(ctx context.Context, in Input, w io.Writer, b ProjectTruster, ...)
- func FormatCitations(cites []api.Citation) string
- func FormatTasks(tasks []api.Task) string
- func FormatToolCall(toolName string, args map[string]any) string
- func FormatToolResult(toolName string, success bool, summary string) string
- func HandleCommand(ctx context.Context, input string, app *App) (bool, error)
- func LicenseText(which, command string) (string, error)
- func NeedsTrustDecision(p api.ProjectSettings) bool
- func NewApprover(in Input, diffLines int) api.Approver
- func NewUserPrompter(in Input) api.UserPromptFunc
- func Page(out io.Writer, text string) error
- func ParseNotifyMode(s string) (mode string, ok bool)
- func PrintBanner(version, agent, model string)
- func PrintRecap(msgs []api.Message, n int)
- func PrintSearchHits(out io.Writer, hits []api.SearchHit)
- func PrintSearchStatus(out io.Writer, s api.SearchStatus)
- func ProcessLine(p api.ProcessInfo) string
- func ProjectItem(it api.ProjectItem) string
- func ProjectNotice(p api.ProjectSettings) string
- func ProjectReason(reason string) string
- func RenderDiff(diff string, maxLines int) (string, bool)
- func RunREPL(ctx context.Context, app *App) error
- func ShowProject(w io.Writer, p api.ProjectSettings)
- func StdinIsTerminal() bool
- func SummarizeToolResponse(resp map[string]any) (summary string, success bool)
- func TaskLine(t api.TaskInfo) string
- func UsageLine(before, after api.Usage) string
- func WaitIndexed(ctx context.Context, b api.Backend, since time.Time, limit time.Duration) error
- type App
- type Completer
- type ExitPrompt
- type Input
- type KeyBindings
- type LineReader
- type Notifier
- type PickItem
- type Picker
- type Printer
- type PrinterOptions
- type ProjectTruster
- type PromptKeys
- type Spinner
- type StatusState
- type TaskControl
- type TerminalInput
- func (t *TerminalInput) Ask(ctx context.Context, text string) (string, error)
- func (t *TerminalInput) AskSecret(ctx context.Context, text string) (string, error)
- func (t *TerminalInput) AskSteer(ctx context.Context, prompt, prefill string) (string, error)
- func (t *TerminalInput) Close() error
- func (t *TerminalInput) Pick(ctx context.Context, title string, items []PickItem, current int) (int, error)
- func (t *TerminalInput) ReadInput(ctx context.Context, prompt string) (string, error)
- func (t *TerminalInput) SetInterruptHandler(f func())
- func (t *TerminalInput) SetNextInput(text string)
- func (t *TerminalInput) SetPromptKeys(k PromptKeys)
- func (t *TerminalInput) WatchKeys(onKey func(prefill string)) (stop func())
- type TerminalOptions
Constants ¶
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 ¶
var ErrExit = errors.New("exit")
ErrExit is returned by HandleCommand when the user asks to quit.
var ErrPickCancelled = errors.New("cancelled")
ErrPickCancelled is returned when the user leaves a picker without choosing (Esc, or an empty answer).
var ErrRewindKey = errors.New("rewind requested")
ErrRewindKey is what ReadInput returns when Esc Esc was pressed at an empty prompt: the REPL opens /rewind.
var WorkspaceSearchSources = map[string][]string{ api.SearchFiles: {api.SearchFiles}, api.SearchDocuments: {api.SearchDocuments}, api.SearchChats: {api.SearchChats}, api.SearchNotes: {api.SearchNotes}, "all": api.SearchSources, }
WorkspaceSearchSources are /search's (and blitz search --in's) words for what to search: a source, or all of them.
Functions ¶
func AskTrust ¶
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
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 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
FormatCitations renders the sources an answer cites under it, one a line, numbered (spec_056 CA-84).
func FormatTasks ¶
FormatTasks renders the agent's task list as a checklist.
func FormatToolCall ¶
FormatToolCall renders an invocation badge for a tool.
func FormatToolResult ¶
FormatToolResult renders a completed tool badge.
func HandleCommand ¶
HandleCommand processes slash commands. Returns true if input was a slash command.
func LicenseText ¶
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 ¶
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 ¶
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
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 PrintRecap ¶
PrintRecap shows the last n messages of a resumed session.
func PrintSearchHits ¶ added in v0.3.0
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 ¶
ProjectReason is why a project setting was ignored, in words.
func RenderDiff ¶
RenderDiff colourises a unified diff for the terminal, keeping at most maxLines lines (0 = all). It reports whether lines were cut.
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 ¶
SummarizeToolResponse picks a short summary from a function response and reports whether it represents success.
func TaskLine ¶
TaskLine is a task on one line: "[task-3] qa · running · 1m20s · $0.02 — review the cart".
func WaitIndexed ¶ added in v0.3.0
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.
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 ¶
NewCompleter creates a completer rooted at workspace.
func (*Completer) Command ¶
Command registers a slash command (without "/") and static argument choices.
func (*Completer) Do ¶
Do implements readline.AutoCompleter: it returns candidate suffixes for the word before the cursor and the length of that word.
func (*Completer) SetWorkspace ¶
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.
type Notifier ¶
Notifier sends the REPL's notifications.
func (Notifier) Approving ¶
Approving wraps an approver to notify when a request waits during a long turn.
func (Notifier) Asking ¶
func (n Notifier) Asking(ask api.UserPromptFunc) api.UserPromptFunc
Asking wraps a question prompter the same way.
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.
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 ¶
NewSpinner returns a spinner writing to out.
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 ¶
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 ¶
Ask prints text (which may span lines) and reads one answer without recording it in history.
func (*TerminalInput) AskSecret ¶ added in v0.9.6
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 ¶
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) 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 ¶
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.
Source Files
¶
- attach.go
- cd.go
- commands.go
- commands_extra.go
- envs.go
- exit.go
- follow.go
- input.go
- keybindings.go
- keys.go
- keywatch.go
- keywatch_linux.go
- keywatch_unix.go
- license.go
- loops.go
- markdown.go
- mode.go
- modelsettings.go
- passthrough.go
- permissions.go
- picker.go
- pickers.go
- processes.go
- project.go
- render.go
- repl.go
- rewind.go
- search.go
- searchws.go
- skills.go
- spinner.go
- status.go
- statusline.go
- tasks.go
- terminal.go
- theme.go