utils

package
v1.20.1 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 39 Imported by: 2 modules, 1 package

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

Index

Constants

View Source
const (
	AuthMFARequired  = "auth_mfa_required"
	UsernameRequired = "user_username_required"

	// Codes the server sends on its own 401s.
	AuthTokenMissing         = "auth_token_missing"
	AuthAuthenticationFailed = "auth_authentication_failed"

	// AuthTokenMFAMissing rides a 401: the token was issued without the
	// workspace's sign-in MFA, and only a new login, which runs it, can lift it.
	AuthTokenMFAMissing = "auth_token_mfa_missing"

	// AuthVerificationUnavailable rides a 503: the server could not check the
	// credential, did not reject it, and a retry can succeed.
	AuthVerificationUnavailable = "auth_verification_unavailable"

	// WorkspaceSudoWithMFAStepUpUnavailable rides a 403: the server refused a
	// change to the workspace's sudo-with-MFA setting because this deployment has
	// no MFA sign-in. Retrying or completing MFA cannot lift it.
	WorkspaceSudoWithMFAStepUpUnavailable = "workspace_sudo_with_mfa_step_up_unavailable"

	// WorkspaceExecutionControlConsoleOnly rides a 403: the edit loosens
	// execution control, which the server accepts from the web console only.
	WorkspaceExecutionControlConsoleOnly = "workspace_execution_control_console_only"

	// ApprovalPolicyConsoleOnly rides a 403: approval policies are written from
	// the web console only.
	ApprovalPolicyConsoleOnly = "approval_policy_console_only"

	// SudoPolicyConsoleOnly rides a 403: sudo policies are created or
	// widened from the web console only.
	SudoPolicyConsoleOnly = "sudo_policy_console_only"

	// A work session can receive a session-authorized sudo policy without a
	// person's approval from the web console only; both names ride a 403.
	WorkSessionSudoBypassConsoleOnly            = "work_session_sudo_bypass_console_only"
	WorkSessionSessionAuthorizedSudoConsoleOnly = "work_session_session_authorized_sudo_console_only"

	// SudoVerifyCredentialCannotProveMFA rides a 403 on sudo grant verification:
	// the credential is an API token, a service token or a non-interactive token,
	// so it cannot complete sudo MFA. Signing in interactively can.
	SudoVerifyCredentialCannotProveMFA = "sudo_verify_credential_cannot_prove_mfa"

	// Refusals of a session-authorized sudo policy bound to an AI agent session, both
	// on a 403. NeedsPresence: the write would leave the policy on an agent
	// session without a person proving presence for that request (a fresh MFA
	// on an interactive login). NeedsApproval: a direct write of such a policy
	// is refused; it has to arrive as a modification of the session, which a
	// person approves.
	SudoPolicyBypassAgentSessionNeedsPresence            = "sudo_policy_bypass_agent_session_needs_presence"
	SudoPolicyBypassAgentSessionNeedsApproval            = "sudo_policy_bypass_agent_session_needs_approval"
	SudoPolicySessionAuthorizedAgentSessionNeedsPresence = "sudo_policy_session_authorized_agent_session_needs_presence"
	SudoPolicySessionAuthorizedAgentSessionNeedsApproval = "sudo_policy_session_authorized_agent_session_needs_approval"

	// Codes the server sends on its own 404/429/406/415 refusals, with no detail.
	APINotFound             = "api_not_found"
	APIRateLimited          = "api_rate_limited"
	APINotAcceptable        = "api_not_acceptable"
	APIUnsupportedMediaType = "api_unsupported_media_type"

	// Codes the Elasticsearch cursor paginator sends when a walk cannot go on: an
	// expired snapshot (400), a mismatched cursor (400), or no snapshot opened (503).
	APICursorExpired     = "api_cursor_expired"
	APIInvalidCursor     = "api_invalid_cursor"
	APISearchUnavailable = "api_search_unavailable"

	// ServerBusyWithUserWork means the server refused a disruptive action; --force overrides it.
	ServerBusyWithUserWork = "server_busy_with_user_work"

	// ServerPAMInstallUnsupported rides a 400: the host has no alpamon-pam
	// package path (macOS, Windows, or an unknown package manager).
	ServerPAMInstallUnsupported = "server_pam_install_unsupported"

	// ServerPAMInstallRequiresSudoWithMFA rides a 400: refused while "Use sudo with MFA"
	// is off, or always on a deployment that cannot complete an MFA step-up.
	ServerPAMInstallRequiresSudoWithMFA = "server_pam_install_requires_sudo_with_mfa"

	// ServerPAMInstallInProgress rides a 409: an alpamon-pam install is already pending.
	ServerPAMInstallInProgress = "server_pam_install_in_progress"

	// CommandInlineCredential means the server refused a command whose command line carries a
	// credential (a -p/--password flag, a KEY=VALUE secret such as PGPASSWORD=..., or a
	// user:pass@host connection string) it would otherwise store. Move the secret to --env. The
	// exec and websh help and the README's "When a command is denied" section repeat these forms;
	// update them together.
	//
	// The CLI deliberately does not expose the server's credential_exposure_acknowledged override:
	// it records the exposure rather than preventing it (hygiene, not authorization, with no role
	// gate), so it would be a one-flag way past the gate where rewriting with --env costs the same.
	// --env stays the only path.
	CommandInlineCredential = "command_inline_credential"

	// APITokenACLNotAllowed means the token's access control rules do not cover the command, server
	// or file path, so a retry fails the same way; widen them with 'alpacon token acl'. It rides a
	// 403 with no detail, so authStatusCodeMessage in client/client.go renders the message.
	APITokenACLNotAllowed = "api_token_acl_not_allowed"

	// CommandACLMoved rides a 405 on a command-ACL write once command ACLs live on
	// the command pre-approval ledger; codeOnlyMessage in client/client.go renders it.
	CommandACLMoved = "command_acl_moved"

	// AuthInteractiveChannelRequiresPresence rides a 403: a token gets no interactive channel
	// whatever its scopes and ACL rules say; only 'alpacon login' without -t lifts it.
	AuthInteractiveChannelRequiresPresence = "auth_interactive_channel_requires_presence"

	// AuthMFARequiresHumanPrincipal rides a 403: the action needs a person's MFA, which a token
	// (API or service) cannot complete; 'alpacon login' without -t can. Removing the action from
	// the workspace's MFA required actions also lifts it, except for actions the server always
	// holds to this (security settings, sudo and approval policy writes, RBAC roles).
	AuthMFARequiresHumanPrincipal = "auth_mfa_requires_human_principal"

	// The token-scope gate's refusals: the token's scopes do not cover this call, or
	// the server could not resolve the call's action to a scope at all.
	APITokenScopeMissing          = "api_token_scope_missing"
	APITokenScopeActionUnresolved = "api_token_scope_action_unresolved"

	// WorkSession gate codes the server returns.
	WorkSessionRequired         = "work_session_required"
	WorkSessionNotUsable        = "work_session_not_usable"
	WorkSessionNotActive        = "work_session_not_active"
	WorkSessionExpired          = "work_session_expired"
	WorkSessionScopeNotAllowed  = "work_session_scope_not_allowed"
	WorkSessionServerNotAllowed = "work_session_server_not_allowed"
	WorkSessionAssigneeMismatch = "work_session_assignee_mismatch"
	// WorkSessionAgentSessionRequired means the CLI declared an AI agent, and the
	// session it named is a user session. Only an agent session serves it.
	WorkSessionAgentSessionRequired = "work_session_agent_session_required"

	// WorkSessionAccountNotApproved means the command names an account other than
	// the one the session was approved to run as.
	WorkSessionAccountNotApproved = "work_session_account_not_approved"

	// Refusals of the account a work session create names with --account.
	WorkSessionTargetAccountAbsent       = "work_session_target_account_absent"
	WorkSessionTargetAccountNotReachable = "work_session_target_account_not_reachable"
	TargetAccountOtherPerson             = "target_account_other_person"

	// WorkSessionClusterNotAllowed: the cluster a kube session names is not
	// the one its work session targets.
	WorkSessionClusterNotAllowed = "work_session_cluster_not_allowed"

	// Refusals of a work session create's targets and lifetime. A session
	// targets servers or exactly one cluster, never both and never neither; a
	// cluster session holds kube and optionally kube_exec, nothing else, and
	// names no account; and its lifetime stays within the workspace's maximum.
	WorkSessionMixedTargets               = "work_session_mixed_targets"
	WorkSessionNoServers                  = "work_session_no_servers"
	WorkSessionTooManyClusters            = "work_session_too_many_clusters"
	WorkSessionInvalidScope               = "work_session_invalid_scope"
	ClusterNotFound                       = "cluster_not_found"
	WorkSessionTargetAccountNotApplicable = "work_session_target_account_not_applicable"
	WorkSessionExpiresExceedsMaxTTL       = "work_session_expires_exceeds_max_ttl"

	// Refusals of a kube session the server names itself. The cluster's agent
	// is not connected; the agent did not accept the session, which the server
	// then closed; the caller's username cannot be the session's identity,
	// unset on an older server or one the server refuses; and
	// the cluster's RBAC bindings made outside Alpacon grant sessions more than
	// Alpacon does, under a workspace policy that refuses rather than warns.
	ClusterNotConnected              = "cluster_not_connected"
	KubeSessionChannelOpenFailed     = "kube_session_channel_open_failed"
	KubeSessionPrincipalNotSupported = "kube_session_principal_not_supported"
	ClusterRBACDrift                 = "cluster_rbac_drift"

	// WorkSession extension refusals: every 'work-session extend' needs a reason and follows the
	// workspace's approval policy, as 'work-session create' does, and a session holds at most one
	// pending extension request.
	WorkSessionExtensionReasonRequired = "work_session_extension_reason_required"
	WorkSessionExtensionAlreadyPending = "work_session_extension_already_pending"
	// WorkSessionAdmissionDenied means the workspace refuses this request outright
	// (session creation, or an extension)—not a queued request waiting on a
	// human, a hard no.
	WorkSessionAdmissionDenied = "work_session_admission_denied"

	// ExitCodeGeneralError is the process exit code for an ordinary failure, the one
	// NewExitError exits with. Name it when calling NewExitErrorWithCode so the general case
	// reads like the specific ones beside it.
	ExitCodeGeneralError = 1

	// ExitCodeUsageError is the process exit code for a flag or argument a command rejected, in
	// Cobra's parse or in its own validation. Unlike ExitCodeGeneralError, it means the invocation
	// itself was wrong, so scripts and AI agents fix the command line rather than retry it unchanged.
	ExitCodeUsageError = 2

	// ExitCodeWorkSessionDenied is the process exit code for WorkSession gate refusals.
	ExitCodeWorkSessionDenied = 3

	// ExitCodePendingApproval is the process exit code for an action whose approval is still open:
	// a sudo denial that created an approval request, a work session created pending, or a wait
	// that ended (timed out or interrupted) undecided. Unlike ExitCodeWorkSessionDenied nothing was
	// refused, so scripts and AI agents wait or check later.
	ExitCodePendingApproval = 4

	// PendingApprovalStatus is the stable machine-readable status string emitted
	// under --output json when an action is pending human approval.
	PendingApprovalStatus = "pending_approval"

	// ExitCodeServerBusy is the process exit code for a disruptive server action refused because
	// the server has active user work (server_busy_with_user_work). Scripts and AI agents retry
	// when the server is idle, or re-run with --force.
	ExitCodeServerBusy = 5

	// ExitCodeNotApproved is the process exit code for an awaited approval that ended without the
	// grant: rejected, expired, revoked, cancelled, or completed. Where ExitCodePendingApproval
	// means the outcome is still open, this one tells scripts and AI agents to stop re-requesting
	// approval. A command the server denied after submission (status denied) exits with it too.
	ExitCodeNotApproved = 6

	// ExitCodePurposeRequired is the process exit code for a command the verification gate parked
	// while it asks what the command is for. No approval request exists, so it is not
	// ExitCodePendingApproval: the caller answers with 'alpacon exec purpose' within about a minute
	// rather than wait.
	ExitCodePurposeRequired = 7

	// PurposeRequiredStatus is the stable machine-readable status string emitted
	// under --output json when a command is parked awaiting its purpose.
	PurposeRequiredStatus = "purpose_required"

	// ExitCodeUpdateAvailable is the process exit code for `alpacon update --check` finding a newer
	// release; a failed check exits ExitCodeGeneralError instead.
	ExitCodeUpdateAvailable = 8

	// ExitCodeMFARequired is the process exit code for an action that waits on a person to finish
	// MFA in a browser: 'alpacon kube mfa' run where stdin or stderr is not a terminal, or its
	// wait ending before the MFA did. Nothing was refused, and the link it printed still works after the CLI exits, so
	// scripts and AI agents hand the link to the person and run the command again once they are
	// done, rather than fixing the command line or giving up.
	ExitCodeMFARequired = 9
)
View Source
const (
	ServiceTokenAccountNotOwn     = "service_token_account_not_own"
	ApplicationSystemUserNotFound = "application_system_user_not_found"
)
View Source
const (
	ErrorCodeUsage                = "usage_error" // local validation that never reached the server
	ErrorCodeNotLoggedIn          = "not_logged_in"
	ErrorCodeConfirmationRequired = "confirmation_required"
	ErrorCodeNetwork              = "network_error"
	ErrorCodeNotApproved          = "not_approved"
	ErrorCodeMFARequired          = "mfa_required"
	ErrorCodeCLI                  = "cli_error"
)

