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 ClassifyError(err error) 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 CliErrorWithCode(exitCode int, errorCode string, msg 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 CliParseErrorWithExit(cmd *cobra.Command, format, msg string)
- func CliSuccess(msg string, args ...any)
- func CliUsageErrorEnvelopeWithExit(operation string, format string, args ...any)
- func CliUsageErrorWithExit(msg 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 ExitIfUsageError(code int, operation string, err error, format string, args ...any)
- func ExitWithFailureJSON(f Failure)
- 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 HTTPErrorCode(status int) string
- func HTTPStatusCode(err error) int
- func HandleCommonErrors(err error, serverName string, callbacks ErrorHandlerCallbacks) error
- func HandleWorkSessionError(err error, operation, target, authMethod, activeWS string)
- func HintOnly(message string, refusal error) error
- 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 IsRefusalStatus(statusCode int) 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 IsUsageError(err error) bool
- func MarkNotLoggedIn(err error) error
- func MarkSubmission(err error) error
- func MarkUsageError(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 OutputFormatIn(args []string) string
- func ParseErrorGateAndMissing(err error) (string, []string)
- func ParseErrorResponse(err error) (string, string)
- func ParsePositiveDuration(flagName, raw string) (time.Duration, error)
- func ParseRefusalHint(body []byte, statusCode int) string
- func ParseRefusalNext(body []byte, statusCode int) string
- func PartialTableWithExit(rows any, msg string, args ...any)
- func PrettyJSON(data []byte) (*bytes.Buffer, error)
- func PrintDeviceCodePrompt(w io.Writer, verificationURI, userCode string) (printedURI string)
- 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 PrintRefusalHints(w io.Writer, err 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 RawTerminalHintLines(err error) string
- 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 RefusalHint(err error) 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 Reword(err error, message string) error
- func SanitizeServerHint(hint string) string
- 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 SetOutputFormat(value string) error
- func SetQuery(rawURL string, set map[string]string, del ...string) string
- 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 StderrForChild() *os.File
- 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 TrackedStderr() io.Writer
- func TruncateString(str string, num int) string
- func Unzip(src string, dest string) error
- func WarnTerminalTextAltered(w io.Writer, indent string)
- func WebsocketDialError(prefix string, err error, resp *http.Response) error
- func WithHTTPStatus(err error, statusCode int) error
- func WithRedirectStatus(err error, resp *http.Response) error
- func WriteToPager() (io.Writer, func())
- func Yellow(value string) string
- func ZipToWriter(folderPath string, w io.Writer) error
- type BatchError
- type ErrorHandlerCallbacks
- type ErrorResponse
- type Failure
- type JSONErrorEnvelope
- type NextAction
- type PartialInfo
- 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" // A work session can receive a session-authorized sudo policy without a // person's approval from the web console only; both names ride a 403. WorkSessionSudoBypassConsoleOnly = "work_session_sudo_bypass_console_only" WorkSessionSessionAuthorizedSudoConsoleOnly = "work_session_session_authorized_sudo_console_only" // SudoVerifyCredentialCannotProveMFA rides a 403 on sudo grant verification: // the credential is an API token, a service token or a non-interactive token, // so it cannot complete sudo MFA. Signing in interactively can. SudoVerifyCredentialCannotProveMFA = "sudo_verify_credential_cannot_prove_mfa" // Refusals of a session-authorized sudo policy bound to an AI agent session, both // on a 403. NeedsPresence: the write would leave the policy on an agent // session without a person proving presence for that request (a fresh MFA // on an interactive login). NeedsApproval: a direct write of such a policy // is refused; it has to arrive as a modification of the session, which a // person approves. SudoPolicyBypassAgentSessionNeedsPresence = "sudo_policy_bypass_agent_session_needs_presence" SudoPolicyBypassAgentSessionNeedsApproval = "sudo_policy_bypass_agent_session_needs_approval" SudoPolicySessionAuthorizedAgentSessionNeedsPresence = "sudo_policy_session_authorized_agent_session_needs_presence" SudoPolicySessionAuthorizedAgentSessionNeedsApproval = "sudo_policy_session_authorized_agent_session_needs_approval" // Codes the server sends on its own 404/429/406/415 refusals, with no detail. APINotFound = "api_not_found" APIRateLimited = "api_rate_limited" APINotAcceptable = "api_not_acceptable" APIUnsupportedMediaType = "api_unsupported_media_type" // Codes the Elasticsearch cursor paginator sends when a walk cannot go on: an // expired snapshot (400), a mismatched cursor (400), or no snapshot opened (503). APICursorExpired = "api_cursor_expired" APIInvalidCursor = "api_invalid_cursor" // ServerBusyWithUserWork means the server refused a disruptive action; --force overrides it. ServerBusyWithUserWork = "server_busy_with_user_work" // ServerPAMInstallUnsupported rides a 400: the host has no alpamon-pam // package path (macOS, Windows, or an unknown package manager). ServerPAMInstallUnsupported = "server_pam_install_unsupported" // ServerPAMInstallRequiresSudoWithMFA rides a 400: refused while "Use sudo with MFA" // is off, or always on a deployment that cannot complete an MFA step-up. ServerPAMInstallRequiresSudoWithMFA = "server_pam_install_requires_sudo_with_mfa" // ServerPAMInstallInProgress rides a 409: an alpamon-pam install is already pending. ServerPAMInstallInProgress = "server_pam_install_in_progress" // CommandInlineCredential means the server refused a command whose command line carries a // credential (a -p/--password flag, a KEY=VALUE secret such as PGPASSWORD=..., or a // user:pass@host connection string) it would otherwise store. Move the secret to --env. The // exec and websh help and the README's "When a command is denied" section repeat these forms; // update them together. // // The CLI deliberately does not expose the server's credential_exposure_acknowledged override: // it records the exposure rather than preventing it (hygiene, not authorization, with no role // gate), so it would be a one-flag way past the gate where rewriting with --env costs the same. // --env stays the only path. CommandInlineCredential = "command_inline_credential" // APITokenACLNotAllowed means the token's access control rules do not cover the command, server // or file path, so a retry fails the same way; widen them with 'alpacon token acl'. It rides a // 403 with no detail, so authStatusCodeMessage in client/client.go renders the message. APITokenACLNotAllowed = "api_token_acl_not_allowed" // CommandACLMoved rides a 405 on a command-ACL write once command ACLs live on // the command pre-approval ledger; codeOnlyMessage in client/client.go renders it. CommandACLMoved = "command_acl_moved" // AuthInteractiveChannelRequiresPresence rides a 403: a token gets no interactive channel // whatever its scopes and ACL rules say; only 'alpacon login' without -t lifts it. AuthInteractiveChannelRequiresPresence = "auth_interactive_channel_requires_presence" // AuthMFARequiresHumanPrincipal rides a 403: the action needs a person's MFA, which a token // (API or service) cannot complete; 'alpacon login' without -t can. Removing the action from // the workspace's MFA required actions also lifts it, except for actions the server always // holds to this (security settings, sudo and approval policy writes, RBAC roles). AuthMFARequiresHumanPrincipal = "auth_mfa_requires_human_principal" // The token-scope gate's refusals: the token's scopes do not cover this call, or // the server could not resolve the call's action to a scope at all. APITokenScopeMissing = "api_token_scope_missing" APITokenScopeActionUnresolved = "api_token_scope_action_unresolved" // WorkSession gate codes the server returns. WorkSessionRequired = "work_session_required" WorkSessionNotUsable = "work_session_not_usable" WorkSessionNotActive = "work_session_not_active" WorkSessionExpired = "work_session_expired" WorkSessionScopeNotAllowed = "work_session_scope_not_allowed" WorkSessionServerNotAllowed = "work_session_server_not_allowed" WorkSessionAssigneeMismatch = "work_session_assignee_mismatch" // WorkSessionAgentSessionRequired means the CLI declared an AI agent, and the // session it named is a user session. Only an agent session serves it. WorkSessionAgentSessionRequired = "work_session_agent_session_required" // WorkSessionAccountNotApproved means the command names an account other than // the one the session was approved to run as. WorkSessionAccountNotApproved = "work_session_account_not_approved" // Refusals of the account a work session create names with --account. WorkSessionTargetAccountAbsent = "work_session_target_account_absent" WorkSessionTargetAccountNotReachable = "work_session_target_account_not_reachable" TargetAccountOtherPerson = "target_account_other_person" // WorkSessionClusterNotAllowed: the cluster a kube session names is not // the one its work session targets. WorkSessionClusterNotAllowed = "work_session_cluster_not_allowed" // Refusals of a work session create's targets and lifetime. A session // targets servers or exactly one cluster, never both and never neither; a // cluster session holds kube and optionally kube_exec, nothing else, and // names no account; and its lifetime stays within the workspace's maximum. WorkSessionMixedTargets = "work_session_mixed_targets" WorkSessionNoServers = "work_session_no_servers" WorkSessionTooManyClusters = "work_session_too_many_clusters" WorkSessionInvalidScope = "work_session_invalid_scope" ClusterNotFound = "cluster_not_found" WorkSessionTargetAccountNotApplicable = "work_session_target_account_not_applicable" WorkSessionExpiresExceedsMaxTTL = "work_session_expires_exceeds_max_ttl" // Refusals of a kube session the server names itself. The cluster's agent // is not connected; the agent did not accept the session, which the server // then closed; and the caller has no user name the session could act as. ClusterNotConnected = "cluster_not_connected" KubeSessionChannelOpenFailed = "kube_session_channel_open_failed" KubeSessionPrincipalNotSupported = "kube_session_principal_not_supported" // WorkSession extension refusals: every 'work-session extend' needs a reason and follows the // workspace's approval policy, as 'work-session create' does, and a session holds at most one // pending extension request. WorkSessionExtensionReasonRequired = "work_session_extension_reason_required" WorkSessionExtensionAlreadyPending = "work_session_extension_already_pending" // WorkSessionAdmissionDenied means the workspace refuses this request outright // (session creation, or an extension)—not a queued request waiting on a // human, a hard no. WorkSessionAdmissionDenied = "work_session_admission_denied" // ExitCodeGeneralError is the process exit code for an ordinary failure, the one // CliErrorWithExit 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 // Cobra's parse or in its own validation. Unlike ExitCodeGeneralError, it means the invocation // itself was wrong, so scripts and AI agents fix the command line rather than retry it unchanged. ExitCodeUsageError = 2 // ExitCodeWorkSessionDenied is the process exit code for WorkSession gate refusals. ExitCodeWorkSessionDenied = 3 // ExitCodePendingApproval is the process exit code for an action whose approval is still open: // a sudo denial that created an approval request, a work session created pending, or a wait // that ended (timed out or interrupted) undecided. Unlike ExitCodeWorkSessionDenied nothing was // refused, so scripts and AI agents wait or check later. ExitCodePendingApproval = 4 // PendingApprovalStatus is the stable machine-readable status string emitted // under --output json when an action is pending human approval. PendingApprovalStatus = "pending_approval" // ExitCodeServerBusy is the process exit code for a disruptive server action refused because // the server has active user work (server_busy_with_user_work). Scripts and AI agents retry // when the server is idle, or re-run with --force. ExitCodeServerBusy = 5 // ExitCodeNotApproved is the process exit code for an awaited approval that ended without the // grant: rejected, expired, revoked, cancelled, or completed. Where ExitCodePendingApproval // means the outcome is still open, this one tells scripts and AI agents to stop re-requesting // approval. ExitCodeNotApproved = 6 // ExitCodePurposeRequired is the process exit code for a command the verification gate parked // while it asks what the command is for. No approval request exists, so it is not // ExitCodePendingApproval: the caller answers with 'alpacon exec purpose' within about a minute // rather than wait. ExitCodePurposeRequired = 7 // PurposeRequiredStatus is the stable machine-readable status string emitted // under --output json when a command is parked awaiting its purpose. PurposeRequiredStatus = "purpose_required" // ExitCodeUpdateAvailable is the process exit code for `alpacon update --check` finding a newer // release; a failed check exits ExitCodeGeneralError instead. ExitCodeUpdateAvailable = 8 )
const ( ErrorCodeUsage = "usage_error" // local validation that never reached the server ErrorCodeNotLoggedIn = "not_logged_in" ErrorCodeConfirmationRequired = "confirmation_required" ErrorCodeNetwork = "network_error" ErrorCodeNotApproved = "not_approved" ErrorCodeCLI = "cli_error" )
Synthetic error_code values: the CLI's own, for failures the server sent no code for.
const ( OutputFormatTable = "table" OutputFormatJSON = "json" )
Valid values for the --output persistent flag.
const ( // PollMaxBackoffTick caps a backoff gap, in multiples of the base tick. It is exported so a // poll loop's own test can state its capped wait as a constant expression. PollMaxBackoffTick = 60 // MaxConsecutivePollFailures bounds a wait's ride through failed polls: a run // of them means the CLI cannot reach the server, and saying so beats // reporting an outcome nobody read. MaxConsecutivePollFailures = 5 // PollMaxThrottleExtensions bounds how many times a throttled poll may push its // deadline out. A duration budget alone is not enough: a server answering // Retry-After: 1 would buy a whole window one second at a time. PollMaxThrottleExtensions = 60 )
const ( OperationCommand = "command" OperationWebFTP = "webftp" OperationWebsh = "websh" // OperationKube targets a cluster rather than a server: it needs a session // that holds the kube scope and targets that cluster. OperationKube = "kube" )
Operations HandleWorkSessionError reports; each 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; --wait-approval can exceed it. DefaultApprovalWaitTimeout = 5 * time.Minute )
const DevVersion = "dev" // What Version carries when no -ldflags set it.
const GatePlan = "plan"
GatePlan is the "gate" of a plan refusal, whose own message already states when its limit resets, so no Retry-After action is added for it.
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 MaxServerHintBytes = 256
MaxServerHintBytes is the most a server hint may take: the server keeps its own hints within it, and the CLI cuts anything longer, since nothing between the server and this process is trusted to have kept it.
const PurposeDemandLead = "Purpose required—the verification gate held this command and is asking what it is for. " +
"No approver has been notified: state the purpose and it is judged again, once, with that in hand."
PurposeDemandLead is the first half of the message every surface prints for an open demand. `exec` and `exec logs` differ only in what they add after it, so keeping the shared half here stops one from being reworded without the other.
Variables ¶
var CommandName string
CommandName is the full command path without the root name ("workspace ls"), set by the entry point.
var ErrInvalidID = errors.New("invalid id")
ErrInvalidID marks a local refusal of an ID that is unsafe as a URL path segment.
var ErrNotLoggedIn = errors.New("not logged in")
ErrNotLoggedIn marks a missing config file; a malformed or unreadable one stays cli_error.
var OutputFormat string
OutputFormat holds the value of the --output persistent flag.
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 ClassifyError ¶ added in v1.18.0
ClassifyError picks the error_code for err: the server's code, else http_<status>, else network_error for a transport failure, else cli_error. A missing config file is not_logged_in.
func CleanupTempFile ¶ added in v1.5.0
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 rare branch with no visible symptom, such as a degrade that succeeds and so looks exactly like the path it replaced. It takes the same break off a spinner line as CliWarning, since the refresh-token degrade logs inside the "Refreshing access token..." spinner.
func CliErrorEnvelopeWithExit ¶ added in v1.7.2
CliErrorEnvelopeWithExit reports a failure and exits 1, or 2 when err is an ErrInvalidID refusal or it or an argument is a usage error; json mode carries err's code.
func CliErrorEnvelopeWithExitCode ¶ added in v1.9.2
func CliErrorEnvelopeWithExitCode(code int, operation string, err error, format string, args ...any)
CliErrorEnvelopeWithExitCode is CliErrorEnvelopeWithExit with a caller-chosen exit code, for refusals a script branches on (e.g. ExitCodeNotApproved).
func CliErrorWithCode ¶ added in v1.18.0
CliErrorWithCode names the json error_code (an ErrorCode* constant); table mode follows the exit code, so only exit 1 keeps the report footer.
func CliErrorWithExit ¶ added in v1.0.0
CliErrorWithExit handles all error messages in the CLI and exits 1, or 2 when an argument is a usage error. Under --output json it prints one envelope instead, classified from the first error in args, and no footer.
func 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 CliParseErrorWithExit ¶ added in v1.18.0
CliParseErrorWithExit reports a command line cmd could not parse and exits 2 in format, the --output value its caller found before the parse stopped; table mode points to cmd's help.
func CliSuccess ¶ added in v1.2.0
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 with error_code usage_error. The envelope keeps no error from args, so a server refusal must not go through it.
func CliUsageErrorWithExit ¶ added in v1.18.0
CliUsageErrorWithExit reports a flag or argument the command rejected and exits 2 with error_code usage_error.
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 ExitIfUsageError ¶ added in v1.18.0
ExitIfUsageError is the one place a report that would exit 1 exits 2 instead: when err, or an error among args, answers IsUsageError, it reports through CliUsageErrorEnvelopeWithExit. Otherwise it returns.
func ExitWithFailureJSON ¶ added in v1.18.0
func ExitWithFailureJSON(f Failure)
ExitWithFailureJSON writes the envelope to stderr and exits with f.ExitCode under --output json; in table mode it returns so the caller's own message and exit stay as they were.
func ExtractBaseDomain ¶ added in v1.1.0
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 HTTPErrorCode ¶ added in v1.18.0
HTTPErrorCode is the synthetic code for a server or proxy answer that carried none.
func HTTPStatusCode ¶ added in v1.8.1
HTTPStatusCode returns the HTTP status carried by err, or 0 if none. Along a chain the outermost status wins. An error that joins several (a BatchError, errors.Join, fmt.Errorf with more than one %w) has a status only when the statuses found across its tree, nested joins included, are all one; two or more distinct statuses give 0.
func HandleCommonErrors ¶ added in v1.0.0
func HandleCommonErrors(err error, serverName string, callbacks ErrorHandlerCallbacks) error
HandleCommonErrors handles an MFA or username-required refusal through callbacks and retries the operation, returning nil once it succeeds. Only the tagged error of the operation's side-effecting request (MarkSubmission) is handled; any other error came after the operation took effect and is returned as is. The error it returns carries no tag.
func HandleWorkSessionError ¶ added in v1.4.8
HandleWorkSessionError prints a WorkSession gate diagnostic and exits(3); no-op for other errors. target is what the operation names: a cluster for OperationKube, a server otherwise.
func HintOnly ¶ added in v1.18.0
HintOnly returns an error that reads as message and carries refusal's hint, sanitized, and nothing else of it: no code, no status, no wrapped error. A timeout uses it to keep the guidance of the refusal its last poll got while staying a timeout to everything that classifies errors, such as the work-session gate or an MFA retry. Without a hint on refusal it is a plain error.
func InteractiveOnly ¶ added in v1.15.0
InteractiveOnly rewrites a token's refusal of an action only an interactive login may take; a scope refusal counts, since granting the scope only reaches the next refusal. A refusal carrying the server's hint is returned as it is: the hint is the guidance.
func IsAgentForbiddenScope ¶ added in v1.16.0
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 IsRefusalStatus ¶ added in v1.18.0
IsRefusalStatus reports whether statusCode is one the server answers a coded refusal with, the only responses whose "hint" is the server's guidance rather than a request field of that name.
func IsRemoteTarget ¶ added in v0.4.0
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 dial failed, or the server answered 429 or 503. Unlike IsTransientRequestError it leaves out a lost response, 502 and 504, which can follow a request that ran, so a non-idempotent request may be resent on it. Only a MarkSubmission-tagged error qualifies.
func IsUsageError ¶ added in v1.18.0
IsUsageError reports whether MarkUsageError tagged err or an error it wraps; a server's usage_error code does not count, since only this process knows its command line was wrong.
func MarkNotLoggedIn ¶ added in v1.18.0
MarkNotLoggedIn tags err with ErrNotLoggedIn and leaves its message as it was.
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 (the command submission, an upload or download create, a session create, a one-request change), or of a lookup before it. Only such an error says whether the server acted, so only it can be retried after MFA or ridden through when unprocessed.
The tag is read off the error as returned, never through wrapping, so a later request's error and a wrapped tagged error count as untagged, which means "the operation already took effect": HandleCommonErrors passes it through. The status and dial error underneath stay readable.
func MarkUsageError ¶ added in v1.18.0
MarkUsageError tags err as a command-line mistake, so ClassifyError reports usage_error for it.
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 opens url in the user's default browser. It does nothing when the browser cannot be opened (headless server, SSH session, container) or another process opened one recently.
Set ALPACON_NO_BROWSER=1 to disable it.
func OutputFormatIn ¶ added in v1.18.0
OutputFormatIn is the last --output value before any "--" in args, for a command line whose parse stopped before reaching it.
func ParseErrorGateAndMissing ¶ added in v1.13.2
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 ParseRefusalHint ¶ added in v1.18.0
ParseRefusalHint returns the "hint" string a 402/403/405/429 body carries, sanitized (SanitizeServerHint), or "" when there is none or nothing printable is left of it. A server that predates the field sends none. A request that does not go through the shared client reads its refusal's hint here, so its error can carry one too.
func ParseRefusalNext ¶ added in v1.18.0
ParseRefusalNext returns the "next" string a 402/403/405/429 body carries, or "" on any other status, where a field of that name is a request field.
func 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 PrintDeviceCodePrompt ¶ added in v1.18.0
PrintDeviceCodePrompt prints the device code prompt and returns the URL it printed, the one the browser must open, so the operator lands on the address they read. Both values come from the authorization server: each is sanitized as a single line, since a newline would let the server write its own line into the prompt. Sanitizing runs before Blue and Bold, since sanitizing afterward would strip their escape sequences.
func 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 reports an action that awaits out-of-band human approval and was not waited on: a {"status":"pending_approval", ...} envelope on stdout under --output json, else an actionable message on stderr. requestID may be empty. retry leads the next actions and keeps its Command a pure executable string, any hint in Description; extra follows the console pointer. It never exits, so the exit-code contract stays with the caller.
func PrintPurposeAccepted ¶ added in v1.12.0
func PrintPurposeAccepted(commandID string)
PrintPurposeAccepted reports a recorded purpose. There is no verdict yet—the command re-enters judgment on the worker—so the result names where to read the outcome rather than pretending to carry it.
func PrintPurposeDemand ¶ added in v1.12.0
PrintPurposeDemand reports a command the gate parked to ask its purpose: a {"status":"purpose_required", ...} envelope on stdout under --output json, else an actionable message on stderr. A nil expiresAt reports no deadline. It never exits, so the exit-code contract stays with the caller.
func PrintPurposeRefused ¶ added in v1.12.0
PrintPurposeRefused reports a rejected answer. The server answers a settled command and an answer from the wrong principal with one code, so neither this message nor the envelope can say which happened—hence the pointer at the command's own state rather than a guess, and never at a resubmission. It never exits; the caller owns the exit-code contract.
func PrintRefusalHints ¶ added in v1.18.0
PrintRefusalHints writes err's refusal guidance to w, one "Hint:" line per RefusalNextActions entry, for output written outside the Cli* helpers.
func PrintTable ¶
func PrintTable(slice any)
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 RawTerminalHintLines ¶ added in v1.18.0
RawTerminalHintLines renders err's refusal guidance for a terminal that may be in raw mode, where a bare newline leaves the cursor where it stood: one "Hint:" line per RefusalNextActions entry, each ending in \r\n.
func 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 RefusalHint ¶ added in v1.18.0
RefusalHint returns the sanitized hint the first error in err's chain that carries one holds, or "" when none does.
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 Reword ¶ added in v1.18.0
Reword returns an error that reads as message and keeps err in its chain, for a call site that words a failure itself: the Cli* error helpers still find err's server hint and print it under message, and err's code still reads through ParseErrorResponse.
func SanitizeServerHint ¶ added in v1.18.0
SanitizeServerHint makes a server hint safe to print on one terminal line: escape sequences, format characters and control characters (newlines included) are removed, surrounding space is trimmed, and the result is cut to MaxServerHintBytes without splitting a character.
func SanitizeTerminalBlock ¶ added in v1.11.2
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 SetOutputFormat ¶ added in v1.18.0
SetOutputFormat applies an --output value, refusing anything but table or json as a usage error.
func SetQuery ¶ added in v1.18.0
SetQuery changes only the query string, leaving an invalid URL for the caller to handle.
func ShowLogo ¶
func ShowLogo(rightLines []string)
ShowLogo renders the Pacabot mascot with up to 3 lines of text, beside the art when the terminal is wide enough and below it otherwise, so wrapped lines cannot break the half-block pixel art.
In color mode body cells are spaces on a cyan background, which fills any gap between lines; in plain mode (no TTY or NO_COLOR) they are █ glyphs. The ▄ and ▀ edge half-blocks stay in both modes because they define the shape. Brand colors: primary #27AAE1, secondary #58595B.
func 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 StderrForChild ¶ added in v1.18.0
StderrForChild returns os.Stderr itself, so the child still sees a terminal, and treats the line as left open, since the CLI cannot see what the child writes.
func StripANSIEscapes ¶ added in v1.9.0
func 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 TrackedStderr ¶ added in v1.18.0
TrackedStderr is os.Stderr as the process has it now, recording whether the last byte left the cursor mid-line, so the error envelope can start on its own line.
func TruncateString ¶
func 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 WebsocketDialError ¶ added in v1.18.0
WebsocketDialError reports a failed WebSocket dial whose URL path carries a channel token, keeping only its host and adding the handshake status a bad handshake alone never names.
func WithHTTPStatus ¶ added in v1.18.0
WithHTTPStatus tags err with statusCode for HTTPStatusCode.
func WithRedirectStatus ¶ added in v1.18.0
WithRedirectStatus keeps the 3xx a refused redirect leaves: Do returns it beside the error.
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 BatchError ¶ added in v1.18.0
BatchError joins the failures of independent items, such as the files of a bulk upload. Its message is Header followed by one line per failure. It unwraps to every failure, so each refusal's hint still prints, but no single item's code speaks for the batch: ParseErrorResponse and StructuredErrorCode do not look inside it, so a batch is never classified as one item's refusal (a work-session gate, an MFA step-up) and its per-item results stay in view.
func (*BatchError) Error ¶ added in v1.18.0
func (e *BatchError) Error() string
func (*BatchError) Unwrap ¶ added in v1.18.0
func (e *BatchError) Unwrap() []error
type ErrorHandlerCallbacks ¶ added in v1.0.0
type ErrorHandlerCallbacks struct {
OnMFARequired func(serverName string) error
OnUsernameRequired func() error
// RetryOperation re-runs the failed operation. After an MFA prompt it runs until it stops
// failing with auth_mfa_required, so its refusal is what tells the wait MFA is not done yet.
RetryOperation func() error
}
ErrorHandlerCallbacks defines callback functions for handling different error types.
type ErrorResponse ¶ added in v0.4.0
type Failure ¶ added in v1.18.0
type Failure struct {
ExitCode int
ErrorCode string
Err error
Message string
Operation string
RemoteExitCode *int
Partial *PartialInfo
NextActions []NextAction
HTTPStatus int
RetryAfter time.Duration
Server map[string]any
}
Failure describes a non-zero exit whose table-mode output the caller keeps; only the --output json envelope is built here. An empty ErrorCode is classified from Err.
type JSONErrorEnvelope ¶ added in v1.6.0
type JSONErrorEnvelope[T any] struct { OK bool `json:"ok"` ExitCode int `json:"exit_code"` ErrorCode string `json:"error_code"` Message string `json:"message"` Command string `json:"command,omitempty"` Reason string `json:"reason,omitempty"` Context T `json:"context"` HTTPStatus int `json:"http_status,omitempty"` RetryAfter int `json:"retry_after,omitempty"` Server map[string]any `json:"server,omitempty"` RemoteExitCode *int `json:"remote_exit_code,omitempty"` Partial *PartialInfo `json:"partial,omitempty"` NextActions []NextAction `json:"next_actions,omitempty"` }
JSONErrorEnvelope is the --output json failure line. Fields are additive only; exit_code and error_code are always present.
type NextAction ¶ added in v1.9.0
type NextAction struct {
Command string `json:"command,omitempty"`
Description string `json:"description,omitempty"`
}
NextAction is one actionable follow-up: Command is a runnable command with no inline comment, for machine consumers, and Description the human hint. Either may be empty, as a guidance-only pointer carries no command.
func RefusalNextActions ¶ added in v1.18.0
func RefusalNextActions(err error) []NextAction
RefusalNextActions is the server's guidance for a refused request, shown under the error line: each distinct hint as sent, then where to read the request's state ("next"), then the Retry-After wait of a gated refusal other than a plan limit. Nil when err carries none. Under an API token "next" is text only, since a path the server names may refuse token authentication.
func (NextAction) PlainText ¶ added in v1.9.0
func (a NextAction) PlainText() string
PlainText renders the action as a human-facing line: "command # description", or just the command or description when the other is empty. Sanitized here because its callers write to the terminal outside the Cli* helpers and call sites interpolate server-returned ids into Command; the JSON envelope marshals the fields themselves and escapes via escapeJSONControls instead.
type PartialInfo ¶ added in v1.18.0
type PartialInfo struct {
Count int `json:"count"`
}
type SSHTarget ¶ added in v0.4.0
type SSHTarget struct {
User string // Username (empty if not specified)
Host string
Path string // Path (empty if not specified)
}
SSHTarget represents a parsed SSH-like target with user, host, and path components.
func ParseSSHTarget ¶ added in v0.4.0
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; otherwise output streamed under a running spinner is drawn over, then erased by Stop. Callers waiting on something that may start producing output hand their writer through here. An empty write leaves the spinner alone.
type ThrottleBudget ¶ added in v1.12.0
type ThrottleBudget struct {
// contains filtered or unexported fields
}
ThrottleBudget is the allowance a poll spends to survive being rate limited. A 429 says the server is alive and pushing back, not that the work is lost, so the deadline moves rather than starving—but only this far.
func NewThrottleBudget ¶ added in v1.12.0
func NewThrottleBudget(timeout time.Duration) *ThrottleBudget
NewThrottleBudget returns a new budget that treats timeout as its cumulative extension limit.
func (*ThrottleBudget) Extend ¶ added in v1.12.0
Extend grows deadline by delay when the budget allows it, and reports whether it did. An extension is granted while the time spent so far is still under limit and the count is still under PollMaxThrottleExtensions.
The grant that carries the total past limit is taken whole rather than trimmed, since a clipped grant would leave the poll no time to serve the wait the throttled server itself just asked for. That overshoot is one delay wide, which the caller caps at PollMaxBackoffTick times its base tick, and no further extension follows it.
func (*ThrottleBudget) Reset ¶ added in v1.12.0
func (b *ThrottleBudget) Reset()
Reset clears the spent budget, extension count, and warning flag—called when the poll sees progress, so a throttle late in a long wait is not charged against an earlier, unrelated one.
func (*ThrottleBudget) ShouldWarn ¶ added in v1.12.0
func (b *ThrottleBudget) ShouldWarn() bool
ShouldWarn reports true once, the first time it is called since construction or the last Reset—so a wait that stays throttled for a long time still warns only once.
func (*ThrottleBudget) WarnThrottled ¶ added in v1.12.0
func (b *ThrottleBudget) WarnThrottled(delay time.Duration)
WarnThrottled prints the rate-limit notice once per throttled stretch, so every wait loop shows the same line. CliWarning steps off a running spinner's line itself, so the caller need not stop one first.
Source Files
¶
- browser.go
- color.go
- error.go
- error_codes.go
- error_envelope.go
- error_handler.go
- failure_report.go
- file_replace_unix.go
- file_save.go
- jwt.go
- log.go
- output.go
- pager.go
- pending_approval.go
- poll.go
- prompt.go
- purpose_demand.go
- redact.go
- refusal_hint.go
- remote_path.go
- spinner.go
- ssh_parser.go
- stderr_line.go
- unzip_path.go
- utils.go
- version.go
- worksession_error.go