out

package
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: AGPL-3.0 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 out renders every command result as a stable, machine-readable envelope. AI agents parse stdout; humans can ask for -o text.

Index

Constants

View Source
const (
	ExitOK       = 0
	ExitError    = 1 // generic / internal error
	ExitUsage    = 2 // bad flags or arguments
	ExitNotFound = 3 // host, key, secret, job ... not found
	ExitConnect  = 4 // ssh connection / auth / host-key failure; CONNECTION_LOST: broke mid-command
	ExitRemote   = 5 // remote command ran but exited non-zero
	ExitPolicy   = 6 // blocked for safety: needs a person's yes or a person at a terminal
	ExitTimeout  = 7 // command or connection timed out
	ExitConflict = 8 // precondition failed (e.g. replace text not found / ambiguous)
)

Exit codes are part of the public contract. Agents may branch on them.

View Source
const (
	PersonalEmail  = "email"
	PersonalPhone  = "phone"
	PersonalCard   = "card"
	PersonalIBAN   = "iban"
	PersonalColumn = "column"
)

Personal kinds, as they appear in [hidden: KIND].

View Source
const Contract = 2

Contract is the version of komando's output contract: the envelope, field names, error codes and exit codes. Within one contract, fields and codes are only added, never renamed or removed; a breaking change raises it (docs/design/principles.md, section 5).

View Source
const Hidden = "[hidden]"

Hidden is what a password, key or token looks like in masked output. Writing text that still holds it is refused (HasHidden), so a masked file read by an agent can never be written back over the real one.

View Source
const UsageHint = "run with --help or `komando schema` for the full command reference"

UsageHint is the hint a usage error gets when its command gives none. The error handler swaps it for the failing command's own --help and example, which says more than a hint shared by every command.

Variables

View Source
var OnGenericText func(command string)

OnGenericText, when set (by a test), hears each command whose -o text came from the generic renderer, not a Text method of its own (S-9.7).

View Source
var UnicodeOK = func() bool {
	if os.Getenv("TERM") == "dumb" {
		return false
	}
	for _, k := range []string{"LC_ALL", "LC_CTYPE", "LANG"} {
		if v := os.Getenv(k); v != "" {
			v = strings.ToLower(v)
			return strings.Contains(v, "utf-8") || strings.Contains(v, "utf8")
		}
	}
	return true
}

UnicodeOK reports whether the terminal can show non-ASCII marks. TERM=dumb cannot. The locale is the first of LC_ALL, LC_CTYPE and LANG that is set, as the C library picks it; a set locale that does not name UTF-8 (C, POSIX, en_US.ISO-8859-1) cannot either. With no locale at all (Windows, most containers) komando keeps the marks: those terminals show UTF-8.

View Source
var WidthOf = func(w io.Writer) int {
	f, ok := w.(*os.File)
	if !ok {
		return 0
	}
	fd := int(f.Fd())
	if !term.IsTerminal(fd) {
		return 0
	}
	n, _, err := term.GetSize(fd)
	if err != nil || n <= 0 || n > maxTextWidth {
		return maxTextWidth
	}
	return n
}

