render

package
v0.0.0-...-1402696 Latest Latest
Warning

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

Go to latest
Published: May 14, 2026 License: Apache-2.0 Imports: 7 Imported by: 3

Documentation

Overview

Package render provides ANSI-colored terminal rendering for Claude and agent sessions.

Package render provides ANSI-colored terminal rendering for Claude and agent sessions.

It supports configurable verbosity levels (quiet/normal/verbose/debug), color control (auto/always/never), and covers the full Claude SDK event set including tools, tasks, hooks, rate limits, and more.

Index

Constants

View Source
const (
	ColorReset   = "\x1b[0m"
	ColorDim     = "\x1b[2m"
	ColorItalic  = "\x1b[3m"
	ColorBold    = "\x1b[1m"
	ColorRed     = "\x1b[31m"
	ColorGreen   = "\x1b[32m"
	ColorYellow  = "\x1b[33m"
	ColorBlue    = "\x1b[34m"
	ColorMagenta = "\x1b[35m"
	ColorCyan    = "\x1b[36m"
	ColorGray    = "\x1b[90m"
)

ANSI color codes — kept exported for backward compatibility.

Variables

This section is empty.

Functions

func FormatToolInput

func FormatToolInput(name string, input map[string]interface{}) string

FormatToolInput formats tool input for inline display after the tool name bracket. Returns an empty string for tools that should be handled specially. This renderer uses terminal-oriented widths and omits the tool name because ToolStart prints it separately; sessionmodel.FormatToolContent uses different widths and prefixes for persisted structured output.

func IsTerminal

func IsTerminal(w io.Writer) bool

IsTerminal checks if the writer is backed by a terminal file descriptor.

Types

type ColorMode

type ColorMode int

ColorMode controls how color output is handled.

const (
	// ColorAuto detects whether stdout is a terminal and enables colors accordingly.
	ColorAuto ColorMode = iota
	// ColorAlways forces color output on.
	ColorAlways
	// ColorNever disables color output.
	ColorNever
)

func ParseColorMode

func ParseColorMode(s string) ColorMode

ParseColorMode converts a string to a ColorMode. Returns ColorAuto for unrecognized values.

type EventHandler

type EventHandler interface {
	// OnText is called with accumulated text at semantic boundaries.
	// Unlike streaming Text() calls, this provides complete text blocks
	// (e.g., all text between tool calls).
	OnText(text string)

	// OnThinking is called when thinking/reasoning content is emitted.
	OnThinking(thinking string)

	// OnToolStart is called when a tool begins execution.
	OnToolStart(name, id string, input map[string]interface{})

	// OnToolComplete is called when a tool finishes.
	// The result may be nil if not captured; isError indicates failure.
	OnToolComplete(name, id string, input map[string]interface{}, result interface{}, isError bool)

	// OnToolResult is called when a tool result is emitted after completion.
	OnToolResult(name, id string, content interface{}, isError bool)

	// OnTurnComplete is called when a conversation turn finishes.
	OnTurnComplete(turnNumber int, success bool, durationMs int64, costUSD float64)

	// OnStatus is called for status messages.
	OnStatus(msg string)

	// OnError is called for error events.
	OnError(err error, context string)
}

EventHandler receives semantic events for structured output capture. All methods receive complete, accumulated data at semantic boundaries, unlike the streaming text output from Renderer.

Implementations should be thread-safe as methods may be called from multiple goroutines.

type NoOpEventHandler

type NoOpEventHandler struct{}

NoOpEventHandler is an EventHandler that does nothing. Useful as a default or for testing.

func (NoOpEventHandler) OnError

func (NoOpEventHandler) OnError(error, string)

func (NoOpEventHandler) OnStatus

func (NoOpEventHandler) OnStatus(string)

func (NoOpEventHandler) OnText

func (NoOpEventHandler) OnText(string)

func (NoOpEventHandler) OnThinking

func (NoOpEventHandler) OnThinking(string)

func (NoOpEventHandler) OnToolComplete

func (NoOpEventHandler) OnToolComplete(string, string, map[string]interface{}, any, bool)

func (NoOpEventHandler) OnToolResult

func (NoOpEventHandler) OnToolResult(string, string, any, bool)

