console

package
v0.43.2 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 17 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 console owns the CLI's injected process environment and output policy.

Index

Constants

View Source
const (
	MaxDiagnosticRunes  = 320
	MaxValidationFields = 3
)

Default diagnostic limits keep incidental server context out of ordinary command output. Verbose diagnostics retain the complete safe original data.

View Source
const (
	ExitOK      = 0
	ExitFailure = 1
	ExitUsage   = 2
	ExitAuth    = 4
)

Exit codes of the process; see the package documentation.

View Source
const (
	ColorKey    = "\x1b[36m"
	ColorString = "\x1b[32m"
	ColorNumber = "\x1b[33m"

	ColorReset = "\x1b[0m"
)

ANSI escape sequences of the color palette. The five colors are the basic ones every terminal theme keeps readable on both dark and light backgrounds: cyan keys, green strings, yellow numbers, magenta booleans, and gray null.

View Source
const (
	// TypeUsage is a command line the CLI cannot accept: an unknown command,
	// a missing or surplus argument, or an unknown or malformed flag.
	TypeUsage = "usage"

	// TypeNotConfigured means the command needs a setting that is absent,
	// such as the inspector URL.
	TypeNotConfigured = "not_configured"

	// TypeUnreachable means the inspector did not answer.
	TypeUnreachable = "unreachable"

	// TypeUnauthorized means the inspector refused the credentials (HTTP 401).
	TypeUnauthorized = "unauthorized"

	// TypeInvalidInput is a request the server rejected as invalid.
	TypeInvalidInput = "invalid_input"

	// TypeFileConflict means existing files block a local action; nothing was
	// written.
	TypeFileConflict = "file_conflict"

	// TypeToolError is a failure reported by a remote tool or the protocol.
	TypeToolError = "tool_error"

	// TypeInternal is an unexpected local failure, such as an I/O error.
	TypeInternal = "internal"
)

The closed list of error types. Every error document carries exactly one in error.type, so scripts and agents branch on the cause without parsing the message. A remote tool may report types of its own, which pass through; the CLI never invents one outside this list.

View Source
const DefaultTimeout = 10 * time.Second

DefaultTimeout bounds each non-waiting request without --request-timeout.

Variables

This section is empty.

Functions

func Command added in v0.37.0

func Command(args []string, extra ...string) string

Command renders an invocation of this CLI as one pasteable command line: the program name, then the arguments quoted where a shell needs it, then extra. The value of a token flag, whether "--token VALUE" or "--token=VALUE", is replaced by "$ARKOREN_MCP_TOKEN".

func ConciseContext

func ConciseContext(raw jsontext.Value) bool

ConciseContext permits small, useful failure context but rejects large lists even when compact JSON encodes them in only a few hundred bytes.

func ConflictingPaths

func ConflictingPaths(operation, destination string, paths []string) error

ConflictingPaths returns the local TypeFileConflict failure without embedding its file list in text. Verbose reporting exposes the retained paths as a JSON array.

func DiagnosticText

func DiagnosticText(text string) (string, bool)

DiagnosticText abbreviates long messages at a rune boundary. Verbose mode bypasses this helper, so complete safe context remains available explicitly.

func ExitCodeFor added in v0.37.0

func ExitCodeFor(errorType string) int

ExitCodeFor maps an error type to the process exit code: usage and not_configured are 2, unauthorized is 4 (ExitAuth) and every other type, including a tool-provided one, is 1.

func Fail added in v0.37.0

func Fail(errorType string, steps []Step, format string, args ...any) error

Fail returns a failure of the given type, with the steps that resolve it and the exit code of the type. The message is formatted like fmt.Errorf, so %w keeps the cause available to errors.Is and errors.As.

func Format added in v0.36.0

func Format(raw []byte, look Style) []byte

Format writes a JSON document in the given style: translated text when the style asks for it, laid-out JSON otherwise.

func Quote added in v0.37.0

func Quote(arg string) string

Quote returns arg as one shell word: unchanged when it holds only characters a shell leaves alone, single-quoted otherwise. Use it for every value interpolated into a step's command.

func Render

func Render(raw []byte, look Style) []byte

Render re-lays out a JSON document in the given style, preserving the order of object members exactly as the server sent them and the exact text of every scalar. It does not go through a Go map or number type, so key order and large numbers survive. Invalid JSON is returned unchanged, which shows the user what the server really sent.

func Text added in v0.36.0