WidthOf is the width komando lays out lines written to w at (errors, hints, warnings on stderr; a text result on stdout): min(terminal width, 80) when w is a terminal, 0 (no wrapping) for anything else (a pipe, a file, an app's writer), so an AI agent, a script or `komando doctor -o text | grep` reads each line whole. A call asks it of its own writers, never the process's. Tests replace it.

Functions

func ApprovalFlag added in v0.13.0

func ApprovalFlag(e *Error) string

ApprovalFlag is the flag that lets a safety stop through (--yes, --allow-dangerous, --reveal), or "" for a stop no flag lifts.

func DefaultHint added in v0.9.0

func DefaultHint(exit int) string

DefaultHint is the next step for an error whose code gives no hint of its own, by its exit code.

func HasHidden added in v0.2.0

func HasHidden(s string) bool

HasHidden reports whether text holds a value komando hid from an agent ([hidden], [hidden: KIND] or [secret:NAME]). Such text must not be written to a file or a database: it would destroy the real value.

func Headline added in v0.13.0

func Headline(m map[string]any, dryRun bool) string

Headline is headline, for a command's own Text method.

func KindWord added in v0.13.0

func KindWord(kind string) string

KindWord is the word people read for an inventory kind: a host is a server, a key an SSH key (S-8.4). Codes and commands keep the kind.

func Marks added in v0.13.0

func Marks(s string) string

Marks returns s as the terminal can show it: unchanged, or with komando's marks (✓ ✗ ● → · …) spelled in ASCII when UnicodeOK is false. It is used for komando's own lines (errors, hints, warnings, status), never for a result's text: that is data (a file, a row, a log line) and is shown as it is.

func MaskJSONFields added in v0.15.0

func MaskJSONFields(b []byte, names map[string]bool, label string) []byte

MaskJSONFields replaces, in a JSON document, the whole value of every object key in names (lower case; at any depth) with label. A document it cannot read comes back hidden whole.

func MaskPersonal added in v0.7.0

func MaskPersonal(s string) string

MaskPersonal hides email addresses, phone numbers, payment card numbers and IBANs in text.

func MaskSecrets added in v0.2.0

func MaskSecrets(s string) string

MaskSecrets hides secret-looking values in plain text.

func NoCR added in v0.14.0

func NoCR(s string) string

NoCR shows a carriage return that does not end a line as \r. A line that starts with a server's or pod's name ("[web1] ...") goes through it, so the server cannot move back over its name and print another one.

func NotFoundCode added in v0.13.0

func NotFoundCode(kind string) string

NotFoundCode is the code NotFound gives for kind. A server, conn and VPN share one: a name komando does not know, whatever kind was meant. TestNotFoundKinds keeps every caller's kind in notFoundCodes.

func NoteText added in v0.15.0

func NoteText(s string) string

NoteText makes a line komando writes about something (an error, a hint, a doctor detail) safe to show wherever it is read: SafeText, and no colour sequences or carriage returns either.

func PersonalLabel added in v0.7.0

func PersonalLabel(kind string) string

PersonalLabel is how a hidden value of kind looks.

func SafeText added in v0.2.0

func SafeText(s string) string

SafeText makes text from servers and databases safe to print on a terminal: escape sequences other than colours (window titles, clipboard writes, cursor moves that fake output), a colour sequence that hides text (SGR 8), control characters and bidi overrides (which make text read in another order than it runs) are shown as \e, \xNN and \uNNNN instead of being run by the terminal. Tabs, newlines and carriage returns stay (progress bars use \r; NoCR takes it out where a line carries a server's name).

func Wrap added in v0.13.0

func Wrap(text string, labelWidth, width int) string

Wrap fills text into lines of at most width columns: the first line starts after a label of labelWidth columns, later lines with a hanging indent of two spaces. It breaks only at spaces, never inside a backticked command, so a command stays whole for copying; a word longer than the line (a URL, a path) gets a line of its own and is not cut. width 0 returns text unchanged. Text with its own line breaks keeps them.

Types

type Envelope

type Envelope struct {
	OK      bool   `json:"ok"`
	Command string `json:"command"`
	Data    any    `json:"data,omitempty"`
	Error   *Error `json:"error,omitempty"`
	Meta    Meta   `json:"meta"`
}

Envelope is the single JSON object printed on stdout for every command.

type Error

type Error struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	Hint    string `json:"hint,omitempty"`
	// Suggestion is the word komando thinks was meant ("did you mean"),
	// S-8.8; the hint has the whole command line with it; additive
	Suggestion string `json:"suggestion,omitempty"`
	// Details holds what a person or an app needs to act on this stop,
	// when the message alone is not enough (EMPTY_FOLDER_CONFIRM_REQUIRED:
	// the folders); additive
	Details any `json:"details,omitempty"`
	Exit    int `json:"-"`
	// Final: no flag lifts this stop (no --yes, --allow-dangerous or
	// --reveal), so an AI agent is not told that adding one asks the user
	Final bool `json:"-"`
	// contains filtered or unexported fields
}

Error is a typed error carrying a stable code, an exit code and a hint that tells the agent how to recover.

func Errf

func Errf(exit int, code, hint, format string, a ...any) *Error

func NotFound

func NotFound(kind, name string) *Error

NotFound is the error for a name komando does not know, worded the one way S-8.4 asks: no <kind> named "<name>".

func Usage

func Usage(format string, a ...any) *Error

func (*Error) Cancel added in v0.11.0

func (e *Error) Cancel(msg string) *Error

Cancel marks a stop the person chose at the terminal: text mode prints msg alone, without "Stopped:", a hint or the code.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Flags added in v0.13.0

func (e *Error) Flags() []string

Flags are every flag the real run needs, from this stop's code and Need, sorted; none for a stop no flag lifts.

func (*Error) ForKind added in v0.15.0

func (e *Error) ForKind(kind string) *Error

func (Error) MarshalJSON added in v0.9.0

func (e Error) MarshalJSON() ([]byte, error)

MarshalJSON writes the error with a hint even when the code that made it gave none: error.hint always says what to try next. The message, hint and suggestion are made safe to show (noteText), as text mode prints them: they carry words from servers and tools, and whoever reads the JSON (an app, an agent's terminal) shows them to a person.

func (*Error) Need added in v0.13.0

func (e *Error) Need(flags ...string) *Error

Need records flags the real run needs besides the one this stop's code names, e.g. --yes on a protected target for a POLICY_BLOCKED stop.

func (*Error) NoFlag added in v0.8.0

func (e *Error) NoFlag() *Error

NoFlag marks a stop that no flag lifts (see Final).

func (*Error) PlainHint added in v0.12.0

func (e *Error) PlainHint() *Error

PlainHint drops the hint Say set for a person, so text mode prints Hint as JSON does (an AI agent reads -o text too).

func (*Error) Say added in v0.11.0

func (e *Error) Say(msg, hint string) *Error

Say sets the words a person reads in text mode. JSON is unchanged, so agents and scripts keep the stable Message and Hint. An empty hint keeps the usual one.

func (*Error) TextHint added in v0.11.0

func (e *Error) TextHint() string

func (*Error) TextMessage added in v0.11.0

func (e *Error) TextMessage() string

TextMessage and TextHint are what text mode prints.

func (*Error) Wanted added in v0.15.0

func (e *Error) Wanted() string

Wanted is the kind a TARGET_NOT_FOUND looked for (host, conn or vpn), "" for any; ForKind sets it. Text mode words the error with it; JSON carries one code for every kind.

func (*Error) WithHint

func (e *Error) WithHint(h string) *Error

type HostKey added in v0.8.0

type HostKey struct {
	Host        string `json:"host"`
	Address     string `json:"address"`
	Type        string `json:"key_type"`
	Fingerprint string `json:"fingerprint"` // SHA256:...
}

HostKey is a server's host key, as komando pinned it.

type Meta

type Meta struct {
	Contract   int    `json:"contract"`
	Version    string `json:"version"`
	DurationMS int64  `json:"duration_ms"`
	DryRun     bool   `json:"dry_run,omitempty"`
	// Skipped lists targets a selector picked that this command cannot work
	// with (a database picked by `exec @prod`, a server by `db query @prod`).
	Skipped []Skipped `json:"skipped,omitempty"`
	// WouldBeBlocked: under --dry-run, the safety stop the real run would hit
	WouldBeBlocked *Error `json:"would_be_blocked,omitempty"`
	// WouldNeed: under --dry-run, every approval flag the real run needs
	// (--allow-dangerous and --yes for a delete on a protected server),
	// sorted; would_be_blocked names only the first stop.
	WouldNeed []string `json:"would_need,omitempty"`
	// HostKeysPinned lists the servers whose host key this command trusted
	// for the first time (host_key_policy accept-new). Nothing proved the
	// key is the server's: compare the fingerprint with the server's own.
	HostKeysPinned []HostKey `json:"host_keys_pinned,omitempty"`
	// Warnings are things that went wrong beside the result (an audit
	// record that could not be written); they are on stderr too.
	Warnings []string `json:"warnings,omitempty"`
	// Truncated: a list stopped at --limit; more items are there
	// (--limit 0 shows them all).
	Truncated bool `json:"truncated,omitempty"`
	// NotSimulated: under --dry-run, the steps the dry run could not try
	// without making them (a MySQL DDL statement commits by itself); the
	// rest of the preview holds, these were not checked.
	NotSimulated []string `json:"not_simulated,omitempty"`
}

type Printer

type Printer struct {
	Format  string // json | text
	Pretty  bool
	Version string
	Start   time.Time
	DryRun  bool
	W       io.Writer // stdout: the envelope, or the text
	// Err is stderr: notes, warnings, hints and, in text mode, errors.
	// nil writes them nowhere.
	Err io.Writer
	// Width is the column a person's stderr lines wrap at, 0 for none (a
	// pipe, an AI agent). nil wraps nothing.
	Width func() int

	// Secrets returns the secret values (by name) that must never appear in
	// output: remote files, logs and command output that happen to contain
	// one show [secret:NAME] instead. It is called once, on first use.
	// Set it when making the printer; once others may use the printer
	// (AddValue runs from other goroutines), change it with SetSecrets.
	Secrets  func() map[string]string
	NoRedact bool // `secret get --reveal`: a person asked for the value
	// Mask also hides values that look like passwords, keys and tokens
	// (mask.go). It is on for AI agents.
	Mask bool
	// Personal, with Mask, also hides personal data: email addresses,
	// phone numbers, card numbers and IBANs (personal.go). A command that
	// reads data from a target turns it on when the mask_personal setting
	// covers that target.
	Personal bool
	// contains filtered or unexported fields
}

Printer prints one call's output. Each call has its own (no two calls share one), set up by the root command.

func (*Printer) AddValue added in v0.13.0

func (p *Printer) AddValue(v string)

AddValue hides v in this command's output from now on, as [hidden]: a secret komando read from somewhere other than its vault (env:, file:, op://, bw://, kdbx:, vault:, a cloud secret manager), which the vault's list does not have.

func (*Printer) BinaryHidden added in v0.15.0

func (p *Printer) BinaryHidden(raw []byte) bool

BinaryHidden reports whether raw holds something this printer hides: a vault value for anyone and, for an AI agent, a secret by its shape or (where personal data is hidden) personal data.

func (*Printer) Blocked added in v0.2.0

func (p *Printer) Blocked() *Error

Blocked is the stop WouldBlock recorded, or nil.

func (*Printer) Cut added in v0.13.0

func (p *Printer) Cut(n int)

Cut records that a list stopped at --limit n (meta.truncated). In text mode one line on stderr says so after the result.

func (*Printer) CutNoted added in v0.13.0

func (p *Printer) CutNoted()

CutNoted is Cut for a command whose own text already says the list was cut: meta.truncated only, no extra stderr line.

func (*Printer) Event

func (p *Printer) Event(v any)

Event emits one NDJSON line (--stream and follow modes).

func (*Printer) Fail

func (p *Printer) Fail(command string, err error) int

func (*Printer) ForgetAdded added in v0.15.0

func (p *Printer) ForgetAdded()

ForgetAdded drops what AddValue added: a value one command read is not hidden in the next one's output (tests run many in one process). The CLI calls it before the command counts as running, never while it runs: another command's secret added after that must stay hidden.

func (*Printer) HoldsVaultValue added in v0.14.0

func (p *Printer) HoldsVaultValue(s string) bool

HoldsVaultValue reports whether s holds a value from the vault (Printer.Secrets), raw, never what only looks like a secret.

func (*Printer) HostKeyPinned added in v0.8.0

func (p *Printer) HostKeyPinned(k HostKey)

HostKeyPinned records a host key trusted on first use, for meta.host_keys_pinned (a person reads it on stderr).

func (*Printer) Longest added in v0.16.0

func (p *Printer) Longest() int

Longest is the length of the longest value this printer hides.

func (*Printer) NewValueScanner added in v0.13.0

func (p *Printer) NewValueScanner() *ValueScanner

NewValueScanner watches for p's secret values; with none, it finds nothing.

func (*Printer) NotSimulated added in v0.13.0

func (p *Printer) NotSimulated(what string)

NotSimulated records a step a dry run left out because trying it would make it (meta.not_simulated).

func (*Printer) Print

func (p *Printer) Print(command string, data any, softErr *Error)

Print prints data. A non-nil softErr marks the envelope not-ok but still carries data (e.g. multi-host exec with partial failures).

func (*Printer) Redact added in v0.2.0

func (p *Printer) Redact(s string) string

Redact hides secret values in plain text.

func (*Printer) RedactExact added in v0.13.0

func (p *Printer) RedactExact(s string) string

RedactExact hides only the exact values komando keeps secret, never what merely looks like one: for text a person must see whole (the approval window), where a pattern could hide more than a value.

func (*Printer) RedactJSON added in v0.15.0

func (p *Printer) RedactJSON(b []byte) []byte

RedactJSON hides in a JSON document what this printer hides in its JSON output, for a caller that shows the document as text too.

func (*Printer) Reset added in v0.2.0

func (p *Printer) Reset()

Reset forgets what one command recorded and set, so the next command in the same call starts as a new printer does (a call may run many commands: tests, an app). Format, W, Err and Width are the call's and stay, and so do the values AddValue hid: another running command may have added one already (ForgetAdded).

func (*Printer) SetSecrets added in v0.14.0

func (p *Printer) SetSecrets(f func() map[string]string)

SetSecrets makes f the printer's Secrets: the values of the one before are no longer hidden as [secret:NAME], and f is called on first use. It locks by itself, so it is safe while AddValue runs elsewhere.

func (*Printer) Skip added in v0.2.0

func (p *Printer) Skip(s Skipped)

Skip records a target the command leaves out. It is reported in meta.skipped, and on stderr in text mode. A command may resolve its target more than once (exec checks the OS mix first): the same target is listed once.

func (*Printer) Spare added in v0.15.0

func (p *Printer) Spare(s string)

Spare stops hiding, in this printer's output, the vault values that s holds (and their encoded forms): s is what an AI agent typed itself. A [secret:NAME] in place of its own guess would tell it the guess is a secret; shown as typed, a right guess and a wrong one look the same.

func (*Printer) Stderr added in v0.14.0

func (p *Printer) Stderr() io.Writer

Stderr is where the printer's stderr lines go.

func (*Printer) View added in v0.3.0

func (p *Printer) View(s string) View

View hides in s what Redact hides, keeping track of where each value was.

func (*Printer) Warn added in v0.12.0

func (p *Printer) Warn(msg string)

Warn records something that went wrong beside the result: it goes to stderr now and into meta.warnings of the envelope printed after it.

func (*Printer) WouldBlock added in v0.2.0

func (p *Printer) WouldBlock(e *Error)

WouldBlock records, under --dry-run, the first safety stop the real run would hit (meta.would_be_blocked), and the flag every stop needs (meta.would_need).

type PrinterTexter added in v0.14.0

type PrinterTexter interface{ TextFor(p *Printer) string }

PrinterTexter is a Texter whose text depends on the printer that prints it: its dry run ("would write" instead of "wrote"), or its stderr and what it hides, for the lines a result sends there.

type Skipped added in v0.2.0

type Skipped struct {
	Name   string `json:"name"`
	Kind   string `json:"kind"` // host, or the conn kind (postgres, redis, ...)
	Reason string `json:"reason"`
}

type Texter

type Texter interface{ Text() string }

Texter lets a result type provide a human rendering for -o text.

type ValueScanner added in v0.13.0

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

ValueScanner watches bytes written to it for a vault value (as is, or in the base64 and URL forms Redact also hides), across write edges. It is for data that cannot be rewritten with [secret:NAME] (a binary file), so it can be stopped instead.

func (*ValueScanner) Found added in v0.13.0

func (s *ValueScanner) Found() bool

Found reports whether a value was seen.

func (*ValueScanner) Write added in v0.13.0

func (s *ValueScanner) Write(b []byte) (int, error)

Write never fails.

type View added in v0.3.0

type View struct {
	Text string
	// contains filtered or unexported fields
}

View is a text as output for an AI agent shows it (Printer.Redact), with the place of every hidden value in the original text. A command that edits what the agent saw (fs replace) works on Text and maps its edits back with Source, so neither its result nor its errors depend on a value the agent never saw.

func (View) Hidden added in v0.3.0

func (v View) Hidden(orig string) []string

Hidden returns the values of orig (the text v was made from) that v shows as labels, in order.

func (View) Masked added in v0.3.0

func (v View) Masked() bool

Masked reports whether v hides a value the agent does not know by name: a label other than a vault value's [secret:NAME].

func (View) Source added in v0.3.0

func (v View) Source(a, b int) (start, end int, ok bool)

Source maps Text[a:b] to the stretch of the original it shows. ok is false when a or b falls inside a label: the edit would cut a hidden value.

Jump to

Keyboard shortcuts

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