Synthetic error_code values: the CLI's own, for failures the server sent no code for.

View Source
const (
	ApprovalExpired     = "approval_expired"
	ApprovalCancelled   = "approval_cancelled"
	ApprovalRuleChanged = "approval_rule_changed"
)
View Source
const (
	OutputFormatTable = "table"
	OutputFormatJSON  = "json"
)

Valid values for the --output persistent flag.

View Source
const (

	// PollMaxBackoffTick caps a backoff gap, in multiples of the base tick. It is exported so a
	// poll loop's own test can state its capped wait as a constant expression.
	PollMaxBackoffTick = 60

	// MaxConsecutivePollFailures bounds a wait's ride through failed polls: a run
	// of them means the CLI cannot reach the server, and saying so beats
	// reporting an outcome nobody read.
	MaxConsecutivePollFailures = 5

	// PollMaxThrottleExtensions bounds how many times a throttled poll may push its
	// deadline out. A duration budget alone is not enough: a server answering
	// Retry-After: 1 would buy a whole window one second at a time.
	PollMaxThrottleExtensions = 60
)
View Source
const (
	OperationCommand = "command"
	OperationWebFTP  = "webftp"
	OperationWebsh   = "websh"
	OperationTunnel  = "tunnel"
	// OperationKube targets a cluster rather than a server: it needs a session
	// that holds the kube scope and targets that cluster.
	OperationKube = "kube"
)

WorkSessionExitError names one of these operations in its diagnostic. Each is also the WorkSession scope that the operation requires.

View Source
const (

	// DebugEnvVar turns on diagnostic output that would be noise in normal use.
	// Any value other than "0" or "false" enables it, matching how the other
	// ALPACON_* switches are read.
	DebugEnvVar = "ALPACON_DEBUG"
)
View Source
const (
	// DefaultApprovalWaitTimeout is the shared --wait default, so exec, work-session create and
	// event wait match; --wait-approval can exceed it.
	DefaultApprovalWaitTimeout = 5 * time.Minute
)
View Source
const DevVersion = "dev" // What Version carries when no -ldflags set it.
View Source
const GatePlan = "plan"

GatePlan is the "gate" of a plan refusal, whose own message already states when its limit resets, so no Retry-After action is added for it.

View Source
const LoginWithoutTokenHint = "'alpacon login' without -t (on a machine without a browser, open the printed URL on another device)"

LoginWithoutTokenHint is the login that opens an interactive channel; the device code URL is printed whether or not a browser opens, so a headless machine needs no flag.

View Source
const MaxServerHintBytes = 256

MaxServerHintBytes is the most a server hint may take: the server keeps its own hints within it, and the CLI cuts anything longer, since nothing between the server and this process is trusted to have kept it.

View Source
const PurposeDemandLead = "Purpose required—the verification gate held this command and is asking what it is for. " +
	"No approver has been notified: state the purpose and it is judged again, once, with that in hand."

PurposeDemandLead is the first half of the message every surface prints for an open demand. `exec` and `exec logs` differ only in what they add after it, so keeping the shared half here stops one from being reworded without the other.

Variables

View Source
var CommandName string

CommandName is the full command path without the root name ("workspace ls"), set by the entry point.

View Source
var ErrInvalidID = errors.New("invalid id")

ErrInvalidID marks a local refusal of an ID that is unsafe as a URL path segment.

View Source
var ErrNoChanges = errors.New("no changes made")

ErrNoChanges reports that an edit left nothing to apply.

View Source
var ErrNotLoggedIn = errors.New("not logged in")

ErrNotLoggedIn marks a missing config file; a malformed or unreadable one stays cli_error.

View Source
var LocalSignalConsoleOrigin = func() (workspaceURL, baseDomain string) { return "", "" }

The command layer supplies config access without making utils import config.

View Source
var OutputFormat string

OutputFormat holds the value of the --output persistent flag.

Stdio is the process's own streams, which the package-level print helpers write through.

View Source
var Version string = DevVersion

Functions

func AgentSessionScope added in v1.16.0

func AgentSessionScope(operation string) string

AgentSessionScope is the scope an agent session requests for operation. An agent cannot hold websh, so its work on the server runs through exec under the command scope instead.

func BeginTokenRefresh added in v1.20.0

func BeginTokenRefresh() func()

BeginTokenRefresh keeps process exit from interrupting a rotated token's save.

func Blue

func Blue(value string) string

Blue returns a bold blue string for terminal output.