func Text(raw []byte, color bool) []byte

Text translates a JSON document into aligned, human-readable text: objects become labeled lines and sections, arrays of flat objects become tables, and short arrays of scalars become comma lists while longer ones become bullets. Null, empty strings, empty arrays and empty objects are omitted; a document with nothing left prints nothing. A top-level object with a "summary" string, or the single member "error" or "warning" holding a "message", starts with a marked headline; see [textWriter.document]. An object with an "items" array is a list: see [listing]. Every RFC 3339 timestamp prints as "2026-11-23 10:00:01 (5s ago)" or "(in 59m)", relative to the current time; use TextAt to choose the clock. A number member named "<name>_ms" or "<name>_bytes" prints in readable units under the label "<name>" ("duration_ms": 12.5 becomes "Duration 12.5ms"). The result has no trailing newline. Invalid JSON is returned unchanged, like Render.

func TextAt added in v0.36.0

func TextAt(raw []byte, color bool, now time.Time) []byte

TextAt is Text with an explicit clock: now is what relative times such as "5s ago" are measured against, so callers and tests control it.

func UsageError

func UsageError(format string, args ...any) error

UsageError returns a TypeUsage failure that exits with ExitUsage. The message must name the argument or flag at fault and, when the choice is closed, the accepted values; the run adds the "See usage" step.

func VersionInfo

func VersionInfo() string

VersionInfo returns the CLI's own version: the module version it was built at, or "(devel)" for a local build.

func WriteJSON

func WriteJSON(out io.Writer, value any, presentation Style) error

WriteJSON encodes before writing and checks short writes on both boundaries. The style may translate the document into text; see Format. A document whose text is empty, because every member was omitted, writes nothing.

Types

type Action added in v0.36.0

type Action string

Action is the kind of one Change. The text presentation colors each kind, and the string values are part of the JSON contract.

const (
	// ActionCreate is a new file.
	ActionCreate Action = "create"

	// ActionEdit is an insertion into an existing file.
	ActionEdit Action = "edit"

	// ActionRemove is a deleted file.
	ActionRemove Action = "remove"

	// ActionWrite is a file written over a previous version, such as a skill
	// update.
	ActionWrite Action = "write"

	// ActionRequire is a module pinned in go.mod; the path is module@version.
	ActionRequire Action = "require"

	// ActionTidy is a go mod tidy run; the path is go.mod.
	ActionTidy Action = "tidy"
)

The actions of a Change.

type Change added in v0.36.0

type Change struct {
	// Action says what happened to Path.
	Action Action `json:"action"`

	// Path is a slash-separated file path: project-relative for files inside
	// the project, absolute for any other file (a key or certificate written
	// elsewhere), or module@version for [ActionRequire]. The text
	// presentation shortens paths under the working directory.
	Path string `json:"path"`

	// Detail adds context such as the inserted line or "private key". It is
	// omitted when empty.
	Detail string `json:"detail,omitzero"`
}

Change is one effect of a local action, reported in the top-level "changes" array of a result next to its "summary". Local action results order their fields summary, ok or dry_run, command fields, changes, next_steps; the text presentation relies on this shape, see Text.

type ConflictError

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

ConflictError retains file conflicts as data rather than joining them into a potentially enormous message. Constructing it never changes the filesystem.

func (*ConflictError) Error

func (failure *ConflictError) Error() string

Error summarizes collections instead of joining every path into the message.

func (*ConflictError) Report

func (failure *ConflictError) Report(verbose bool) ErrorReport

Report selects either a short conflict summary or the complete structured path list. The original message is identical in both modes; a caller that wants every path offers a --verbose step.

type Environment

type Environment struct {
	// Stdin is read by "--input -".
	Stdin io.Reader

	// Stdout receives results and help; Stderr receives errors and warnings.
	Stdout, Stderr io.Writer

	// Env looks up an environment variable.
	Env func(string) (string, bool)

	// Dir is the working directory: where ./.env and relative @file paths are
	// read from.
	Dir string

	// IsTerminal reports that Stdout is a terminal, which enables color
	// unless NO_COLOR or --no-color say otherwise.
	IsTerminal bool

	// ErrorTerminal reports that Stderr is a terminal independently of Stdout.
	ErrorTerminal bool

	// InputTerminal reports that Stdin is a terminal. Local project creation
	// prompts only with terminal input, independently of output coloring.
	InputTerminal bool

	// Presentation carries formatting options for local results.
	Presentation Globals

	// Now is the clock for relative times in text output; nil uses time.Now.
	Now func() time.Time

	// Invocation is the command line without the program name, as typed. It
	// lets a step repeat the real command, for example with --verbose; nil
	// makes such steps text-only.
	Invocation []string
}

