Documentation
¶
Index ¶
- Constants
- Variables
- func AgentSessionScope(operation string) string
- func Blue(value string) string
- func Bold(value string) string
- func BoolPointerToString(value *bool) string
- func BuildURL(basePath, relativePath string, params map[string]string) string
- func CleanupTempFile(f *os.File)
- func CliDebug(msg string, args ...any)
- func CliError(msg string, args ...any)
- func CliErrorEnvelopeWithExit(operation string, err error, format string, args ...any)
- func CliErrorEnvelopeWithExitCode(code int, operation string, err error, format string, args ...any)
- func CliErrorWithExit(msg string, args ...any)
- func CliErrorWithExitCode(code int, msg string, args ...any)
- func CliInfo(msg string, args ...any)
- func CliInfoWithExit(msg string, args ...any)
- func CliSuccess(msg string, args ...any)
- func CliUsageErrorEnvelopeWithExit(operation string, format string, args ...any)
- func CliWarning(msg string, args ...any)
- func CompactStrings(ss []string) []string
- func ConfirmAction(msg string, args ...any)
- func CreateAndEditTempFile(data []byte) (string, error)
- func DebugEnabled() bool
- func DecodeJWTPayload(token string) (map[string]any, error)
- func DeleteFile(path string) error
- func ExtractBaseDomain(workspaceURL string) string
- func ExtractWorkspaceName(workspaceURL string) string
- func FormatJSON(value any) (string, error)
- func FormatTimestamp(ts string) string
- func GetCLIVersion() string
- func GetUserAgent() string
- func Green(value string) string
- func HTTPStatusCode(err error) int
- func HandleCommonErrors(err error, serverName string, callbacks ErrorHandlerCallbacks) error
- func HandleWorkSessionError(err error, operation, serverName, authMethod, activeWS string)
- func InteractiveOnly(err error, action string) error
- func IsAgentForbiddenScope(scope string) bool
- func IsC1OrDEL(r rune) bool
- func IsControlRune(r rune) bool
- func IsFatalClientError(status int) bool
- func IsInteractiveShell() bool
- func IsLocalTarget(target string) bool
- func IsRemoteTarget(target string) bool
- func IsReplacementTempName(name string) bool
- func IsRetryLaterStatus(status int) bool
- func IsSubmissionError(err error) bool
- func IsTransientRequestError(err error) bool
- func IsUUID(str string) bool
- func IsUnprocessedRequestError(err error) bool
- func MarkSubmission(err error) error
- func NextPollBackoff(tick time.Duration, attempt int, retryAfter time.Duration) time.Duration
- func NextPollTick(tick, elapsed time.Duration) time.Duration
- func OpenBrowser(url string)
- func ParseErrorGateAndMissing(err error) (string, []string)
- func ParseErrorResponse(err error) (string, string)
- func ParsePositiveDuration(flagName, raw string) (time.Duration, error)
- func PartialTableWithExit(rows any, msg string, args ...any)
- func PrettyJSON(data []byte) (*bytes.Buffer, error)
- func PrintHeader(header string)
- func PrintJSONError[T any](w io.Writer, envelope JSONErrorEnvelope[T])
- func PrintJSONValue(w io.Writer, value any) error
- func PrintJson(body []byte)
- func PrintListOrExit[T any](rows []T, err error, failMsg string)
- func PrintPendingApproval(message, requestID string, retry NextAction, extra ...NextAction)
- func PrintPurposeAccepted(commandID string)
- func PrintPurposeDemand(message, commandID string, expiresAt *time.Time)
- func PrintPurposeRefused(commandID string, cause error)
- func PrintTable(slice any)
- func ProcessEditedData(originalData []byte) (any, error)
- func PromptForBool(prompt string) bool
- func PromptForInput(promptText string) string
- func PromptForInputWithDefault(promptText, defaultValue string) string
- func PromptForIntInput(promptText string, defaultValue int) int
- func PromptForListInput(promptText string) []string
- func PromptForPassword(promptText string) string
- func PromptForRequiredInput(promptText string) string
- func PromptForRequiredIntInput(promptText string) int
- func Red(value string) string
- func RedactURL(raw string) string
- func RedactURLError(err error) error
- func RedactURLErrorHostOnly(err error) error
- func RedactURLHostOnly(raw string) string
- func RemoteFileName(remotePath string) (string, error)
- func RemovePrefixBeforeAPI(url string) string
- func RequirePositiveInt(flagName string, value int)
- func RequireSubcommand(cmd *cobra.Command, notes ...string) error
- func RetryAfter(err error) time.Duration
- func RetryAfterFromHeader(header http.Header) time.Duration
- func SanitizeTerminalBlock(s string) (clean string, altered bool)
- func SanitizeTerminalLine(s string) (clean string, altered bool)
- func SanitizeTerminalText(s string) string
- func SaveFile(fileName string, data []byte) error
- func SaveStreamAtomic(fileName string, r io.Reader, newFilePerm os.FileMode) (int64, error)
- func ShowLogo(rightLines []string)
- func SplitAndParseInt(input string) []int
- func SplitAndTrim(s, sep string) []string
- func SplitPath(path string) (string, string, error)
- func SpoolToTempFile(pattern string, fn func(io.Writer) error) (*os.File, int64, error)
- func StripANSIEscapes(s string) string
- func StripControlChars(s string) string
- func StripFormatAndANSI(s string) string
- func StripFormatChars(s string) string
- func StructuredErrorCode(err error) string
- func ThrottleCeiling(timeout, tick time.Duration) time.Duration
- func TimeFormat(value int) *string
- func TimeUtils(t time.Time) string
- func TruncateString(str string, num int) string
- func Unzip(src string, dest string) error
- func WarnTerminalTextAltered(w io.Writer, indent string)
- func WriteToPager() (io.Writer, func())
- func Yellow(value string) string
- func ZipToWriter(folderPath string, w io.Writer) error
- type ErrorHandlerCallbacks
- type ErrorResponse
- type JSONErrorEnvelope
- type NextAction
- type SSHTarget
- type Spinner
- type ThrottleBudget
Constants ¶
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" // credential, did not reject it, and a retry can succeed. AuthVerificationUnavailable = "auth_verification_unavailable" // 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" // 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" // 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 requires a person's MFA, // which a token (API or service) cannot complete, so completing MFA under the // token cannot lift it. Signing in with 'alpacon login' without -t can. Removing // the action from the workspace's MFA required actions also can, but only for an // action the workspace armed: the server holds some actions (security settings, // sudo and approval policy writes, RBAC roles) to this no matter what. 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: 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 )
const ( OutputFormatTable = "table" OutputFormatJSON = "json" )
Valid values for the --output persistent flag.
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 )
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.
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" )
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 )
const DevVersion = "dev" // What Version carries when no -ldflags set it.
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.
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.
const UsageErrorCode = "usage_error"
UsageErrorCode is the synthetic error_code for local validation failures that never reached the server.
Variables ¶
var ErrInvalidID = errors.New("invalid id")
ErrInvalidID marks a local refusal of an ID that is unsafe as a URL path segment.
var OutputFormat string
OutputFormat holds the value of the --output persistent flag. Bound by cmd/root.go; read by PrintTable and PrintJson.
var Version string = DevVersion
Functions ¶
func AgentSessionScope ¶ added in v1.16.0
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 BoolPointerToString ¶
func CleanupTempFile ¶ added in v1.5.0
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
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 CliErrorEnvelopeWithExit ¶ added in v1.7.2
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
CliErrorWithExit handles all error messages in the CLI.
func CliErrorWithExitCode ¶ added in v1.9.2
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 CliInfoWithExit ¶
CliInfoWithExit prints an informational message to stderr and exits the program with a status code of 0
func CliSuccess ¶ added in v1.2.0
CliSuccess handles all success messages in the CLI.
func CliUsageErrorEnvelopeWithExit ¶ added in v1.7.2
CliUsageErrorEnvelopeWithExit reports a bad flag or argument and exits(2); error_code is fixed to UsageErrorCode.
func CliWarning ¶
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
CompactStrings trims whitespace from each element and drops empty entries.
func ConfirmAction ¶ added in v1.2.0
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 DebugEnabled ¶ added in v1.11.0
func DebugEnabled() bool
DebugEnabled reports whether diagnostic output is turned on.
func DecodeJWTPayload ¶ added in v1.1.0
DecodeJWTPayload decodes the payload (second segment) of a JWT token without verifying the signature. Returns the claims as a map.
func DeleteFile ¶
func ExtractBaseDomain ¶ added in v1.1.0
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
ExtractWorkspaceName extracts workspace name from workspace URL
func FormatJSON ¶ added in v1.6.0
func FormatTimestamp ¶ added in v1.16.0
FormatTimestamp renders a server timestamp in the local zone.
func GetCLIVersion ¶
func GetCLIVersion() string
func GetUserAgent ¶
func GetUserAgent() string
func HTTPStatusCode ¶ added in v1.8.1
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
HandleWorkSessionError prints a WorkSession gate diagnostic and exits(3); no-op for other errors.
func InteractiveOnly ¶ added in v1.15.0
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.
func IsAgentForbiddenScope ¶ added in v1.16.0
IsAgentForbiddenScope reports whether an agent session cannot hold scope.
func IsC1OrDEL ¶ added in v1.11.0
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
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
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
IsLocalTarget checks if a target string represents a local location
func IsRemoteTarget ¶ added in v0.4.0
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
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
IsRetryLaterStatus reports whether a 4xx is asking to be retried rather than refusing.
func IsSubmissionError ¶ added in v1.16.0
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
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 IsUnprocessedRequestError ¶ added in v1.15.0
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
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
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
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
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
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
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
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 PrintHeader ¶
func PrintHeader(header string)
func PrintJSONError ¶ added in v1.6.0
func PrintJSONError[T any](w io.Writer, envelope JSONErrorEnvelope[T])
func PrintListOrExit ¶ added in v1.15.0
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, extra ...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. extra follows the generic console pointer. 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
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
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 ¶
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 PromptForInput ¶
func PromptForInputWithDefault ¶ added in v1.3.4
PromptForInputWithDefault prompts for input and returns the default if empty.
func PromptForIntInput ¶
func PromptForListInput ¶
func PromptForPassword ¶
func PromptForRequiredInput ¶
func RedactURL ¶ added in v1.16.0
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
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
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
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
RemoteFileName returns the final path component for a remote file path.
func RemovePrefixBeforeAPI ¶
func RequirePositiveInt ¶ added in v1.9.2
RequirePositiveInt exits with a usage error when an integer flag is not positive.
func RequireSubcommand ¶ added in v1.15.0
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
RetryAfter returns the delay the server asked for on err, or 0 if it sent none.
func RetryAfterFromHeader ¶ added in v1.16.0
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
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
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
SanitizeTerminalText strips escape sequences before the standalone control bytes; reversed, ESC alone would go and "[2K" would stay on screen as text.
func SaveStreamAtomic ¶ added in v1.5.0
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 ¶
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 SplitAndTrim ¶ added in v1.4.4
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 ¶
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
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 StripControlChars ¶ added in v1.9.0
func StripFormatAndANSI ¶ added in v1.11.0
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
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
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
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 TruncateString ¶
func WarnTerminalTextAltered ¶ added in v1.11.2
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
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.
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 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
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
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) StopWriter ¶ added in v1.11.1
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
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.