func Bold added in v1.2.0

func Bold(value string) string

Bold returns a bold string for terminal output.

func BoolPointerToString

func BoolPointerToString(value *bool) string

func BuildURL

func BuildURL(basePath, relativePath string, params map[string]string) (string, error)

BuildURL joins relativePath onto basePath with a trailing slash and params as the query, or returns the parse error when basePath is not a URL.

func CheckPositiveInt added in v1.20.0

func CheckPositiveInt(flagName string, value int) error

CheckPositiveInt returns the usage failure for an integer flag that is not positive, or nil.

func ClassifyError added in v1.18.0

func ClassifyError(err error) string

ClassifyError picks the error_code for err: the server's code, else http_<status>, else network_error for a transport failure, else cli_error. A missing config file is not_logged_in.

func CleanupTempFile added in v1.5.0

func CleanupTempFile(f *os.File)

CleanupTempFile closes f and removes the backing file. Safe to call with a nil pointer. Intended as the cleanup half of SpoolToTempFile.

func CliDebug added in v1.11.0

func CliDebug(msg string, args ...any)

CliDebug prints a diagnostic message to stderr when DebugEnvVar is set. Use it for a rare branch with no visible symptom, such as a degrade that succeeds and so looks exactly like the path it replaced. It takes the same break off a spinner line as CliWarning, since the refresh-token degrade logs inside the "Refreshing access token..." spinner.

func CliError

func CliError(msg string, args ...any)

CliError handles all error messages in the CLI.

func CliErrorEnvelopeWithExit added in v1.7.2

func CliErrorEnvelopeWithExit(operation string, err error, format string, args ...any)

CliErrorEnvelopeWithExit reports a failure and exits 1, or 2 when err or an argument is a usage error; json mode carries err's code.

func CliErrorEnvelopeWithExitCode added in v1.9.2

func CliErrorEnvelopeWithExitCode(code int, operation string, err error, format string, args ...any)

CliErrorEnvelopeWithExitCode is CliErrorEnvelopeWithExit with a caller-chosen exit code, for refusals a script branches on (e.g. ExitCodeNotApproved).

func CliErrorWithExit added in v1.0.0

func CliErrorWithExit(msg string, args ...any)

CliErrorWithExit handles all error messages in the CLI and exits 1, or 2 when an argument is a usage error. Under --output json it prints one envelope instead, classified from the first error in args, and no footer.

func CliInfo

func CliInfo(msg string, args ...any)

CliInfo handles all informational messages in the CLI.

func CliParseErrorWithExit added in v1.18.0

func CliParseErrorWithExit(cmd *cobra.Command, format, msg string)

CliParseErrorWithExit reports a command line cmd could not parse and exits 2 in format, the --output value its caller found before the parse stopped; table mode points to cmd's help.

func CliSuccess added in v1.2.0

func CliSuccess(msg string, args ...any)

CliSuccess handles all success messages in the CLI.

func CliUsageErrorEnvelopeWithExit added in v1.7.2

func CliUsageErrorEnvelopeWithExit(operation string, format string, args ...any)

CliUsageErrorEnvelopeWithExit reports a bad flag or argument and exits 2 with error_code usage_error. The envelope keeps no error from args, so a server refusal must not go through it.

func CliUsageErrorWithExit added in v1.18.0

func CliUsageErrorWithExit(msg string, args ...any)

CliUsageErrorWithExit reports a flag or argument the command rejected and exits 2 with error_code usage_error.

func CliWarning

func CliWarning(msg string, args ...any)

CliWarning handles all warning messages in the CLI.

A warning can land while a Spinner is animating stderr (SaveStreamAtomic warns from inside a download), and the spinner leaves the cursor mid-line. The break and the text go out as one write so a spinner frame cannot wedge itself between them.

func CompactStrings added in v1.5.0

func CompactStrings(ss []string) []string

CompactStrings trims whitespace from each element and drops empty entries.

func Confirm added in v1.20.0

func Confirm(msg string, args ...any) (bool, error)

Confirm asks msg as a yes/no question before a destructive action. A decline prints the cancel notice and returns false, which the caller ends on with exit 0; a non-interactive run returns the exit-2 failure.

func DebugEnabled added in v1.11.0

func DebugEnabled() bool

DebugEnabled reports whether diagnostic output is turned on.

func DecodeJWTPayload added in v1.1.0

func DecodeJWTPayload(token string) (map[string]any, error)

DecodeJWTPayload decodes the payload (second segment) of a JWT token without verifying the signature. Returns the claims as a map.

func DeleteFile

func DeleteFile(path string) error

func EmitLocalSignal added in v1.20.0

func EmitLocalSignal(kind localsignal.Kind, fields localsignal.Fields, sources ...SignalOriginSource)

func Exit added in v1.20.0

func Exit(code int)

Exit lets a refresh save its rotated token before terminating the process.

func ExitIfUsageError added in v1.18.0

func ExitIfUsageError(code int, operation string, err error, format string, args ...any)

ExitIfUsageError exits 2 for a report that would exit 1 when err, or an error among args, answers IsUsageError, as newExitError and newEnvelopeExitError do for an ExitError. Otherwise it returns.

func ExitWithFailureJSON added in v1.18.0

func ExitWithFailureJSON(f Failure)

ExitWithFailureJSON writes the envelope to stderr and exits with f.ExitCode under --output json; in table mode it returns so the caller's own message and exit stay as they were.

func ExtractBaseDomain added in v1.1.0

func ExtractBaseDomain(workspaceURL string) string

ExtractBaseDomain extracts the top-level base domain from a workspace URL. For example, "https://myws.us1.alpacon.io" returns "alpacon.io". Returns "" if the hostname has fewer than 3 parts (e.g. self-hosted with no subdomain).

func ExtractWorkspaceName added in v0.4.0

func ExtractWorkspaceName(workspaceURL string) string

ExtractWorkspaceName extracts workspace name from workspace URL.

func FormatJSON added in v1.6.0

func FormatJSON(value any) (string, error)

func FormatTimestamp added in v1.16.0

func FormatTimestamp(ts string) string

FormatTimestamp renders a server timestamp in the local zone.

func FprintExitError added in v1.20.0

func FprintExitError(w io.Writer, e *ExitError)

FprintExitError writes what PrintExitError writes to w.

func FprintFailureJSON added in v1.20.0

func FprintFailureJSON(w io.Writer, f Failure)

FprintFailureJSON writes f's envelope to w whatever the output format, for a caller that has checked for --output json and returns the exit rather than taking it.

func GetCLIVersion

func GetCLIVersion() string

func GetUserAgent

func GetUserAgent() string

func Green

func Green(value string) string

Green returns a bold green string for terminal output.

func HTTPErrorCode added in v1.18.0

func HTTPErrorCode(status int) string

HTTPErrorCode is the synthetic code for a server or proxy answer that carried none.

func HTTPStatusCode added in v1.8.1

func HTTPStatusCode(err error) int

HTTPStatusCode returns the HTTP status carried by err, or 0 if none. Along a chain the outermost status wins. An error that joins several (a BatchError, errors.Join, fmt.Errorf with more than one %w) has a status only when the statuses found across its tree, nested joins included, are all one; two or more distinct statuses give 0.

func HandleCommonErrors added in v1.0.0

func HandleCommonErrors(err error, serverName string, callbacks ErrorHandlerCallbacks) error

HandleCommonErrors handles an MFA or username-required refusal through callbacks and retries the operation, returning nil once it succeeds. Only the tagged error of the operation's side-effecting request (MarkSubmission) is handled; any other error came after the operation took effect and is returned as is. The error it returns carries no tag.

func HasFieldErrorCode added in v1.20.0

func HasFieldErrorCode(err error, field, code string) bool

HasFieldErrorCode reports whether the server's field_errors list an entry for field with code.

func HasUnixModes added in v1.20.0

func HasUnixModes() bool

HasUnixModes reports whether the OS has Unix permission bits. Windows has none, and Chmod there toggles the read-only attribute instead.

func HiddenCount added in v1.20.0

func HiddenCount(hidden *int) int

HiddenCount reads a count of targets the server left unnamed; nil (a server older than Alpacon Server 2.48.0) and a negative value count as none.

func HintOnly added in v1.18.0

func HintOnly(message string, refusal error) error

HintOnly returns an error that reads as message and carries refusal's hint, sanitized, and nothing else of it: no code, no status, no wrapped error. A timeout uses it to keep the guidance of the refusal its last poll got while staying a timeout to everything that classifies errors, such as the work-session gate or an MFA retry. Without a hint on refusal it is a plain error.

func InteractiveOnly added in v1.15.0

func InteractiveOnly(err error, action string) error

InteractiveOnly rewrites a token's refusal of an action only an interactive login may take; a scope refusal counts, since granting the scope only reaches the next refusal. A refusal carrying the server's hint is returned as it is: the hint is the guidance.

func IsAgentForbiddenScope added in v1.16.0

func IsAgentForbiddenScope(scope string) bool