Environment supplies process state without consulting global streams or configuration. Commands retain caller ownership of the injected streams.

func (Environment) DiagnosticStyle

func (env Environment) DiagnosticStyle() Style

DiagnosticStyle uses the same policy as results, but checks stderr's terminal state so redirecting either stream does not style the other one.

func (Environment) OutputStyle added in v0.36.0

func (env Environment) OutputStyle() Style

OutputStyle applies formatting without resolving inspector configuration. A terminal gets translated text unless --json or --compact asks for JSON; any other destination always gets JSON, so scripts and agents can parse it.

func (Environment) Result

func (env Environment) Result(value any) error

Result writes one local result using the remote result presentation policy.

type ErrorDocument added in v0.37.0

type ErrorDocument struct {
	// Error describes the failure.
	Error ErrorReport `json:"error"`

	// NextSteps resolves the failure; it is omitted when nothing helps.
	NextSteps []Step `json:"next_steps,omitzero"`
}

ErrorDocument is what the CLI writes to stderr for a failure: the error and, at the top level beside it, the steps that resolve it.

type ErrorReport

type ErrorReport struct {
	// Message is the safe explanation of the failure. It states what went
	// wrong, never what to do; that belongs in next_steps.
	Message string `json:"message"`

	// Type classifies the failure and is always set: one of the Type
	// constants, or a type a remote tool advertised.
	Type string `json:"type"`

	// Status is an actual HTTP failure Status, never a tool classification.
	Status int `json:"status,omitzero"`

	// Fields contains validation messages keyed by JSON pointer.
	Fields map[string][]string `json:"fields,omitzero"`

	// Sources maps validation pointers to the supplying command-line argument.
	Sources map[string]string `json:"sources,omitzero"`

	// Details contains safe nonvalidation tool context.
	Details jsontext.Value `json:"details,omitzero"`

	// Destination is the local directory whose existing files blocked an action.
	Destination string `json:"destination,omitzero"`

	// ConflictCount counts all local conflicts, including undisplayed ones.
	ConflictCount int `json:"conflict_count,omitzero"`

	// Conflicts contains complete paths only when verbose output is requested.
	Conflicts []string `json:"conflicts,omitzero"`

	// Truncated reports abbreviated messages or validation context.
	Truncated bool `json:"truncated,omitzero"`

	// OmittedFields counts validation pointers excluded from the default view.
	OmittedFields int `json:"omitted_fields,omitzero"`

	// DetailsOmitted reports safe tool context available with --verbose.
	DetailsOmitted bool `json:"details_omitted,omitzero"`
}

ErrorReport contains diagnostics without repeating the message across protocol title/detail fields. Optional context is omitted when absent. What to do about the failure is never part of it: see ErrorDocument.

func (ErrorReport) Concise

func (report ErrorReport) Concise(verbose bool) ErrorReport

Concise bounds incidental diagnostics without altering remote success data, raw exports, or the underlying error used for classification and exit codes.

type ExitError

type ExitError struct {
	// Code selects the process status after any diagnostic is printed. For a
	// failure with a Type it is [ExitCodeFor] of that type.
	Code int

	// Err is the diagnostic cause; nil suppresses additional error output.
	Err error

	// Type is the error type of the diagnostic, one of the Type constants. When
	// Err is nil it only records what the report already printed (a preview that
	// would fail with a file conflict) and may be empty.
	Type string

	// Steps resolve the failure and become the top-level next_steps of the
	// error document. A usage error without steps gets a "See usage" step for
	// the command that was run.
	Steps []Step
}

ExitError ends the run with a chosen code. A nil Err means everything was already printed (a failing health report or check).

func (*ExitError) Error

func (failure *ExitError) Error() string

Error implements error.

func (*ExitError) Unwrap

func (failure *ExitError) Unwrap() error

Unwrap returns the cause.

type Globals

