utils

package
v1.16.1 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 33 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"

	// WorkSessionSudoBypassConsoleOnly rides a 403: a work session can receive an
	// MFA-bypass sudo policy without a person's approval from the web console only.
	WorkSessionSudoBypassConsoleOnly = "work_session_sudo_bypass_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 an MFA-bypass 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"

	// 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: disruptive action refused; --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: the server refused a command because its command
	// line carries a credential (e.g. a -p/--password flag, a KEY=VALUE secret such
	// as PGPASSWORD=..., or a user:pass@host connection string), which the server
	// would otherwise persist in the stored command line. Move the secret to
	// --env instead.
	// The rejected-forms list above is repeated in the exec and websh help text
	// and the README's "When a command is denied" section—when the server-side
	// gate changes, update all of them together.
	//
	// The server also accepts a per-command credential_exposure_acknowledged
	// override, which the CLI deliberately does not expose: it records the
	// exposure rather than preventing it (hygiene, not authorization—it carries
	// no role gate), so exposing it would offer a one-flag way past the gate
	// where rewriting with --env costs the same. --env stays the only path.
	CommandInlineCredential = "command_inline_credential"

	// APITokenACLNotAllowed: the server refused the request because the token's
	// access control rules do not cover it—the command, the server, or the file path
	// falls outside the envelope an admin granted this token. The refusal is
	// permanent for the same request: a retry submits the same thing. Widen the
	// rules with 'alpacon token acl' instead. The server sends this on a 403 with no
	// human detail, so authStatusCodeMessage in client/client.go renders the message.
	APITokenACLNotAllowed = "api_token_acl_not_allowed"

	// 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: 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: 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"

	// Refusals of a kube session the server names itself. An AI agent's
	// WorkSession cannot open one yet; the cluster's agent is not connected;
	// the agent did not accept the session, which the server then closed; and
	// the caller has no user name the session could act as.
	KubeSessionAgentModeNotSupported = "kube_session_agent_mode_not_supported"
	ClusterNotConnected              = "cluster_not_connected"
	KubeSessionChannelOpenFailed     = "kube_session_channel_open_failed"
	KubeSessionPrincipalNotSupported = "kube_session_principal_not_supported"

	// WorkSession extension approval. Every 'work-session extend' request
	// requires a reason and follows the workspace's approval policy, the same
	// rule 'work-session create' uses; a session may hold only one pending
	// extension request at a time. See cmd/worksession's extend command.
	WorkSessionExtensionReasonRequired = "work_session_extension_reason_required"
	WorkSessionExtensionAlreadyPending = "work_session_extension_already_pending"
	// WorkSessionAdmissionDenied: 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—what
	// CliErrorWithExit already exits with. Name it when calling CliErrorWithExitCode
	// 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 its own validation. It is distinct from ExitCodeGeneralError (1):
	// 1 means the request failed (network, server), 2 means the invocation itself
	// was wrong. Scripts and AI agents branch on it to fix the command line rather
	// than retry 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 HITL denial that created an approval
	// request, a work session created in the pending state, or a wait that ended
	// (timed out or was interrupted) with the outcome undecided.
	// It is distinct from ExitCodeWorkSessionDenied (3): the action was not
	// refused, it is awaiting an out-of-band approve/reject in the Alpacon console
	// (web/Slack). Scripts and AI agents branch on it to "wait or check later"
	// rather than treat it as a hard failure.
	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).
	// It is a transient, retryable "busy now → retry later" condition, distinct from
	// a hard failure (1): scripts and AI agents branch on it to retry when idle
	// (or re-run with --force) rather than give up.
	ExitCodeServerBusy = 5

	// ExitCodeNotApproved is the process exit code for an awaited approval that
	// ended without being granted—rejected, expired, revoked, cancelled, or
	// completed. It is the counterpart of ExitCodePendingApproval (4): 4 means the
	// outcome is still open, 6 means it settled without the grant. Scripts and AI
	// agents branch on it to stop retrying rather than keep re-requesting approval.
	ExitCodeNotApproved = 6

	// ExitCodePurposeRequired is the process exit code for a command the
	// verification gate parked while it asks what the command is for.
	// It is deliberately not ExitCodePendingApproval (4): nothing is pending on a
	// human, no approval request exists, and the next move belongs to the caller
	// that submitted the command. Scripts and AI agents branch on it to answer
	// with 'alpacon exec purpose' rather than to wait or to give up—and the
	// window is about a minute, so waiting loses it.
	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. It is distinct from ExitCodeGeneralError (1): 1 means
	// the check itself failed, 8 means the check succeeded and a newer version
	// exists. Scripts and CI branch on it to schedule an update.
	ExitCodeUpdateAvailable = 8
)
View Source
const (
	OutputFormatTable = "table"
	OutputFormatJSON  = "json"
)

Valid values for the --output persistent flag.

View Source
const (

	// PollMaxBackoffTick is exported so a poll loop's own test (api/event,
	// cmd/exec, cmd/worksession) 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"
	// OperationKube names no scope: any active WorkSession of the caller qualifies.
	OperationKube = "kube"
)