IsAgentForbiddenScope reports whether an agent session cannot hold scope.

func IsApprovalLapse added in v1.20.0

func IsApprovalLapse(code string) bool

IsApprovalLapse reports an approval that ended without a denial.

func IsC1OrDEL added in v1.11.0

func IsC1OrDEL(r rune) bool

IsC1OrDEL reports whether r is DEL or a C1 control. A terminal decodes U+009B as an 8-bit CSI, so these open a control sequence that the escape pass never sees: it matches ESC-led forms alone.

func IsControlRune added in v1.9.0

func IsControlRune(r rune) bool

IsControlRune reports whether r is a C0, DEL, or C1 control character (the last can introduce CSI/OSC on 8-bit terminals).

func IsFatalClientError added in v1.9.2

func IsFatalClientError(status int) bool

IsFatalClientError reports whether a 4xx will fail the same way on retry.

func IsHookError added in v1.20.0

func IsHookError(err error) bool

IsHookError reports whether err came from a hook MarkHookErrors wrapped.

func IsInteractiveShell added in v0.4.4

func IsInteractiveShell() bool

IsInteractiveShell checks if the current program is running in an interactive terminal.

func IsLocalTarget added in v0.4.0

func IsLocalTarget(target string) bool

IsLocalTarget checks if a target string represents a local location.

func IsRefusalStatus added in v1.18.0

func IsRefusalStatus(statusCode int) bool

IsRefusalStatus reports whether statusCode is one the server answers a coded refusal with, the only responses whose "hint" is the server's guidance rather than a request field of that name.

func IsRemoteTarget added in v0.4.0

func IsRemoteTarget(target string) bool

IsRemoteTarget reports whether target holds a colon and is not spelled as a local path: a ./, ../, .\, ..\, \\ or / prefix, C:\x, or C:/x on Windows.

func IsReplacementTempName added in v1.12.0

func IsReplacementTempName(name string) bool

IsReplacementTempName reports whether name is a createReplacementTempFile staging file. A write still in flight wears the same name and takes no lock any sweeper can see, so a caller must age one out rather than trust a lock.

func IsRetryLaterStatus added in v1.9.2

func IsRetryLaterStatus(status int) bool

IsRetryLaterStatus reports whether a 4xx is asking to be retried rather than refusing.

func IsSubmissionError added in v1.16.0

func IsSubmissionError(err error) bool

IsSubmissionError reports whether err, as returned and not through any wrapping, is the tagged error of an operation's side-effecting request.

func IsTransientRequestError added in v1.11.1

func IsTransientRequestError(err error) bool

IsTransientRequestError reports whether err may not repeat on the next attempt. A missing status covers a request that never reached the server and a response that failed to decode, so a caller must bound its retries.

func IsUUID

func IsUUID(str string) bool

func IsUnprocessedRequestError added in v1.15.0

func IsUnprocessedRequestError(err error) bool

IsUnprocessedRequestError reports whether err shows the server did not act on the request: the dial failed, or the server answered 429 or 503. Unlike IsTransientRequestError it leaves out a lost response, 502 and 504, which can follow a request that ran, so a non-idempotent request may be resent on it. Only a MarkSubmission-tagged error qualifies.

func IsUsageError added in v1.18.0

func IsUsageError(err error) bool

IsUsageError reports whether MarkUsageError tagged err or an error it wraps; a server's usage_error code does not count, since only this process knows its command line was wrong.

func JoinReached added in v1.20.0

func JoinReached(names []string, hidden *int, noun string) string

JoinReached joins names and says how many more are hidden ("web-1 and 2 more", or "2 servers you cannot access" with no name left); noun is singular, and names are returned unsanitized.

func LastOutputPaged added in v1.20.0

func LastOutputPaged() bool

LastOutputPaged reports whether WriteToPager's last flush ran a pager, not a stdout fallback, so a caller can repeat on stderr what the pager scrolled away.

func MarkApprovalSignaled added in v1.20.0

func MarkApprovalSignaled(err error) error

func MarkHookErrors added in v1.20.0

func MarkHookErrors(c *cobra.Command) (restore func())

MarkHookErrors wraps what every error-returning hook of c and its subcommands returns, so IsHookError can tell a command's own failure from Cobra's parse error. restore puts the original hooks back.

func MarkNotLoggedIn added in v1.18.0

func MarkNotLoggedIn(err error) error

MarkNotLoggedIn tags err with ErrNotLoggedIn and leaves its message as it was.

func MarkSubmission added in v1.16.0

func MarkSubmission(err error) error

MarkSubmission tags err, if any, as the error of the request that carries the operation's side effect (the command submission, an upload or download create, a session create, a one-request change), or of a lookup before it. Only such an error says whether the server acted, so only it can be retried after MFA or ridden through when unprocessed.

The tag is read off the error as returned, never through wrapping, so a later request's error and a wrapped tagged error count as untagged, which means "the operation already took effect": HandleCommonErrors passes it through. The status and dial error underneath stay readable.

func MarkUsageError added in v1.18.0

func MarkUsageError(err error) error

MarkUsageError tags err as a command-line mistake, so ClassifyError reports usage_error for it.

func NewEnvelopeExitError added in v1.20.0

func NewEnvelopeExitError(operation string, err error, msg string, args ...any) error

NewEnvelopeExitError is the failure CliErrorEnvelopeWithExit reports: exit 1 with the footer, or 2 when err or an argument is a usage error; json mode classifies err under operation.

func NewEnvelopeExitErrorWithCode added in v1.20.0

func NewEnvelopeExitErrorWithCode(code int, operation string, err error, msg string, args ...any) error

NewEnvelopeExitErrorWithCode is the failure CliErrorEnvelopeWithExitCode reports: the given exit and no footer, or exit 2 when code is 1 and err or an argument is a usage error.

func NewExitError added in v1.20.0

func NewExitError(msg string, args ...any) error

NewExitError is the failure CliErrorWithExit reports: exit 1 with the issue footer, or 2 when an argument is a usage error.

func NewExitErrorWithCode added in v1.20.0

func NewExitErrorWithCode(code int, msg string, args ...any) error

NewExitErrorWithCode returns a failure with the given exit code and no footer, for an expected refusal scripts branch on.

func NewExitErrorWithErrorCode added in v1.20.0

func NewExitErrorWithErrorCode(exitCode int, errorCode, msg string, args ...any) error

NewExitErrorWithErrorCode names the json error_code (an ErrorCode* constant); table mode follows the exit code, so only exit 1 keeps the report footer.

func NewMFARequiredExitError added in v1.20.1

func NewMFARequiredExitError(operation, message string, next []NextAction) error

NewMFARequiredExitError returns the exit-9 failure for an action that waits on a person to finish MFA in a browser: message on a warning line and next under a "Next:" list in table mode, or one error envelope with error_code mfa_required and next as its next_actions under --output json. Nothing was refused, so no server error rides along and no footer is printed.

func NewParseExitError added in v1.20.0

func NewParseExitError(cmd *cobra.Command, format, msg string) error

NewParseExitError is the failure CliParseErrorWithExit reports. It applies format, as that does.

func NewSilentExitError added in v1.20.0

func NewSilentExitError(code int) error

NewSilentExitError returns a failure with the given exit code that prints nothing, for a command that wrote its own failure line.

func NewUsageEnvelopeExitError added in v1.20.0

func NewUsageEnvelopeExitError(operation, msg string, args ...any) error

NewUsageEnvelopeExitError is the failure CliUsageErrorEnvelopeWithExit reports.

func NewUsageExitError added in v1.20.0

func NewUsageExitError(msg string, args ...any) error

NewUsageExitError is the failure CliUsageErrorWithExit reports: exit 2 with error_code usage_error.

func NextPollBackoff added in v1.11.1

func NextPollBackoff(tick time.Duration, attempt int, retryAfter time.Duration) time.Duration

NextPollBackoff returns the gap after a failed poll; attempt is the failure count so far, 0 for the first. A server-sent retryAfter wins but shares the cap, so a hostile value cannot park the loop until the deadline.

func NextPollTick added in v1.11.1

func NextPollTick(tick, elapsed time.Duration) time.Duration

NextPollTick widens the gap as the wait ages; elapsed is its age.

func OpenBrowser added in v1.3.3

func OpenBrowser(url string)

OpenBrowser opens url in the user's default browser. It does nothing when the browser cannot be opened (headless server, SSH session, container) or another process opened one recently.

Set ALPACON_NO_BROWSER=1 to disable it.

func OutputFormatIn added in v1.18.0

func OutputFormatIn(args []string) string

OutputFormatIn is the last --output value before any "--" in args, for a command line whose parse stopped before reaching it.

func ParseErrorGateAndMissing added in v1.13.2

func ParseErrorGateAndMissing(err error) (string, []string)

ParseErrorGateAndMissing returns the "gate" and "missing" fields a coded 402/403/405/429 carried, or ("", nil) if err carries none. Unlike ParseErrorResponse this has no textual fallback: every producer of these fields is a *apiError in client/client.go, which always implements gateGuidanceError, so there is no legacy string form to recover one from.