type Globals struct {
	// URL and Token are explicit flag values, before environment resolution.
	URL, Token string

	// EnvFile is nil unless --env-file was given, including an empty value.
	EnvFile *string

	// Timeout bounds each non-streaming request.
	Timeout time.Duration

	// TimeoutSet distinguishes an explicit deadline from the ordinary default.
	TimeoutSet bool

	// Compact, NoColor, Follow, and Help are the boolean flags.
	Compact, NoColor, Follow, Help bool

	// JSON prints results and errors as JSON even on a terminal.
	JSON bool

	// Verbose includes complete diagnostic context and local file lists.
	Verbose bool
}

Globals holds the global flags of one run.

type Output

type Output struct {
	// Writer receives successful writes with the original byte boundaries.
	Writer io.Writer
	// Err retains the first failure, including a short write without an error.
	Err error
}

Output retains the first stdout failure for run to report after the command returns. This boundary covers direct text, JSON, tabwriter flushes, and follow callbacks alike, without making rendering code own exit policy. It does not buffer or retry writes, and suppresses writes after a failure.

func (*Output) Write

func (output *Output) Write(data []byte) (int, error)

Write forwards data until the first failure and normalizes short writes to io.ErrShortWrite. Returning the retained error also stops follow callbacks immediately; run catches failures from renderers that do not return errors.

type Problem added in v0.37.0

type Problem struct {
	// Rule names the broken rule of a rule-based check, such as a layout rule.
	Rule string `json:"rule,omitzero"`

	// Field names what is wrong when there is no rule: a flag, argument or
	// skill name.
	Field string `json:"field,omitzero"`

	// Path is the file the problem is in, when there is one.
	Path string `json:"path,omitzero"`

	// Line is the 1-based line in Path, when known.
	Line int `json:"line,omitzero"`

	// Message explains the problem.
	Message string `json:"message"`
}

Problem is one finding of a check: a broken layout rule, an invalid file or a stale skill. A check lists them in "problems", an empty array when ok.

type Step added in v0.37.0

type Step struct {
	// Text is one imperative sentence, such as "Enter the project".
	Text string `json:"text"`

	// Command is a single exact, pasteable command line that performs the
	// step. It is omitted when the step needs judgment, several commands or a
	// value only the reader has.
	Command string `json:"command,omitzero"`
}

Step is one thing the reader can do next. Every list of steps is the top-level "next_steps" member of a document, on successes and errors alike.

func VerboseStep added in v0.37.0

func VerboseStep(text string, invocation []string) Step

VerboseStep is the step that repeats the current command with --verbose. With a known invocation it carries the exact command line; without one (a caller that supplied no arguments) it is a text-only step.

type Style

type Style struct {
	// Indent spreads the value over lines indented by two spaces; false
	// writes it on one line without insignificant whitespace.
	Indent bool

	// Color wraps every key and scalar in ANSI colors.
	Color bool

	// Text translates the document into human-readable text with [Text]
	// instead of laying out JSON; [Format] applies it, [Render] ignores it.
	Text bool

	// Now is the time relative timestamps in text are measured against; the
	// zero value means the current time. Tests set it for deterministic output.
	Now time.Time

	// Dir is the working directory. Text output prints paths under it
	// relative to it; JSON always keeps them exact. Empty disables shortening.
	Dir string
}

Style says how Format presents a JSON document.

type Version added in v0.36.0

type Version struct {
	// Version is the module version, or "(devel)" for a local build.
	Version string `json:"version"`

	// Module is the main module path; verbose only.
	Module string `json:"module,omitzero"`

	// GoVersion is the toolchain that built the CLI; verbose only.
	GoVersion string `json:"go_version,omitzero"`

	// Revision is the VCS commit the CLI was built from; verbose only.
	Revision string `json:"revision,omitzero"`

	// RevisionAt is the commit time; verbose only.
	RevisionAt string `json:"revision_at,omitzero"`

	// Modified reports uncommitted changes at build time; verbose only, and
	// absent when the build recorded no VCS state.
	Modified *bool `json:"modified,omitzero"`
}

Version is the JSON document of `arkoren --version`: plain data without a summary. Only Version is present unless verbose output was requested.

func VersionReport

func VersionReport(verbose bool) Version

VersionReport adds only safe build identifiers in verbose mode. Compiler flags, dependency inventories, and local replacement paths are not exposed.

type Warning added in v0.37.0

type Warning struct {
	// Message is one sentence.
	Message string `json:"message"`

	// Details are further sentences or facts, printed as bullets.
	Details []string `json:"details,omitzero"`
}

Warning is something the reader should know although the command succeeded, listed in the top-level "warnings" member and printed as "! message".

Jump to

Keyboard shortcuts

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