Operations HandleWorkSessionError reports; each but OperationKube is also the WorkSession scope it 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; not a ceiling (--wait-approval exceeds it), preserving the old 30 × 10s window.
	DefaultApprovalWaitTimeout = 5 * time.Minute
)
View Source
const DevVersion = "dev" // What Version carries when no -ldflags set 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. " +
	"Stay silent and the command is not blocked—it takes the ordinary path when the demand expires."

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.

View Source
const UsageErrorCode = "usage_error"

UsageErrorCode is the synthetic error_code for local validation failures that never reached the server.

Variables

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 OutputFormat string

OutputFormat holds the value of the --output persistent flag. Bound by cmd/root.go; read by PrintTable and PrintJson.

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 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

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 branch that is expected to be rare and that produces no visible symptom when it runs: a degrade that always succeeds looks exactly like the path it replaced, so without a line here there is nothing to tell the two apart after the fact.

The refresh-token degrade logs from inside the "Refreshing access token..." spinner (auth0.refreshWithDeviceScopeFallback, reached from client.NewAlpaconAPIClient), so this line needs the same break off an animated line a warning does.

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; json mode carries err's code. An ErrInvalidID refusal exits 2 through CliUsageErrorEnvelopeWithExit.

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.

func CliErrorWithExitCode added in v1.9.2

func CliErrorWithExitCode(code int, msg string, args ...any)

CliErrorWithExitCode prints an error message to stderr and exits with the given code. Unlike CliErrorWithExit it omits the "report an issue" footer—use it for expected, machine-distinguishable refusals (e.g. a busy server) that scripts branch on by exit code.

func CliInfo

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

CliInfo handles all informational messages in the CLI.

func CliInfoWithExit

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

CliInfoWithExit prints an informational message to stderr and exits the program with a status code of 0

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); error_code is fixed to UsageErrorCode.

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 ConfirmAction added in v1.2.0

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

ConfirmAction prompts the user for confirmation before a destructive action. In non-interactive mode (piped stdin, CI, etc.), it exits and asks for --yes flag. Returns on confirm; exits the program on decline.

func CreateAndEditTempFile

func CreateAndEditTempFile(data []byte) (string, error)

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 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 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 HTTPStatusCode added in v1.8.1

func HTTPStatusCode(err error) int

HTTPStatusCode returns the HTTP status carried by err, or 0 if none—lets callers tell 404 from 401.

func HandleCommonErrors added in v1.0.0

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

HandleCommonErrors handles common errors (MFA, UsernameRequired) with retry logic Returns nil if error was handled successfully, otherwise returns the original or new error

Only the tagged error of the operation's side-effecting request (MarkSubmission) is handled; any other error is returned as is, because it came after the operation took effect on the server and nothing here may run it again. The error it returns carries no tag.

func HandleWorkSessionError added in v1.4.8

func HandleWorkSessionError(err error, operation, serverName, authMethod, activeWS string)

HandleWorkSessionError prints a WorkSession gate diagnostic and exits(3); no-op for other errors.

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 ACL refusal.

func IsAgentForbiddenScope added in v1.16.0

func IsAgentForbiddenScope(scope string) bool

IsAgentForbiddenScope reports whether an agent session cannot hold scope.

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 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 IsRemoteTarget added in v0.4.0

func IsRemoteTarget(target string) bool

IsRemoteTarget checks if a target string represents a remote location A target is considered remote if it contains a colon (:)

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 connection never opened, or the server answered 429 or 503. Unlike IsTransientRequestError it leaves out a lost response, a 502 and a 504, which can follow a request that already ran, so a request that is not idempotent may be sent again on it. Only the tagged error of the side-effecting request itself (MarkSubmission) can be unprocessed: any other error came from a later request of an operation the server already acted on, whatever status it carries.

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 itself (the command submission, an upload or download create, a session create, a one-request change), including whatever lookup precedes that request. Only such an error says the server did or did not act, so only it can be retried after MFA or ridden through when it is unprocessed.

The tag is read off the error exactly as returned, never through wrapping: an operation that makes further requests after the one it tagged returns their errors untagged, and a caller that wraps a tagged error hides the tag. An untagged error is therefore the safe default, "the operation already took effect": HandleCommonErrors passes it through and the wait ends on it. The status and dial error underneath stay readable through the tag.

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 attempts to open the given URL in the user's default browser. It silently falls back to doing nothing if the browser cannot be opened (e.g., headless server, SSH session, container) or if another process recently opened a browser (debounce).

Set ALPACON_NO_BROWSER=1 to disable browser auto-open globally.

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 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 PartialTableWithExit added in v1.15.0

func PartialTableWithExit(rows any, msg string, args ...any)

PartialTableWithExit prints rows to stdout, the reason to stderr, and exits with ExitCodeGeneralError. It is not for a walk that collected nothing: that is an ordinary failure for CliErrorWithExit.

func PrettyJSON

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

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)

func PrintListOrExit added in v1.15.0

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

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

func PrintPendingApproval added in v1.7.2

func PrintPendingApproval(message, requestID string, retry NextAction)