func ParseErrorResponse added in v0.4.0

func ParseErrorResponse(err error) (string, string)

ParseErrorResponse prefers a typed code anywhere in the chain over text: a wrapper's message can quote server-supplied text, such as a rejected ID, that reads as a code.

func ParseIntList added in v1.20.0

func ParseIntList(input string) ([]int, error)

ParseIntList parses a comma-separated list of integers, or returns the exit-1 failure on any other value.

func ParsePositiveDuration added in v1.9.1

func ParsePositiveDuration(flagName, raw string) (time.Duration, error)

ParsePositiveDuration parses a duration flag value, rejecting non-positive ones. It trims surrounding whitespace so every duration flag normalizes input the same way.

func ParseRefusalHint added in v1.18.0

func ParseRefusalHint(body []byte, statusCode int) string

ParseRefusalHint returns the "hint" string a 402/403/405/429 body carries, sanitized (SanitizeServerHint), or "" when there is none or nothing printable is left of it. A server that predates the field sends none. A request that does not go through the shared client reads its refusal's hint here, so its error can carry one too.

func ParseRefusalNext added in v1.18.0

func ParseRefusalNext(body []byte, statusCode int) string

ParseRefusalNext returns the "next" string a 402/403/405/429 body carries, or "" on any other status, where a field of that name is a request field.

func ParseServerTarget added in v1.20.1

func ParseServerTarget(server, username string) (host, user string)

ParseServerTarget splits user@host into host and user; a non-empty username wins over the inline one. A target holding a colon is returned untouched.

func PartialTableExitError added in v1.20.0

func PartialTableExitError(rows any, msg string, args ...any) error

PartialTableExitError prints the reason to stderr and rows to stdout, then returns a silent ExitCodeGeneralError, since the warning is the failure line, or PrintTable's failure when rows do not print. It does not check for empty rows: a caller with none to show returns an ordinary failure instead.

func PrettyJSON

func PrettyJSON(data []byte) (*bytes.Buffer, error)

func PrintDeviceCodePrompt added in v1.18.0

func PrintDeviceCodePrompt(w io.Writer, verificationURI, userCode string) (printedURI string)

PrintDeviceCodePrompt prints the device code prompt and returns the URL it printed, the one the browser must open, so the operator lands on the address they read. Both values come from the authorization server: each is sanitized as a single line, since a newline would let the server write its own line into the prompt. Sanitizing runs before Blue and Bold, since sanitizing afterward would strip their escape sequences.

func PrintExitError added in v1.20.0

func PrintExitError(e *ExitError)

PrintExitError writes e to stderr: the error line, the server's hint and the footer, or one envelope under --output json.

func PrintHeader

func PrintHeader(header string)

func PrintJSONError added in v1.6.0

func PrintJSONError[T any](w io.Writer, envelope JSONErrorEnvelope[T])

func PrintJSONValue added in v1.6.0

func PrintJSONValue(w io.Writer, value any) error

func PrintJson

func PrintJson(body []byte) error

PrintJson prints body to stdout as indented JSON, or returns the exit-1 failure when body is not JSON.

func PrintList added in v1.20.0

func PrintList[T any](rows []T, err error, failMsg string) error

PrintList prints a list a paginated read returned with err. On a nil err it is PrintTable; otherwise it prints the rows as partial through PartialTableExitError, or fails with failMsg when there are none.

func PrintListTo added in v1.20.0

func PrintListTo[T any](s *IOStreams, rows []T, err error, failMsg string) error

PrintListTo is PrintList on s; a generic function, since Go methods take no type parameters.

func PrintPendingApproval added in v1.7.2

func PrintPendingApproval(message, requestID string, retry NextAction, extra ...NextAction)

PrintPendingApproval reports an action that awaits out-of-band human approval and was not waited on: a {"status":"pending_approval", ...} envelope on stdout under --output json, else an actionable message on stderr. requestID may be empty. retry leads the next actions and keeps its Command a pure executable string, any hint in Description; extra follows the console pointer. It never exits, so the exit-code contract stays with the caller.

func PrintPurposeAccepted added in v1.12.0

func PrintPurposeAccepted(commandID string)

PrintPurposeAccepted reports a recorded purpose. There is no verdict yet—the command re-enters judgment on the worker—so the result names where to read the outcome rather than pretending to carry it.

func PrintPurposeDemand added in v1.12.0

func PrintPurposeDemand(message, commandID string, expiresAt *time.Time)

PrintPurposeDemand reports a command the gate parked to ask its purpose: a {"status":"purpose_required", ...} envelope on stdout under --output json, else an actionable message on stderr. A nil expiresAt reports no deadline. It never exits, so the exit-code contract stays with the caller.

func PrintPurposeRefused added in v1.12.0

func PrintPurposeRefused(commandID string, cause error)

PrintPurposeRefused reports a rejected answer. The server answers a settled command and an answer from the wrong principal with one code, so neither this message nor the envelope can say which happened—hence the pointer at the command's own state rather than a guess, and never at a resubmission. It never exits; the caller owns the exit-code contract.

func PrintRefusalHints added in v1.18.0

func PrintRefusalHints(w io.Writer, err error)

PrintRefusalHints writes err's refusal guidance to w, one "Hint:" line per RefusalNextActions entry, for output written outside the Cli* helpers.

func PrintTable

func PrintTable(slice any) error

PrintTable prints a slice of row structs as a table, or as JSON under --output json. It returns the exit-1 failure when slice is not a slice or does not marshal.

func ProcessEditedData

func ProcessEditedData(originalData []byte) (any, error)

ProcessEditedData opens originalData as pretty JSON in the editor and returns the edited JSON, or ErrNoChanges when the bytes are unchanged.

func PromptForBool

func PromptForBool(prompt string) bool

func PromptForPassword

func PromptForPassword(promptText string) (string, error)

PromptForPassword reads a password after promptText; Ctrl+C returns a silent exit-1 failure.

func ProtectRefreshOnSignal added in v1.20.0

func ProtectRefreshOnSignal() func()

ProtectRefreshOnSignal lets an active grant save before a terminating signal is re-raised.

func RawTerminalHintLines added in v1.18.0

func RawTerminalHintLines(err error) string

RawTerminalHintLines renders err's refusal guidance for a terminal that may be in raw mode, where a bare newline leaves the cursor where it stood: one "Hint:" line per RefusalNextActions entry, each ending in \r\n.

func ReadInput added in v1.20.0

func ReadInput(promptText string) (string, error)

ReadInput reads one line from stdin after promptText, or returns the exit-1 failure on no input.

func ReadInputWithDefault added in v1.20.0

func ReadInputWithDefault(promptText, defaultValue string) (string, error)

func ReadIntInput added in v1.20.0

func ReadIntInput(promptText string, defaultValue int) (int, error)

func ReadRequiredInput added in v1.20.0

func ReadRequiredInput(promptText string) (string, error)

ReadRequiredInput is ReadInput that asks again on an empty line.

func ReadRequiredIntInput added in v1.20.0

func ReadRequiredIntInput(promptText string) (int, error)

func Red

func Red(value string) string

Red returns a bold red string for terminal output.

func RedactURL added in v1.16.0

func RedactURL(raw string) string

