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 AnswerOffline(out io.Writer, question string, why string)
- func AskTrust(ctx context.Context, in Input, w io.Writer, dir string, p api.ProjectSettings) string
- func ColorOn() bool
- func ColorWanted(flag string, tty bool, getenv func(string) string) bool
- func ConfirmExit(ctx context.Context, in Input, pm api.Processes, interrupts <-chan os.Signal, ...) bool
- func CostBreakdown(t api.Totals) []string
- func DataMentions(conns []api.DataConnection) []string
- func DecideTrust(ctx context.Context, in Input, w io.Writer, b ProjectTruster, ...)
- func FirstLine(s string) string
- 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 HelpPrompt(question string) string
- 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 PrintDataConnections(out io.Writer, conns []api.DataConnection)
- func PrintReasoning(out io.Writer, r api.Reasoning, full bool)
- func PrintReasoningTurns(out io.Writer, r api.Reasoning)
- 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 RenderBanner(b BannerInfo) string
- func RenderDiff(diff string, maxLines int) (string, bool)
- func RenderMarkdown(md, theme string, width int, pretty bool) string
- func RunREPL(ctx context.Context, app *App) error
- func SetColor(on bool, getenv func(string) string)
- func ShowDocs(out io.Writer, cmd, words string, render func(string) string)
- 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 UnsafeFromAgent(mode string) error
- 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 BannerInfo
- type Command
- type Completer
- func (c *Completer) Custom(f func() []string)
- func (c *Completer) Do(line []rune, pos int) ([][]rune, int)
- func (c *Completer) Fuzzy(before string) (string, bool)
- func (c *Completer) Mentions(f func() []string)
- func (c *Completer) SetWorkspace(dir string)
- func (c *Completer) Source(s Source, f func() []string)
- func (c *Completer) Suggest(before string) (ghost, hint string)
- type ExitPrompt
- type Input
- type KeyBindings
- type LineReader
- type Notifier
- type PickItem
- type Picker
- type Printer
- type PrinterOptions
- type ProjectTruster
- type PromptKeys
- type Source
- 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 ( BannerFull = "full" BannerCompact = "compact" BannerOff = "off" )
The banner's forms (ui.banner, spec_067_cli_parity CLP-01, CLP-02).
const ShellUsage = "!<command>"
ShellUsage is how /help shows running a shell command.
Variables ¶
var ( 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 colour codes. They're variables so that SetColor can blank them all when colour is off (NO_COLOR, a pipe, --color=never: CLP-03).
var Commands = []*Command{ {Name: "btw", Group: "help.group.session", Usage: "<question>", Help: "help.btw", Turn: true}, {Name: "checkpoints", Group: "help.group.session", Help: "help.checkpoints"}, {Name: "clear", Group: "help.group.session", Help: "help.clear"}, {Name: "compact", Group: "help.group.session", Usage: "[focus]", Help: "help.compact"}, {Name: "context", Group: "help.group.session", Help: "help.context"}, {Name: "copy", Group: "help.group.session", Usage: "[n]", Help: "help.copy"}, {Name: "cost", Aliases: []string{"usage"}, Group: "help.group.session", Help: "help.cost"}, {Name: "export", Group: "help.group.session", Usage: "[file]", Help: "help.export", Args: []Source{SrcPaths}}, {Name: "fork", Group: "help.group.session", Usage: "[n]", Help: "help.fork"}, {Name: "reasoning", Group: "help.group.session", Usage: "[<turn>|turns] [--full]", Help: "help.reasoning", Subs: []*Command{sub("turns")}, Flags: []string{"--full"}}, {Name: "rename", Group: "help.group.session", Usage: "<name>", Help: "help.rename"}, {Name: "resume", Group: "help.group.session", Usage: "[id]", Help: "help.resume", Args: []Source{SrcSessions}}, {Name: "rewind", Group: "help.group.session", Usage: "[n [mode]] [--force]", Help: "help.rewind", Flags: []string{"--force"}}, {Name: "session", Group: "help.group.session", Usage: "list [--all]|new|load <id|name>|save <name>", Help: "help.session", Subs: []*Command{ {Name: "list", Flags: []string{"--all"}}, sub("new"), {Name: "load", Aliases: []string{"resume"}, Args: []Source{SrcSessions}}, sub("save"), }}, {Name: "status", Group: "help.group.session", Help: "help.status"}, {Name: "undo", Group: "help.group.session", Usage: "[--force]", Help: "help.undo", Flags: []string{"--force"}}, {Name: "agent", Group: "help.group.agents", Usage: "[name]", Help: "help.agent", Args: []Source{SrcAgents}}, {Name: "agents", Group: "help.group.agents", Usage: "[update]", Help: "help.agents", Subs: []*Command{{Name: "update", Turn: true}}}, {Name: "effort", Group: "help.group.agents", Usage: "[minimal|low|medium|high|max|auto]", Help: "help.effort", Choices: efforts}, {Name: "model", Group: "help.group.agents", Usage: "[name] [--new] | --refresh", Help: "help.model", Args: []Source{SrcModels}, Flags: []string{"--new", "--refresh"}}, {Name: "model_settings", Group: "help.group.agents", Usage: "[<model> [key=value…|reset]]", Help: "help.model_settings", Args: []Source{SrcModelSettings}}, {Name: "pin_model", Aliases: []string{"pin"}, Group: "help.group.agents", Usage: "[<agent> <model>]", Help: "help.pin", Args: []Source{SrcAgents, SrcModels}}, {Name: "personality", Group: "help.group.agents", Usage: "[name]", Help: "help.personality", Args: []Source{SrcPersonalities}}, {Name: "style", Group: "help.group.agents", Usage: "[name]", Help: "help.style", Args: []Source{SrcStyles}}, {Name: "unpin", Group: "help.group.agents", Usage: "<agent>", Help: "help.unpin", Args: []Source{SrcPinned}}, {Name: "data", Group: "help.group.work", Help: "help.data_cli"}, {Name: "goal", Group: "help.group.work", Usage: "[<condition>|clear]", Help: "help.goal", Turn: true, Subs: []*Command{sub("clear")}}, {Name: "loop", Group: "help.group.work", Usage: "[<interval> <prompt>|stop <n>]", Help: "help.loop", Subs: []*Command{sub("stop")}}, {Name: "plan", Group: "help.group.work", Usage: "<goal>", Help: "help.plan", Turn: true}, {Name: "processes", Aliases: []string{"ps"}, Group: "help.group.work", Usage: "[all|log <id>|stop <id>…|stop flagged|stop all]", Help: "help.processes", Subs: []*Command{ sub("all"), sub("log", SrcProcesses), {Name: "stop", Args: []Source{SrcProcesses}, Choices: []string{"flagged", "all"}}, }}, {Name: "search", Group: "help.group.work", Usage: "[files|documents|chats|notes|all|web|session] <terms>, /search status|reindex", Help: "help.search", Turn: true, Subs: []*Command{ sub("files"), sub("documents"), sub("chats"), sub("notes"), sub("all"), sub("web"), sub("session"), sub("status"), sub("reindex"), }}, {Name: "tasks", Group: "help.group.work", Usage: "[show|stop <id>]", Help: "help.tasks", Subs: []*Command{sub("show", SrcTasks), sub("stop", SrcTasks)}}, {Name: "attach", Group: "help.group.workspace", Usage: "[path|clear]", Help: "help.attach", Args: []Source{SrcPaths}, Subs: []*Command{sub("clear")}}, {Name: "cd", Group: "help.group.workspace", Usage: "[path]", Help: "help.cd", Args: []Source{SrcDirs}}, {Name: "diff", Group: "help.group.workspace", Usage: "[git]", Help: "help.diff", Subs: []*Command{sub("git")}}, {Name: "init", Group: "help.group.workspace", Help: "help.init", Turn: true}, {Name: "memory", Group: "help.group.workspace", Usage: "[show|reload|add <note>|notes|forget <name>]", Help: "help.memory", Subs: []*Command{ sub("show"), sub("reload"), sub("add"), sub("notes"), sub("forget"), }}, {Name: "paste", Group: "help.group.workspace", Help: "help.paste"}, {Name: "reload", Group: "help.group.workspace", Help: "help.reload"}, {Name: "rules", Group: "help.group.workspace", Usage: "update", Help: "help.rules", Subs: []*Command{{Name: "update", Turn: true}}}, {Name: "trust", Group: "help.group.workspace", Help: "help.trust"}, {Name: "approvals", Group: "help.group.safety", Usage: "[revoke <n>|clear]", Help: "help.approvals", Subs: []*Command{sub("revoke"), sub("clear")}}, {Name: "hooks", Group: "help.group.safety", Help: "help.hooks"}, {Name: "mode", Group: "help.group.safety", Usage: "[auto|default|accept-edits|plan|dont-ask|bypass|unsafe]", Help: "help.mode", Choices: modes}, {Name: "permissions", Aliases: []string{"perms"}, Group: "help.group.safety", Usage: "[allow|ask|deny|remove <rule> [--save]]", Help: "help.permissions", Subs: []*Command{ {Name: "allow", Flags: []string{"--save"}}, {Name: "ask", Flags: []string{"--save"}}, {Name: "deny", Flags: []string{"--save"}}, {Name: "remove", Aliases: []string{"rm"}, Flags: []string{"--save"}}, }}, {Name: "sandbox", Group: "help.group.safety", Help: "help.sandbox"}, {Name: "envs", Group: "help.group.extensions", Usage: "[prune|remove <key>]", Help: "help.envs", Subs: []*Command{sub("prune"), sub("remove")}}, {Name: "mcp", Group: "help.group.extensions", Help: "help.mcp"}, {Name: "skills", Group: "help.group.extensions", Usage: "list|show <name>|search <q>|registry|install <name> [--project]|update", Help: "help.skills", Subs: []*Command{ sub("list"), sub("show", SrcSkills), sub("search"), sub("registry"), {Name: "install", Flags: []string{"--project"}}, {Name: "update", Turn: true}, }}, {Name: "tools", Group: "help.group.extensions", Help: "help.tools"}, {Name: "config", Aliases: []string{"set", "show"}, Group: "help.group.settings", Usage: "[key=value [--save]]", Help: "help.set", Args: []Source{SrcConfig}, Flags: []string{"--save"}}, {Name: "docs", Group: "help.group.settings", Usage: "[page|words]", Help: "help.docs_cli"}, {Name: "exit", Aliases: []string{"quit"}, Group: "help.group.settings", Help: "help.exit"}, {Name: "help", Group: "help.group.settings", Usage: "[command|keys|question]", Help: "help.help", Args: []Source{SrcCommands}, Choices: []string{"keys"}}, {Name: "license", Group: "help.group.settings", Usage: "[full|third-party]", Help: "help.license", Subs: []*Command{sub("full"), sub("third-party")}}, {Name: "locale", Aliases: []string{"lang", "language"}, Group: "help.group.settings", Usage: "[code]", Help: "help.locale", Args: []Source{SrcLocales}}, {Name: "theme", Group: "help.group.settings", Usage: "[name [--save]]", Help: "help.theme", Args: []Source{SrcThemes}, Flags: []string{"--save"}}, }
Commands are the REPL's built-in slash commands.
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 AnswerOffline ¶ added in v1.3.0
AnswerOffline answers a question without a model (CLP-23): the docs' sections and the commands that match it, and how to ask in your own words.
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 ColorWanted ¶ added in v1.3.0
ColorWanted decides whether output is coloured (CLP-03): --color (always, never; auto or "" to decide), then NO_COLOR (set, not empty: off), then CLICOLOR_FORCE or FORCE_COLOR (on), then TERM=dumb or output that isn't a terminal (off).
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 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
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 HelpPrompt ¶ added in v1.3.0
HelpPrompt is what's sent to the model to answer a question about Blitz (CLP-22): the docs' sections that match it, then the question. It's an aside: recorded nowhere, its tools read-only.
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 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 PrintReasoning ¶ added in v1.3.0
PrintReasoning draws one turn's graph as a tree: its calls with their model, tokens, time and cost; under each, its steps of reasoning, its tools (✓ or ✗) and sub-agents (their calls nested), and its words. full prints each node's text too.
func PrintReasoningTurns ¶ added in v1.3.0
PrintReasoningTurns lists a session's turns: each one's number, prompt, calls, steps of reasoning and cost.
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 RenderBanner ¶ added in v1.3.0
func RenderBanner(b BannerInfo) string
RenderBanner is the interactive CLI's first lines (CLP-01): the Blitz wordmark in the lightning gradient (or one line when the terminal is narrow, colour is off, the organization renames the app, or the form is compact), "powered by Retail Cortex" and the version, then the workspace, the agent and model, the mode and the sandbox, and one line of how to get going.
func RenderDiff ¶
RenderDiff colourises a unified diff for the terminal, keeping at most maxLines lines (0 = all). It reports whether lines were cut.
func RenderMarkdown ¶ added in v1.3.0
RenderMarkdown is md for the terminal: rendered when pretty, else as it is.
func SetColor ¶ added in v1.3.0
SetColor turns every colour the CLI prints on or off; with it on, truecolor (COLORTERM=truecolor or 24bit) draws the banner's gradient in full colour, else in 256 colours.
func ShowDocs ¶ added in v1.3.0
ShowDocs is `blitz docs` and /docs (spec_067_cli_parity CLP-21): with nothing, the docs' pages by section; with a page's name, the page; else the sections that best match the words.
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 UnsafeFromAgent ¶ added in v1.2.0
UnsafeFromAgent refuses unsafe mode in a blitz the agent's command started (activity.AgentEnv set): its /mode and flags never take the agent outside the sandbox; only the person chooses it (spec_005 APR-14e).
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
// Banner is ui.banner: BannerFull ("" too), BannerCompact or BannerOff
// (spec_067_cli_parity CLP-02).
Banner string
// Width is the terminal's width in columns (0: unknown).
Width int
// StateDir is where the CLI keeps what it remembers between runs (the
// start-up hints shown, CLP-04); "" keeps nothing.
StateDir string
// AfterBanner, when set, prints under the banner before the first
// prompt (a resumed session's recap).
AfterBanner func()
// 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 BannerInfo ¶ added in v1.3.0
type BannerInfo struct {
// Form is BannerFull, BannerCompact or BannerOff.
Form string
Width int
Version string
// Workspace is its folder, Branch its git branch ("" for none).
Workspace, Branch string
Agent, Model string
// NoModel says no model is set up yet.
NoModel bool
Mode string
// Sandbox is the shell sandbox in a word or two.
Sandbox string
}
BannerInfo is what the banner shows.
type Command ¶ added in v1.3.0
type Command struct {
Name string
Aliases []string
// Group is /help's group (an i18n key) for a top-level command.
Group string
// Usage is what follows the name in /help ("[name]").
Usage string
// Help is the description's i18n key ("" for a sub-command that has
// none of its own).
Help string
Subs []*Command
// Args are what the words after the command (and its sub-commands)
// are, in order; the last repeats.
Args []Source
// Choices are fixed words the next argument can be.
Choices []string
Flags []string
// Turn marks a command the REPL itself runs (as a turn, or before the
// dispatcher): /btw, /init, /plan, /goal, /search, … update.
Turn bool
}
Command is one slash command or sub-command, declared once for the dispatcher's check, /help and completion (spec_067_cli_parity CLP-10).
func FindCommand ¶ added in v1.3.0
FindCommand is the built-in command named name or one of its aliases (without its /), or nil.
type Completer ¶
type Completer struct {
// contains filtered or unexported fields
}
Completer completes slash commands at every level of the command tree, their flags and values, /config's key=value, and @path and @db: references (spec_067_cli_parity CLP-11). It also gives the hint shown after the cursor as you type (CLP-12) and a fuzzy match for Tab (CLP-13).
func NewCompleter ¶
NewCompleter creates a completer of the built-in commands, rooted at workspace.
func (*Completer) Custom ¶ added in v1.3.0
Custom registers a function supplying the custom commands' names, asked each time so commands added since start-up complete too.
func (*Completer) Do ¶
Do implements readline.AutoCompleter: the candidates' suffixes for the word before the cursor, and that word's length.
func (*Completer) Fuzzy ¶ added in v1.3.0
Fuzzy is the line with its last word replaced by the one candidate it matches by words or letters in order (/perms → /permissions, /pmod → /pin_model) when no candidate starts with it (CLP-13); false when there isn't exactly one.
func (*Completer) Mentions ¶ added in v0.9.7
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 ¶
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 Source ¶ added in v1.3.0
type Source string
Source names what a command's argument can be, for completion: the completer asks the function registered for it (Completer.Source), or knows it itself (themes, modes, config keys, paths).
const ( SrcAgents Source = "agents" // the agents' names SrcPinned Source = "pinned" // agents with a pinned model SrcModels Source = "models" // every provider's chat models SrcModelSettings Source = "model_settings" // models in use or with settings SrcSessions Source = "sessions" // saved sessions and snapshots SrcThemes Source = "themes" SrcStyles Source = "styles" SrcPersonalities Source = "personalities" SrcLocales Source = "locales" SrcSkills Source = "skills" SrcTasks Source = "tasks" // background tasks' IDs SrcProcesses Source = "processes" // background processes' IDs SrcConfig Source = "config" // key=value of /config SrcPaths Source = "paths" // workspace files and folders SrcDirs Source = "dirs" // folders only SrcCommands Source = "commands" // the slash commands, for /help )
The argument sources.
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
- banner.go
- cd.go
- commands.go
- commands_extra.go
- commandtree.go
- complete.go
- data.go
- docs.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
- reasoning.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