PrintPendingApproval emits the structured "pending approval" feedback for an action that requires out-of-band human approval and was not waited on. Under --output json it writes a {"status":"pending_approval", ...} envelope to stdout; otherwise it writes an actionable message to stderr. requestID may be empty when the surface cannot supply one. retry is a surface-specific retry action (e.g. the exact command to re-run); its Command stays a pure, executable string so a machine consumer can run it directly, with any hint in Description. It never exits — the caller owns process exit so the exit-code contract stays in one place.

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 emits the structured "state the purpose" feedback for a command the gate parked. Under --output json it writes a {"status":"purpose_required", ...} envelope to stdout; otherwise it writes an actionable message to stderr. expiresAt may be nil, in which case no deadline is reported rather than one being invented. It never exits—the caller owns process exit so the exit-code contract stays in one place.

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 PrintTable

func PrintTable(slice any)

func ProcessEditedData

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

ProcessEditedData facilitates user modifications to original data, formats it, supports editing via a temp file, compares the edited data against the original, and parses it into JSON. If no changes are made, the update is aborted and an error is returned.

func PromptForBool

func PromptForBool(prompt string) bool

func PromptForInput

func PromptForInput(promptText string) string

func PromptForInputWithDefault added in v1.3.4

func PromptForInputWithDefault(promptText, defaultValue string) string

PromptForInputWithDefault prompts for input and returns the default if empty.

func PromptForIntInput

func PromptForIntInput(promptText string, defaultValue int) int

func PromptForListInput

func PromptForListInput(promptText string) []string

func PromptForPassword

func PromptForPassword(promptText string) string

func PromptForRequiredInput

func PromptForRequiredInput(promptText string) string

func PromptForRequiredIntInput

func PromptForRequiredIntInput(promptText string) int

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 RemoteFileName added in v1.6.0

func RemoteFileName(remotePath string) (string, error)

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

func RemovePrefixBeforeAPI

func RemovePrefixBeforeAPI(url string) string

func RequirePositiveInt added in v1.9.2

func RequirePositiveInt(flagName string, value int)

RequirePositiveInt exits with a usage error when an integer flag is not positive.

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 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 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 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 ShowLogo(rightLines []string)

ShowLogo renders the Pacabot mascot with up to 3 lines of text. When the terminal is wide enough the text sits to the right of the art (lines 1-3 align with art rows 1-3); otherwise it falls back to rendering text below the art so wrapped lines don't break the half-block pixel art rendering.

Pixel art ported from strategy/brand-assets/pacabot/pacabot.sh. In color mode, body cells render as spaces with BG=cyan so the cell background fills any inter-line gap. In plain mode (no TTY / NO_COLOR), body cells substitute █ glyphs so the silhouette stays visible without ANSI codes. Edge half-blocks (▄ ▀) are kept in both modes — they define the shape: ▄ corners and ! bar bottom (FG cyan, glyph extends below the em-box in most fonts), and ▀ for the eye (grey on cyan) and the mouth (grey FG). Brand colors: primary #27AAE1, secondary #58595B.

func SplitAndParseInt

func SplitAndParseInt(input string) []int

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 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 TruncateString

func TruncateString(str string, num int) string

func Unzip

func Unzip(src string, dest string) error

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 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 ErrorHandlerCallbacks added in v1.0.0

type ErrorHandlerCallbacks struct {
	// OnMFARequired is called when MFA authentication is required
	// serverName: the name of the server requiring MFA
	OnMFARequired func(serverName string) error

	// OnUsernameRequired is called when username is required
	OnUsernameRequired func() error

	// RetryOperation re-runs the operation that failed. After an MFA prompt it is
	// called repeatedly until it stops failing with auth_mfa_required, so the
	// server's refusal is what tells the wait that MFA has not completed yet.
	// Should return nil on success, error on failure.
	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 JSONErrorEnvelope added in v1.6.0

type JSONErrorEnvelope[T any] struct {
	OK          bool         `json:"ok"`
	ExitCode    int          `json:"exit_code,omitempty"`
	ErrorCode   string       `json:"error_code,omitempty"`
	Message     string       `json:"message"`
	Reason      string       `json:"reason,omitempty"`
	Context     T            `json:"context"`
	NextActions []NextAction `json:"next_actions,omitempty"`
}

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 pure, runnable command (no inline comments) for machine consumers; Description carries the human hint. Either may be empty—a pure command needs no hint, and a guidance-only pointer (e.g. "approve it in the console") carries no runnable command—so both fields are omitempty.

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 SSHTarget added in v0.4.0

type SSHTarget struct {
	User string // Username (empty if not specified)
	Host string // Hostname/server name
	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 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. A spinner animates the line a caller is about to write to and Stop erases that line, so output streamed while one is running gets drawn over and then wiped. Callers that wait on something which may start producing output—an approved command resuming, an operation retried after MFA—hand their writer through here instead of having to know when the first byte arrives. An empty write is not output, so it 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 the first time a throttled stretch calls it, and stays quiet for the rest of that stretch. Every wait loop that spends a budget shows the same line, so the wording lives here rather than at each call site. CliWarning steps off a running spinner's line itself, so a caller animating one need not stop it first.

Jump to

Keyboard shortcuts

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