RedactURL keeps the scheme, host and path of a URL and drops everything that can carry a credential: the query (a presigned URL's signature), the fragment and any userinfo. A string that does not parse is cut at its first '?' or '#'.

func RedactURLError added in v1.16.0

func RedactURLError(err error) error

RedactURLError rewrites a *url.Error in err's chain, which Go prints with the whole request URL, so that neither its message nor its fields carry the URL's query. A presigned URL's query holds a live signature, and an error message ends up in terminals and CI logs. A quoted URL inside the inner error's text, such as an unparsable redirect Location, is redacted too. An error without a *url.Error, or one with nothing to hide, is returned as is.

func RedactURLErrorHostOnly added in v1.16.0

func RedactURLErrorHostOnly(err error) error

RedactURLErrorHostOnly is RedactURLError for a URL whose path is a credential as well: it keeps only the scheme and host, so even a malformed URL that a parser quotes whole reveals nothing past the host.

func RedactURLHostOnly added in v1.16.0

func RedactURLHostOnly(raw string) string

RedactURLHostOnly keeps only the scheme and host of a URL. Use it for a URL whose path carries a credential too, such as a websocket channel token.

func RefusalHint added in v1.18.0

func RefusalHint(err error) string

RefusalHint returns the sanitized hint the first error in err's chain that carries one holds, or "" when none does.

func RejectUnknownSubcommand added in v1.20.0

func RejectUnknownSubcommand(notes ...string) cobra.PositionalArgs

func RemoteFileName added in v1.6.0

func RemoteFileName(remotePath string) (string, error)

RemoteFileName returns the final path component for a remote file path.

func RemotePathBase added in v1.20.0

func RemotePathBase(remotePath string, windows bool) string

RemotePathBase returns a remote path's last element by the server's rules: a Windows server also splits on a backslash, which a Linux or macOS file name may hold.

func RemotePathDir added in v1.20.0

func RemotePathDir(remotePath string, windows bool) string

RemotePathDir returns the directory holding a remote path's last element by the server's rules.

func RemovePrefixBeforeAPI

func RemovePrefixBeforeAPI(url string) string

func ReportNoChanges added in v1.20.0

func ReportNoChanges(err error) bool

ReportNoChanges prints the no-change notice and returns true when err is ErrNoChanges; the caller then ends on exit 0.

func RequireSubcommand added in v1.15.0

func RequireSubcommand(cmd *cobra.Command, notes ...string) error

RequireSubcommand prints cmd's help, then returns an error that points to --help instead of repeating the subcommand list the help already printed.

func RetryAfter added in v1.10.0

func RetryAfter(err error) time.Duration

RetryAfter returns the delay the server asked for on err, or 0 if it sent none.

func RetryAfterFromHeader added in v1.16.0

func RetryAfterFromHeader(header http.Header) time.Duration

RetryAfterFromHeader reads a Retry-After header as delta-seconds, the form a throttled response sends. An HTTP-date, a non-positive or an unrepresentable value reads as no hint, since misreading one would stall a wait.

func Reword added in v1.18.0

func Reword(err error, message string) error

Reword returns an error that reads as message and keeps err in its chain, for a call site that words a failure itself: the Cli* error helpers still find err's server hint and print it under message, and err's code still reads through ParseErrorResponse.

func SanitizeServerHint added in v1.18.0

func SanitizeServerHint(hint string) string

SanitizeServerHint makes a server hint safe to print on one terminal line: escape sequences, format characters and control characters (newlines included) are removed, surrounding space is trimmed, and the result is cut to MaxServerHintBytes without splitting a character.

func SanitizeTerminalBlock added in v1.11.2

func SanitizeTerminalBlock(s string) (clean string, altered bool)

SanitizeTerminalBlock sanitizes per line, because SanitizeTerminalText drops \n and callers print multi-line values the operator saves as files. CRLF is folded first, or a server sending DOS line endings would report every value as altered; a lone \r is still dropped, and does report altered.

func SanitizeTerminalBlockKeepingTabs added in v1.20.0

func SanitizeTerminalBlockKeepingTabs(s string) string

func SanitizeTerminalLine added in v1.11.2

func SanitizeTerminalLine(s string) (clean string, altered bool)

SanitizeTerminalLine is SanitizeTerminalText plus the answer to whether it had to take anything out. A \n counts as altered here: the caller's value is one line by contract, so a newline in it is a forged line and not a line ending worth keeping.

func SanitizeTerminalOneLine added in v1.20.0

func SanitizeTerminalOneLine(s string) string

SanitizeTerminalOneLine fits free text, such as an approver's reason or an agent's tunnel failure, onto one terminal line: line breaks, tabs and runs of space become one space. Whitespace is folded before sanitizing, since SanitizeTerminalText drops \t, \r and \n and would run the words on either side together.

func SanitizeTerminalText added in v1.9.2

func SanitizeTerminalText(s string) string

SanitizeTerminalText strips escape sequences before the standalone control bytes; reversed, ESC alone would go and "[2K" would stay on screen as text.

func SaveFile

func SaveFile(fileName string, data []byte) error

func SaveStreamAtomic added in v1.5.0

func SaveStreamAtomic(fileName string, r io.Reader, newFilePerm os.FileMode) (int64, error)

SaveStreamAtomic writes r to fileName through a temp file, then renames it into place; an existing file keeps its own mode, a new one gets newFilePerm minus the umask.

func ServiceTokenAccountMessage added in v1.20.0

func ServiceTokenAccountMessage(field string) string

ServiceTokenAccountMessage describes the fixed account on a service token's ACL.

func SetOutputFormat added in v1.18.0

func SetOutputFormat(value string) error

SetOutputFormat applies an --output value, refusing anything but table or json as a usage error.

func SetQuery added in v1.18.0

func SetQuery(rawURL string, set map[string]string, del ...string) string

SetQuery changes only the query string, leaving an invalid URL for the caller to handle.

func ShowLogo(rightLines []string)

ShowLogo renders the Pacabot mascot with up to 3 lines of text, beside the art when the terminal is wide enough and below it otherwise, so wrapped lines cannot break the half-block pixel art.

In color mode body cells are spaces on a cyan background, which fills any gap between lines; in plain mode (no TTY or NO_COLOR) they are █ glyphs. The ▄ and ▀ edge half-blocks stay in both modes because they define the shape. Brand colors: primary #27AAE1, secondary #58595B.

func SignalApprovalPending added in v1.20.0

func SignalApprovalPending(err error, fields localsignal.Fields)

func SignalFields added in v1.20.0

func SignalFields(err error) localsignal.Fields

func SignalPaused added in v1.20.0

func SignalPaused(err error)

SignalPaused applies to any operation, using only the structured pause code.

func SignalRefusal added in v1.20.0

func SignalRefusal(err error)

SignalRefusal is called only by command execution and file transfer paths. Error sinks own pause signals so one pause never increments the folded count twice.

func SignalResponse added in v1.20.0

func SignalResponse(status int, body []byte, sources ...SignalOriginSource)

SignalResponse handles a pause on raw responses without classifying raw API calls as commands.

func SplitAndTrim added in v1.4.4

func SplitAndTrim(s, sep string) []string

SplitAndTrim splits s by sep, trims whitespace from each element, and drops empty entries. Returns nil when the input is empty or yields no non-empty elements.

func SplitPath

func SplitPath(path string) (string, string, error)

SplitPath splits a "server:/path" target into its server name and remote path. It returns an error when path carries no ':' separator or no server name. An empty remote path is accepted; callers decide whether it is meaningful.

func SpoolToTempFile added in v1.5.0

func SpoolToTempFile(pattern string, fn func(io.Writer) error) (*os.File, int64, error)

SpoolToTempFile creates a temp file, invokes fn to write into it, closes it to surface flush errors, then reopens it for reading with its size. On any error the temp file is closed and removed. The caller owns cleanup on success.

func StderrForChild added in v1.18.0

func StderrForChild() *os.File

StderrForChild returns os.Stderr itself, so the child still sees a terminal, and treats the line as left open, since the CLI cannot see what the child writes.

func StripANSIEscapes added in v1.9.0

func StripANSIEscapes(s string) string

func StripControlChars added in v1.9.0

func StripControlChars(s string) string

func StripFormatAndANSI added in v1.11.0

func StripFormatAndANSI(s string) string

StripFormatAndANSI removes format characters before escape sequences. Reversed, one buried in a sequence would break the match and leave its tail on screen.

func StripFormatChars added in v1.9.2

func StripFormatChars(s string) string

StripFormatChars removes the Unicode format (Cf) characters. No Cf rune is a control byte, so IsControlRune misses them all, while the bidi controls among them reorder what a terminal renders: "denied" can display as "approved".

func StructuredErrorCode added in v1.15.0

func StructuredErrorCode(err error) string

StructuredErrorCode returns the code a typed error in err's chain carries, or "" if none does. Unlike ParseErrorResponse it never reads a code out of message text, so a code that only appears inside a message, such as an agent's transfer report, does not count.

func ThrottleCeiling added in v1.12.0

func ThrottleCeiling(timeout, tick time.Duration) time.Duration

ThrottleCeiling is the longest a throttled wait may run: its own timeout, one timeout of extensions, and the overshoot of the grant that crosses the budget, which Extend takes whole. Exported for the wait loops' own tests the way PollMaxBackoffTick is—a wait that refills its budget has no ceiling at all.

func TimeFormat

func TimeFormat(value int) *string

func TimeUtils

func TimeUtils(t time.Time) string

func TrackedStderr added in v1.18.0

func TrackedStderr() io.Writer

TrackedStderr is os.Stderr as the process has it now, recording whether the last byte left the cursor mid-line, so the error envelope can start on its own line.

func TruncateString

func TruncateString(str string, num int) string

func Unzip

func Unzip(src string, dest string) error

func WaitForTokenRefreshes added in v1.20.0

func WaitForTokenRefreshes()

WaitForTokenRefreshes covers a 10s config lock wait, an 8s grant and 1s for saving.

func WarnTerminalTextAltered added in v1.11.2

func WarnTerminalTextAltered(w io.Writer, indent string)

WarnTerminalTextAltered takes a writer and an indent because its callers print outside the Cli* helpers and line the warning up with the value it is about.

func WebsocketDialError added in v1.18.0

func WebsocketDialError(prefix string, err error, resp *http.Response) error

WebsocketDialError reports a failed WebSocket dial whose URL path carries a channel token, keeping only its host and adding the handshake status a bad handshake alone never names.

func WithExitError added in v1.20.0

func WithExitError(run func(*cobra.Command, []string) error) func(*cobra.Command, []string) error

WithExitError wraps a RunE that returns ExitError. Cobra prints nothing for an ExitError, which cmd.Execute prints, but keeps its error line and usage for a flag or pre-run error.

func WithHTTPStatus added in v1.18.0

func WithHTTPStatus(err error, statusCode int) error

WithHTTPStatus tags err with statusCode for HTTPStatusCode.

func WithRedirectStatus added in v1.18.0

func WithRedirectStatus(err error, resp *http.Response) error

WithRedirectStatus keeps the 3xx a refused redirect leaves: Do returns it beside the error.

func WithSignalFields added in v1.20.0

func WithSignalFields(err error, fields localsignal.Fields, sources ...SignalOriginSource) error

func WorkSessionExitError added in v1.20.0

func WorkSessionExitError(err error, operation, target, authMethod, activeWS string) error

WorkSessionExitError returns the exit-3 gate diagnostic, or nil when err is not a WorkSession gate refusal. target is what the operation names: a cluster for OperationKube, a server otherwise.

func WriteToPager added in v1.0.0

func WriteToPager() (io.Writer, func())

WriteToPager returns a writer that buffers output and pipes it through a pager only when the output exceeds the terminal height. The caller must call the returned cleanup function when done writing.

Behavior:

  • If stdout is not a terminal (e.g. piped), prints directly to stdout.
  • If the output fits within the terminal height, prints directly to stdout.
  • Otherwise, pipes through the PAGER environment variable or "less -RSX".
  • Falls back to direct stdout if the pager command is not available.

func Yellow

func Yellow(value string) string

Yellow returns a bold yellow string for terminal output.

func ZipToWriter added in v1.5.0

func ZipToWriter(folderPath string, w io.Writer) error

Types

type AnnotatedText added in v1.20.0

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

AnnotatedText is a list cell whose table text adds a note to the value JSON carries, so a table can say what the value leaves out without changing what a script reads.

func Annotate added in v1.20.0

func Annotate(value, tableText string) AnnotatedText

func (AnnotatedText) MarshalJSON added in v1.20.0

func (t AnnotatedText) MarshalJSON() ([]byte, error)

func (AnnotatedText) String added in v1.20.0

func (t AnnotatedText) String() string

type BatchError added in v1.18.0

type BatchError struct {
	Header   string
	Failures []error
}

BatchError joins the failures of independent items, such as the files of a bulk upload. Its message is Header followed by one line per failure. It unwraps to every failure, so each refusal's hint still prints, but no single item's code speaks for the batch: ParseErrorResponse and StructuredErrorCode do not look inside it, so a batch is never classified as one item's refusal (a work-session gate, an MFA step-up) and its per-item results stay in view.

func (*BatchError) Error added in v1.18.0

func (e *BatchError) Error() string

func (*BatchError) Unwrap added in v1.18.0

func (e *BatchError) Unwrap() []error

type ErrorHandlerCallbacks added in v1.0.0

type ErrorHandlerCallbacks struct {
	OnMFARequired func(serverName string) error

	OnUsernameRequired func() error

	// RetryOperation re-runs the failed operation. After an MFA prompt it runs until it stops
	// failing with auth_mfa_required, so its refusal is what tells the wait MFA is not done yet.
	RetryOperation func() error
}

ErrorHandlerCallbacks defines callback functions for handling different error types.

type ErrorResponse added in v0.4.0

type ErrorResponse struct {
	Code   string `json:"code"`
	Source string `json:"source"`
}

type ExitError added in v1.20.0

type ExitError struct {
	Code int
	// contains filtered or unexported fields
}

ExitError is a failure a RunE command returns: cmd.Execute prints it with PrintExitError and exits with Code. Build it with a constructor; NewSilentExitError is the one that prints nothing.

func (*ExitError) Error added in v1.20.0

func (e *ExitError) Error() string

func (*ExitError) Unwrap added in v1.20.0

func (e *ExitError) Unwrap() []error

Unwrap returns the errors among the message's arguments, so a caller can still inspect the cause.

type Failure added in v1.18.0

type Failure struct {
	ExitCode       int
	ErrorCode      string
	Err            error
	Message        string
	Operation      string
	RemoteExitCode *int
	Partial        *PartialInfo
	NextActions    []NextAction
	HTTPStatus     int
	RetryAfter     time.Duration
	Server         map[string]any
}

Failure describes a non-zero exit whose table-mode output the caller keeps; only the --output json envelope is built here. An empty ErrorCode is classified from Err.

type HeldRequest added in v1.20.0

type HeldRequest struct {
	ApprovalRequest string     `json:"approval_request"`
	ExpiresAt       *time.Time `json:"expires_at"` // Nil when the server knows no deadline.
	StatusPath      string     `json:"status_path"`
}

HeldRequest is the command detail's open sudo approval. Null or an absent key on an older server decodes to nil.

func (*HeldRequest) Expired added in v1.20.0

func (h *HeldRequest) Expired() bool

Expired reports whether the deadline has passed, not when approval occurred.

type IOStreams added in v1.20.0

type IOStreams struct {
	Out    io.Writer
	ErrOut io.Writer

	// ColorEnabled gates ANSI codes; it follows ErrOut, where colored messages go, so a pipe
	// or a redirected log carries none, and NO_COLOR turns it off.
	ColorEnabled bool
	// contains filtered or unexported fields
}

IOStreams is where a command writes: data to Out, messages to ErrOut, in the --output format it holds. Commands take one through their constructor so a test can hand in buffers.

func SystemIOStreams added in v1.20.0

func SystemIOStreams() *IOStreams

SystemIOStreams writes to whatever os.Stdout and os.Stderr are at the time of each write, under the format the --output flag set.

func TestIOStreams added in v1.20.0

func TestIOStreams() (ios *IOStreams, out, errOut *bytes.Buffer)

TestIOStreams returns streams writing to the two buffers, in table format with no color.

func (*IOStreams) Blue added in v1.20.0

func (s *IOStreams) Blue(value string) string

Blue returns a bold blue string when s has color.

func (*IOStreams) Bold added in v1.20.0

func (s *IOStreams) Bold(value string) string

Bold returns a bold string when s has color.

func (*IOStreams) FprintExitError added in v1.20.0

func (s *IOStreams) FprintExitError(w io.Writer, e *ExitError)

FprintExitError writes e to w in s's format.

func (*IOStreams) Green added in v1.20.0

func (s *IOStreams) Green(value string) string

Green returns a bold green string when s has color.

func (*IOStreams) Info added in v1.20.0

func (s *IOStreams) Info(msg string, args ...any)

Info writes an informational message to s.ErrOut.

func (*IOStreams) IsJSON added in v1.20.0

func (s *IOStreams) IsJSON() bool

IsJSON reports whether these streams print --output json.

func (*IOStreams) NewParseExitError added in v1.20.0

func (s *IOStreams) NewParseExitError(cmd *cobra.Command, format, msg string) error

NewParseExitError is the package-level NewParseExitError, applying format to s.

func (*IOStreams) OutputFormat added in v1.20.0

func (s *IOStreams) OutputFormat() string

OutputFormat is the --output value these streams print in.

func (*IOStreams) Pager added in v1.20.0

func (s *IOStreams) Pager() (io.Writer, func())

Pager returns where a table goes: through the process pager when Out is the process's stdout writer, and straight to Out for any other writer.

func (*IOStreams) PartialTableExitError added in v1.20.0

func (s *IOStreams) PartialTableExitError(rows any, msg string, args ...any) error

PartialTableExitError is the package-level PartialTableExitError on s.

func (*IOStreams) PrintExitError added in v1.20.0

func (s *IOStreams) PrintExitError(e *ExitError)

PrintExitError writes e to s.ErrOut in s's format, as cmd.Execute prints a failure.

func (*IOStreams) PrintHeader added in v1.20.0

func (s *IOStreams) PrintHeader(header string)

PrintHeader writes header to s.ErrOut, above the data s.Out carries.

func (*IOStreams) PrintJson added in v1.20.0

func (s *IOStreams) PrintJson(body []byte) error

PrintJson prints body to s.Out as indented JSON, or returns the exit-1 failure when body is not JSON.

func (*IOStreams) PrintPendingApproval added in v1.20.0

func (s *IOStreams) PrintPendingApproval(message, requestID string, retry NextAction, extra ...NextAction)

PrintPendingApproval is the package-level PrintPendingApproval on s.

func (*IOStreams) PrintPurposeAccepted added in v1.20.0

func (s *IOStreams) PrintPurposeAccepted(commandID string)

PrintPurposeAccepted is the package-level PrintPurposeAccepted on s.

func (*IOStreams) PrintPurposeDemand added in v1.20.0

func (s *IOStreams) PrintPurposeDemand(message, commandID string, expiresAt *time.Time)

PrintPurposeDemand is the package-level PrintPurposeDemand on s.

func (*IOStreams) PrintPurposeRefused added in v1.20.0

func (s *IOStreams) PrintPurposeRefused(commandID string, cause error)

PrintPurposeRefused is the package-level PrintPurposeRefused on s.

func (*IOStreams) PrintRefusalHints added in v1.20.0

func (s *IOStreams) PrintRefusalHints(w io.Writer, err error)

PrintRefusalHints is the package-level PrintRefusalHints in s's color.

func (*IOStreams) PrintTable added in v1.20.0

func (s *IOStreams) PrintTable(slice any) error

PrintTable prints a slice of row structs to s.Out as a table, or as JSON under --output json. It returns the exit-1 failure when slice is not a slice or does not marshal.

func (*IOStreams) RawTerminalHintLines added in v1.20.0

func (s *IOStreams) RawTerminalHintLines(err error) string

RawTerminalHintLines is the package-level RawTerminalHintLines in s's color.

func (*IOStreams) Red added in v1.20.0

func (s *IOStreams) Red(value string) string

Red returns a bold red string when s has color.

func (*IOStreams) ReportNoChanges added in v1.20.0

func (s *IOStreams) ReportNoChanges(err error) bool

ReportNoChanges is the package-level ReportNoChanges on s.

func (*IOStreams) SetOutputFormat added in v1.20.0

func (s *IOStreams) SetOutputFormat(value string) error

SetOutputFormat applies an --output value, refusing anything but table or json as a usage error.

func (*IOStreams) Success added in v1.20.0

func (s *IOStreams) Success(msg string, args ...any)

Success writes a success message to s.ErrOut.

func (*IOStreams) WarnTerminalTextAltered added in v1.20.0

func (s *IOStreams) WarnTerminalTextAltered(w io.Writer, indent string)

WarnTerminalTextAltered is the package-level WarnTerminalTextAltered in s's color.

func (*IOStreams) Warning added in v1.20.0

func (s *IOStreams) Warning(msg string, args ...any)

Warning writes a warning to s.ErrOut, with the server's hint for a refusal among args.

func (*IOStreams) Yellow added in v1.20.0

func (s *IOStreams) Yellow(value string) string

Yellow returns a bold yellow string when s has color.

type JSONErrorEnvelope added in v1.6.0

type JSONErrorEnvelope[T any] struct {
	OK             bool           `json:"ok"`
	ExitCode       int            `json:"exit_code"`
	ErrorCode      string         `json:"error_code"`
	Message        string         `json:"message"`
	Command        string         `json:"command,omitempty"`
	Reason         string         `json:"reason,omitempty"`
	Context        T              `json:"context"`
	HTTPStatus     int            `json:"http_status,omitempty"`
	RetryAfter     int            `json:"retry_after,omitempty"`
	Server         map[string]any `json:"server,omitempty"`
	RemoteExitCode *int           `json:"remote_exit_code,omitempty"`
	Partial        *PartialInfo   `json:"partial,omitempty"`
	NextActions    []NextAction   `json:"next_actions,omitempty"`
}

JSONErrorEnvelope is the --output json failure line. Fields are additive only; exit_code and error_code are always present.

type NextAction added in v1.9.0

type NextAction struct {
	Command     string `json:"command,omitempty"`
	Description string `json:"description,omitempty"`
}

NextAction is one actionable follow-up: Command is a runnable command with no inline comment, for machine consumers, and Description the human hint. Either may be empty, as a guidance-only pointer carries no command.

func RefusalNextActions added in v1.18.0

func RefusalNextActions(err error) []NextAction

RefusalNextActions returns server hints, status paths, retry delays and held approvals. A refusal's "next" is text only under an API token because that path may reject it.

func (NextAction) PlainText added in v1.9.0

func (a NextAction) PlainText() string

PlainText renders the action as a human-facing line: "command # description", or just the command or description when the other is empty. Sanitized here because its callers write to the terminal outside the Cli* helpers and call sites interpolate server-returned ids into Command; the JSON envelope marshals the fields themselves and escapes via escapeJSONControls instead.

type PartialInfo added in v1.18.0

type PartialInfo struct {
	Count int `json:"count"`
}

type SSHTarget added in v0.4.0

type SSHTarget struct {
	User string // Username (empty if not specified)
	Host string
	Path string // Path (empty if not specified)
}

SSHTarget represents a parsed SSH-like target with user, host, and path components.

func ParseSSHTarget added in v0.4.0

func ParseSSHTarget(target string) SSHTarget

ParseSSHTarget parses SSH-like target strings and returns the components Supports formats: - host - user@host - host:path - user@host:path An '@' is only treated as the user separator when it precedes the first ':', so a remote path may itself contain '@' (e.g. host:/tmp/alice@example.com).

type SignalOriginSource added in v1.20.0

type SignalOriginSource interface {
	LocalSignalOrigin() localsignal.ConsoleOrigin
}

type Spinner added in v1.0.0

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

Spinner displays an animated spinner with a message. When stderr is not a terminal (e.g., piped or redirected), the spinner animation is replaced with a single static progress line so logs stay clean without ANSI artifacts.

func NewSpinner added in v1.0.0

func NewSpinner(message string) *Spinner

NewSpinner creates a new spinner with the given message If the message ends with "...", the dots will animate (. -> .. -> ...)

func (*Spinner) Start added in v1.0.0

func (s *Spinner) Start()

Start begins the spinner animation.

func (*Spinner) Stop added in v1.0.0

func (s *Spinner) Stop()

Stop stops the spinner animation.

func (*Spinner) StopWriter added in v1.11.1

func (s *Spinner) StopWriter(w io.Writer) io.Writer

StopWriter wraps w so the spinner stops before the first byte written to it reaches the terminal; otherwise output streamed under a running spinner is drawn over, then erased by Stop. Callers waiting on something that may start producing output hand their writer through here. An empty write leaves the spinner alone.

type ThrottleBudget added in v1.12.0

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

ThrottleBudget is the allowance a poll spends to survive being rate limited. A 429 says the server is alive and pushing back, not that the work is lost, so the deadline moves rather than starving—but only this far.

func NewThrottleBudget added in v1.12.0

func NewThrottleBudget(timeout time.Duration) *ThrottleBudget

NewThrottleBudget returns a new budget that treats timeout as its cumulative extension limit.

func (*ThrottleBudget) Extend added in v1.12.0

func (b *ThrottleBudget) Extend(deadline time.Time, delay time.Duration) (time.Time, bool)

Extend grows deadline by delay when the budget allows it, and reports whether it did. An extension is granted while the time spent so far is still under limit and the count is still under PollMaxThrottleExtensions.

The grant that carries the total past limit is taken whole rather than trimmed, since a clipped grant would leave the poll no time to serve the wait the throttled server itself just asked for. That overshoot is one delay wide, which the caller caps at PollMaxBackoffTick times its base tick, and no further extension follows it.

func (*ThrottleBudget) Reset added in v1.12.0

func (b *ThrottleBudget) Reset()

Reset clears the spent budget, extension count, and warning flag—called when the poll sees progress, so a throttle late in a long wait is not charged against an earlier, unrelated one.

func (*ThrottleBudget) ShouldWarn added in v1.12.0

func (b *ThrottleBudget) ShouldWarn() bool

ShouldWarn reports true once, the first time it is called since construction or the last Reset—so a wait that stays throttled for a long time still warns only once.

func (*ThrottleBudget) WarnThrottled added in v1.12.0

func (b *ThrottleBudget) WarnThrottled(delay time.Duration)

WarnThrottled prints the rate-limit notice once per throttled stretch, so every wait loop shows the same line. CliWarning steps off a running spinner's line itself, so the caller need not stop one first.

type Timestamp added in v1.20.0

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

Timestamp is a list cell: its table text in a table, RFC 3339 UTC or null in JSON, or the server's string as sent when it could not be parsed.

func NewTimestamp added in v1.20.0

func NewTimestamp(t time.Time, tableText string) Timestamp

func OptionalTimestamp added in v1.20.0

func OptionalTimestamp(t *time.Time) Timestamp

OptionalTimestamp is an absolute time with no table text, null in JSON when t is nil.

func ParseLocalTimestamp added in v1.20.0

func ParseLocalTimestamp(value string) Timestamp

ParseLocalTimestamp is ParseTimestamp with the table text in the local zone (FormatTimestamp).

func ParseTimestamp added in v1.20.0

func ParseTimestamp(value string) Timestamp

ParseTimestamp shows a server's time string as sent in a table. JSON gets it in UTC, null when empty, or as sent when it is not RFC 3339.

func RelativeTime added in v1.20.0

func RelativeTime(t time.Time) Timestamp

func (Timestamp) MarshalJSON added in v1.20.0

func (t Timestamp) MarshalJSON() ([]byte, error)

func (Timestamp) String added in v1.20.0

func (t Timestamp) String() string

type TruncatedText added in v1.20.0

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

TruncatedText is a list cell cut to width in a table and whole in JSON.

func Truncate added in v1.20.0

func Truncate(s string, width int) TruncatedText

func (TruncatedText) MarshalJSON added in v1.20.0

func (t TruncatedText) MarshalJSON() ([]byte, error)

func (TruncatedText) String added in v1.20.0

func (t TruncatedText) String() string

Jump to

Keyboard shortcuts

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