func (NoOpEventHandler) OnToolStart

func (NoOpEventHandler) OnToolStart(string, string, map[string]interface{})

func (NoOpEventHandler) OnTurnComplete

func (NoOpEventHandler) OnTurnComplete(int, bool, int64, float64)

type Option

type Option func(*Renderer)

Option configures a Renderer.

func WithColorMode

func WithColorMode(m ColorMode) Option

WithColorMode sets the color output mode.

func WithEventHandler

func WithEventHandler(h EventHandler) Option

WithEventHandler sets the semantic event handler.

func WithVerbosity

func WithVerbosity(v Verbosity) Option

WithVerbosity sets the verbosity level.

type Palette

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

Palette controls whether ANSI color codes are emitted.

type QuestionOption

type QuestionOption struct {
	Label       string
	Description string
}

QuestionOption represents an option for a question.

func ParseQuestionOptions

func ParseQuestionOptions(optionsRaw []interface{}) []QuestionOption

ParseQuestionOptions parses options from the AskUserQuestion input. Options can be strings or objects with label/description fields.

type Renderer

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

Renderer handles terminal output with ANSI colors and verbosity control.

func New

func New(out io.Writer, opts ...Option) *Renderer

New creates a Renderer with functional options. Defaults: VerbosityNormal, ColorAuto, no event handler.

func NewRenderer

func NewRenderer(out io.Writer, verbose bool) *Renderer

NewRenderer creates a renderer writing to the given output. If verbose is false, uses VerbosityNormal; if true, VerbosityVerbose. Colors are automatically disabled if output is not a terminal.

func NewRendererWithEvents

func NewRendererWithEvents(out io.Writer, verbose bool, handler EventHandler) *Renderer

NewRendererWithEvents creates a renderer that also emits semantic events.

func NewRendererWithOptions

func NewRendererWithOptions(out io.Writer, verbose, noColor bool) *Renderer

NewRendererWithOptions creates a renderer with explicit color control.

func (*Renderer) APIRetry

func (r *Renderer) APIRetry(attempt, maxRetries int, errorMsg string)

APIRetry prints an API retry notification.

func (*Renderer) AuthStatus

func (r *Renderer) AuthStatus(isAuthenticating bool, output []string)

AuthStatus prints an authentication status update.

func (*Renderer) CommandEnd

func (r *Renderer) CommandEnd(callID string, exitCode int, durationMs int64)

CommandEnd prints the completion of a command execution. In verbose mode, prints one line per tool: [command] ✓ or [command] ✗ exit N

func (*Renderer) CommandOutput

func (r *Renderer) CommandOutput(callID, chunk string)

CommandOutput accumulates streaming command output for a given call.

func (*Renderer) CommandStart

func (r *Renderer) CommandStart(callID, command string)

CommandStart records the start of a command execution.

func (*Renderer) CompactBoundary

func (r *Renderer) CompactBoundary(trigger string)

CompactBoundary prints a conversation compaction event.

func (*Renderer) Error

func (r *Renderer) Error(err error, context string)

Error prints an error message.

func (*Renderer) HasOutput

func (r *Renderer) HasOutput(callID string) bool

HasOutput reports whether any command output has been accumulated for callID.

func (*Renderer) HookLifecycle

func (r *Renderer) HookLifecycle(phase, hookName string)

HookLifecycle prints a hook execution event.

func (*Renderer) PlanComplete

func (r *Renderer) PlanComplete(input map[string]interface{})

PlanComplete prints the plan completion summary.

func (*Renderer) PostTurnSummary

func (r *Renderer) PostTurnSummary(title, description string)

PostTurnSummary prints a background post-turn summary.

func (*Renderer) Question

func (r *Renderer) Question(question string, options []string)

Question prints a question prompt with simple string options.

func (*Renderer) QuestionAutoAnswer

func (r *Renderer) QuestionAutoAnswer(question, header string, options []QuestionOption, selectedIdx int)

QuestionAutoAnswer renders a question with all options, highlighting the auto-selected answer.

func (*Renderer) QuestionWithOptions

func (r *Renderer) QuestionWithOptions(question, header string, options []QuestionOption)

QuestionWithOptions prints a question prompt with labeled options.

func (*Renderer) RateLimit

func (r *Renderer) RateLimit(status string, utilization *float64)

RateLimit prints a rate limit notification.

func (*Renderer) Reasoning

func (r *Renderer) Reasoning(text string)

Reasoning is an alias for Thinking, matching the Codex renderer API.

func (*Renderer) Reset

func (r *Renderer) Reset()

Reset clears any in-flight render state. Call this from session teardown (context cancellation, session end, crash recovery) so commands that never received a CommandEnd and partial text chunks do not leak into later sessions.

Reset does not flush text or write any output; it only drops state.

func (*Renderer) SessionInfo

func (r *Renderer) SessionInfo(sessionID, model string)

SessionInfo prints session metadata (session ID, model).

func (*Renderer) SetEventHandler

func (r *Renderer) SetEventHandler(handler EventHandler)

SetEventHandler sets or updates the event handler. Pass nil to disable.

func (*Renderer) Status

func (r *Renderer) Status(msg string)

Status prints a status message. Shown at Normal+ verbosity.

func (*Renderer) TaskNotification

func (r *Renderer) TaskNotification(taskID, status, summary string)

TaskNotification prints a task completion notification.

func (*Renderer) TaskProgress

func (r *Renderer) TaskProgress(taskID, description string)

TaskProgress prints a task progress update.

func (*Renderer) TaskStarted

func (r *Renderer) TaskStarted(taskID, description string)

TaskStarted prints a task/sub-agent start notification.

func (*Renderer) Text

func (r *Renderer) Text(text string)

Text prints streaming text output.

func (*Renderer) Thinking

func (r *Renderer) Thinking(thinking string)

Thinking prints thinking/reasoning output in dim italic.

func (*Renderer) ToolComplete

func (r *Renderer) ToolComplete(name string, input map[string]interface{})

ToolComplete prints the completed tool input.

func (*Renderer) ToolExecutionProgress

func (r *Renderer) ToolExecutionProgress(name, id string, elapsedSec float64)

ToolExecutionProgress prints elapsed time for a running tool.

func (*Renderer) ToolProgress

func (r *Renderer) ToolProgress(chunk string)

ToolProgress prints streaming tool input chunks.

func (*Renderer) ToolResult

func (r *Renderer) ToolResult(content interface{}, isError bool)

ToolResult prints the result of the most recently completed tool execution.

func (*Renderer) ToolResultForTool

func (r *Renderer) ToolResultForTool(name, id string, content interface{}, isError bool)

ToolResultForTool prints the result of the specified tool execution.

func (*Renderer) ToolStart

func (r *Renderer) ToolStart(name, id string)

ToolStart prints the start of a tool invocation.

func (*Renderer) TurnCompleteWithTokens

func (r *Renderer) TurnCompleteWithTokens(success bool, durationMs, inputTokens, outputTokens int64)

TurnCompleteWithTokens prints a turn summary with token counts (Codex-style).

func (*Renderer) TurnSummary

func (r *Renderer) TurnSummary(turnNumber int, success bool, durationMs int64, costUSD float64)

TurnSummary prints a summary of the completed turn.

type Verbosity

type Verbosity int

Verbosity controls how much detail is printed to the terminal.

const (
	// VerbosityQuiet shows only errors and final results.
	VerbosityQuiet Verbosity = iota
	// VerbosityNormal shows text, tool names, errors, turn summaries,
	// rate limit warnings, and auth status. Tool results are hidden
	// unless they are errors.
	VerbosityNormal
	// VerbosityVerbose shows all tool results (truncated), thinking,
	// task/hook lifecycle, API retries, and compact boundaries.
	VerbosityVerbose
	// VerbosityDebug shows everything: full tool results, streaming tool
	// input, state changes, API retries, compact boundaries.
	VerbosityDebug
)

func ParseVerbosity

func ParseVerbosity(s string) Verbosity

ParseVerbosity converts a string to a Verbosity level. Returns VerbosityNormal for unrecognized values.

func (Verbosity) String

func (v Verbosity) String() string

String returns a human-readable name for the verbosity level.

Jump to

Keyboard shortcuts

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