Documentation
¶
Index ¶
- Constants
- Variables
- func AgentSessionScope(operation string) string
- func BeginTokenRefresh() func()
- 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, error)
- func CheckPositiveInt(flagName string, value int) error
- 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 CliErrorWithExit(msg string, args ...any)
- func CliInfo(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 Confirm(msg string, args ...any) (bool, error)
- func DebugEnabled() bool
- func DecodeErrorObject(body []byte) (map[string]any, bool)
- func DecodeJWTPayload(token string) (map[string]any, error)
- func DeleteFile(path string) error
- func EmitLocalSignal(kind localsignal.Kind, fields localsignal.Fields, ...)
- func Exit(code int)
- 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 FprintExitError(w io.Writer, e *ExitError)
- func FprintFailureJSON(w io.Writer, f Failure)
- 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 HasExecutableRefusalStep(err error) bool
- func HasFieldErrorCode(err error, field, code string) bool
- func HasIssuedRefusalStep(err error) bool
- func HasRefusalOutcome(err error) bool
- func HasUnixModes() bool
- func HiddenCount(hidden *int) int
- func HintOnly(message string, refusal error) error
- func InteractiveOnly(err error, action string) error
- func IsAgentForbiddenScope(scope string) bool
- func IsApprovalLapse(code string) bool
- func IsC1OrDEL(r rune) bool
- func IsControlRune(r rune) bool
- func IsFatalClientError(status int) bool
- func IsHookError(err error) 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 IsServerErrorCode(code string) 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 JoinReached(names []string, hidden *int, noun string) string
- func LastOutputPaged() bool
- func MarkApprovalSignaled(err error) error
- func MarkHookErrors(c *cobra.Command) (restore func())
- func MarkNotLoggedIn(err error) error
- func MarkSubmission(err error) error
- func MarkUsageError(err error) error
- func NewEnvelopeExitError(operation string, err error, msg string, args ...any) error
- func NewEnvelopeExitErrorWithCode(code int, operation string, err error, msg string, args ...any) error
- func NewExitError(msg string, args ...any) error
- func NewExitErrorWithCode(code int, msg string, args ...any) error
- func NewExitErrorWithErrorCode(exitCode int, errorCode, msg string, args ...any) error
- func NewFailureExitError(f Failure, table func(w io.Writer, s *IOStreams)) error
- func NewFailureExitErrorFunc(code int, failure func() Failure, table func(w io.Writer, s *IOStreams)) error
- func NewMFARequiredExitError(operation, message string, next []NextAction) error
- func NewParseExitError(cmd *cobra.Command, format, msg string) error
- func NewSilentExitError(code int) error
- func NewUsageEnvelopeExitError(operation, msg string, args ...any) error
- func NewUsageExitError(msg string, args ...any) 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(cmd *cobra.Command, args []string) (format string, given, missing bool)
- func ParseErrorGateAndMissing(err error) (string, []string)
- func ParseErrorResponse(err error) (string, string)
- func ParseIntList(input string) ([]int, error)
- func ParsePositiveDuration(flagName, raw string) (time.Duration, error)
- func ParseRefusalHint(body []byte, statusCode int) string
- func ParseRefusalNext(body []byte, statusCode int) string
- func ParseServerTarget(server, username string) (host, user string)
- func PartialTableExitError(rows any, msg string, args ...any) error
- func PausedRefusalFrame(message []byte) (localsignal.Fields, bool)
- func PausedRefusalNotice(message []byte) (string, bool)
- func PrettyJSON(data []byte) (*bytes.Buffer, error)
- func PrintDeviceCodePrompt(w io.Writer, verificationURI, userCode string) (printedURI string)
- func PrintExitError(e *ExitError)
- 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) error
- func PrintList[T any](rows []T, err error, failMsg string) error
- func PrintListTo[T any](s *IOStreams, rows []T, err error, failMsg string) error
- 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) error
- func ProcessEditedData(originalData []byte) (any, error)
- func ProcessExitCode(code int) int
- func PromptForBool(prompt string) bool
- func PromptForPassword(promptText string) (string, error)
- func ProtectRefreshOnSignal() func()
- func RawTerminalHintLines(err error) string
- func ReadInput(promptText string) (string, error)
- func ReadInputWithDefault(promptText, defaultValue string) (string, error)
- func ReadIntInput(promptText string, defaultValue int) (int, error)
- func ReadRequiredInput(promptText string) (string, error)
- func ReadRequiredIntInput(promptText string) (int, error)
- 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 RejectUnknownSubcommand(notes ...string) cobra.PositionalArgs
- func RemoteFileName(remotePath string) (string, error)
- func RemotePathBase(remotePath string, windows bool) string
- func RemotePathDir(remotePath string, windows bool) string
- func ReportNoChanges(err error) bool
- 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 SanitizeTerminalBlockKeepingTabs(s string) string
- func SanitizeTerminalLine(s string) (clean string, altered bool)
- func SanitizeTerminalOneLine(s string) string
- 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 ServiceTokenAccountMessage(field string) string
- func SetOutputFormat(value string) error
- func SetQuery(rawURL string, set map[string]string, del ...string) string
- func ShowLogo(rightLines []string)
- func SignalApprovalPending(err error, fields localsignal.Fields)
- func SignalFields(err error) localsignal.Fields
- func SignalPaused(err error)
- func SignalRefusal(err error)
- func SignalResponse(status int, body []byte, sources ...SignalOriginSource)
- 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 WaitForTokenRefreshes()
- func WarnTerminalTextAltered(w io.Writer, indent string)
- func WebsocketDialError(prefix string, err error, resp *http.Response) error
- func WithExitError(run func(*cobra.Command, []string) error) func(*cobra.Command, []string) error
- func WithHTTPStatus(err error, statusCode int) error
- func WithRedirectStatus(err error, resp *http.Response) error
- func WithSignalFields(err error, fields localsignal.Fields, sources ...SignalOriginSource) error
- func WorkSessionExitError(err error, operation, target, authMethod, activeWS string) error
- func WorkSessionReason(code string) string
- func WriteToPager() (io.Writer, func())
- func Yellow(value string) string
- func ZipToWriter(folderPath string, w io.Writer) error
- type AnnotatedText
- type BatchError
- type ErrorHandlerCallbacks
- type ErrorResponse
- type ExitError
- type Failure
- type HeldRequest
- type IOStreams
- func (s *IOStreams) AgentInputError(answer string) error
- func (s *IOStreams) AgentMode() bool
- func (s *IOStreams) Blue(value string) string
- func (s *IOStreams) Bold(value string) string
- func (s *IOStreams) CommandExitError(cmd *cobra.Command, args []string, err error) *ExitError
- func (s *IOStreams) FprintExitError(w io.Writer, e *ExitError)
- func (s *IOStreams) FprintFailureJSON(w io.Writer, f Failure)
- func (s *IOStreams) Green(value string) string
- func (s *IOStreams) Info(msg string, args ...any)
- func (s *IOStreams) IsJSON() bool
- func (s *IOStreams) ListenerReady(local, remote, message string)
- func (s *IOStreams) NewParseExitError(cmd *cobra.Command, format, msg string) error
- func (s *IOStreams) OutIsTerminal() bool
- func (s *IOStreams) OutputFormat() string
- func (s *IOStreams) Pager() (io.Writer, func())
- func (s *IOStreams) PagerWithError() (io.Writer, func() error)
- func (s *IOStreams) PartialTableExitError(rows any, msg string, args ...any) error
- func (s *IOStreams) PrintCommandRunning(commandID, status string) error
- func (s *IOStreams) PrintExitError(e *ExitError)
- func (s *IOStreams) PrintHeader(header string)
- func (s *IOStreams) PrintJson(body []byte) error
- func (s *IOStreams) PrintPendingApproval(message, requestID string, retry NextAction, extra ...NextAction)
- func (s *IOStreams) PrintPendingApprovalWithError(message, requestID string, cause error, retry NextAction, extra ...NextAction)
- func (s *IOStreams) PrintPurposeAccepted(commandID string)
- func (s *IOStreams) PrintPurposeDemand(message, commandID string, expiresAt *time.Time)
- func (s *IOStreams) PrintPurposeRefused(commandID string, cause error)
- func (s *IOStreams) PrintRefusalHints(w io.Writer, err error)
- func (s *IOStreams) PrintTable(slice any) error
- func (s *IOStreams) Progress(msg string, args ...any)
- func (s *IOStreams) RawTerminalHintLines(err error) string
- func (s *IOStreams) Red(value string) string
- func (s *IOStreams) ReportNoChanges(err error) bool
- func (s *IOStreams) ResolveOutput(value string, given bool) error
- func (s *IOStreams) SetExplicitOutputFormat(value string) error
- func (s *IOStreams) SetOutputDefaults(value string, agentDetected bool)
- func (s *IOStreams) SetOutputFormat(value string) error
- func (s *IOStreams) Success(msg string, args ...any)
- func (s *IOStreams) WarnTerminalTextAltered(w io.Writer, indent string)
- func (s *IOStreams) Warning(msg string, args ...any)
- func (s *IOStreams) Yellow(value string) string
- type JSONErrorEnvelope
- type NextAction
- type PartialInfo
- type RefusalOutcome
- type SSHTarget
- type SignalOriginSource
- type Spinner
- type ThrottleBudget
- type Timestamp
- type TruncatedText
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" // SudoPolicyPatternHasSudoPrefix rides a 400 on a work session create or // update whose --sudo pattern begins with sudo, which a pattern leaves out. SudoPolicyPatternHasSudoPrefix = "sudo_policy_pattern_has_sudo_prefix" // Refusals of a kube session the server names itself. The cluster's agent // is not connected; the agent did not accept the session, which the server // then closed; the caller's username cannot be the session's identity, // unset on an older server or one the server refuses; and // the cluster's RBAC bindings made outside Alpacon grant sessions more than // Alpacon does, under a workspace policy that refuses rather than warns. ClusterNotConnected = "cluster_not_connected" KubeSessionChannelOpenFailed = "kube_session_channel_open_failed" KubeSessionPrincipalNotSupported = "kube_session_principal_not_supported" ClusterRBACDrift = "cluster_rbac_drift" // WorkSession extension refusals: every 'work-session extend' needs a reason and follows the // workspace's approval policy, as 'work-session create' does, and a session holds at most one // pending extension request. WorkSessionExtensionReasonRequired = "work_session_extension_reason_required" WorkSessionExtensionAlreadyPending = "work_session_extension_already_pending" // WorkSessionAdmissionDenied means the workspace refuses this request outright // (session creation, or an extension)—not a queued request waiting on a // human, a hard no. WorkSessionAdmissionDenied = "work_session_admission_denied" // ExitCodeGeneralError is the process exit code for an ordinary failure, the one // NewExitError exits with. Name it when calling NewExitErrorWithCode so the general case // reads like the specific ones beside it. ExitCodeGeneralError = 1 // ExitCodeUsageError is the process exit code for a flag or argument a command rejected, in // Cobra's parse or in its own validation. Unlike ExitCodeGeneralError, it means the invocation // itself was wrong, so scripts and AI agents fix the command line rather than retry it unchanged. ExitCodeUsageError = 2 // ExitCodeWorkSessionDenied is the process exit code for WorkSession gate refusals. ExitCodeWorkSessionDenied = 3 // ExitCodePendingApproval is the process exit code for an action whose approval is still open: // a sudo denial that created an approval request, a work session created pending, or a wait // that ended (timed out or interrupted) undecided. Unlike ExitCodeWorkSessionDenied nothing was // refused, so scripts and AI agents wait or check later. ExitCodePendingApproval = 4 // PendingApprovalStatus is the stable machine-readable status string emitted // under --output json when an action is pending human approval. PendingApprovalStatus = "pending_approval" // ExitCodeServerBusy is the process exit code for a disruptive server action refused because // the server has active user work (server_busy_with_user_work). Scripts and AI agents retry // when the server is idle, or re-run with --force. ExitCodeServerBusy = 5 // ExitCodeNotApproved is the process exit code for an awaited approval that ended without the // grant: rejected, expired, revoked, cancelled, or completed. Where ExitCodePendingApproval // means the outcome is still open, this one tells scripts and AI agents to stop re-requesting // approval. A command the server denied after submission (status denied) exits with it too. ExitCodeNotApproved = 6 // ExitCodePurposeRequired is the process exit code for a command the verification gate parked // while it asks what the command is for. No approval request exists, so it is not // ExitCodePendingApproval: the caller answers with 'alpacon exec purpose' within about a minute // rather than wait. ExitCodePurposeRequired = 7 // PurposeRequiredStatus is the stable machine-readable status string emitted // under --output json when a command is parked awaiting its purpose. PurposeRequiredStatus = "purpose_required" // CommandRunningStatus is the stable machine-readable status string `exec logs` emits under // --output json for a command that has not finished. It exits 0: nothing failed or is held. CommandRunningStatus = "running" // ExitCodeUpdateAvailable is the process exit code for `alpacon update --check` finding a newer // release; a failed check exits ExitCodeGeneralError instead. ExitCodeUpdateAvailable = 8 // ExitCodeMFARequired is the process exit code for an action that waits on a person to finish // MFA in a browser: 'alpacon kube mfa' run where stdin or stderr is not a terminal, or its // wait ending before the MFA did. Nothing was refused, and the link it printed still works after the CLI exits, so // scripts and AI agents hand the link to the person and run the command again once they are // done, rather than fixing the command line or giving up. ExitCodeMFARequired = 9 )
const ( ServiceTokenAccountNotOwn = "service_token_account_not_own" ApplicationSystemUserNotFound = "application_system_user_not_found" // Validation codes the server may send with only the generic "Invalid input." message. ServerUsernameGroupnameInvalid = "server_username_groupname_invalid" WebFTPNameTooLong = "webftp_name_too_long" WebFTPInvalidPath = "webftp_invalid_path" )
const ( ErrorCodeUsage = "usage_error" // local validation that never reached the server ErrorCodeNotLoggedIn = "not_logged_in" ErrorCodeConfirmationRequired = "confirmation_required" ErrorCodeNetwork = "network_error" ErrorCodeNotApproved = "not_approved" ErrorCodeMFARequired = "mfa_required" ErrorCodeCLI = "cli_error" ErrorCodeRemoteCommandFailed = "remote_command_failed" // a remote command ended in failure ErrorCodeLocalCommandFailed = "local_command_failed" // tunnel's local command exited non-zero ErrorCodePurposeRefused = "purpose_refused" )
Synthetic error_code values: the CLI's own, for failures the server sent no code for.
const ( ApprovalExpired = "approval_expired" ApprovalCancelled = "approval_cancelled" ApprovalRuleChanged = "approval_rule_changed" SessionPaused = "session_paused" SupersededByPause = "superseded_by_pause" )
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" OperationTunnel = "tunnel" // OperationKube targets a cluster rather than a server: it needs a session // that holds the kube scope and targets that cluster. OperationKube = "kube" )
WorkSessionExitError names one of these operations in its diagnostic. Each is also the WorkSession scope that the operation requires.
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 ErrNoChanges = errors.New("no changes made")
ErrNoChanges reports that an edit left nothing to apply.
var ErrNotLoggedIn = errors.New("not logged in")
ErrNotLoggedIn marks a missing config file; a malformed or unreadable one stays cli_error.
var LocalSignalConsoleOrigin = func() (workspaceURL, baseDomain string) { return "", "" }
The command layer supplies config access without making utils import config.
var OutputFormat string
OutputFormat holds the value of the --output persistent flag.
var Stdio = SystemIOStreams()
Stdio is the process's own streams, which the package-level print helpers write through.
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 BeginTokenRefresh ¶ added in v1.20.0
func BeginTokenRefresh() func()
BeginTokenRefresh keeps process exit from interrupting a rotated token's save.
func BoolPointerToString ¶
func BuildURL ¶
BuildURL joins relativePath onto basePath with a trailing slash and params as the query, or returns the parse error when basePath is not a URL.
func CheckPositiveInt ¶ added in v1.20.0
CheckPositiveInt returns the usage failure for an integer flag that is not positive, or nil.
func ClassifyError ¶ added in v1.18.0
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 or an argument is a usage error; json mode carries err's code.
func CliErrorEnvelopeWithExitCode ¶ added in v1.9.2
func CliErrorEnvelopeWithExitCode(code int, operation string, err error, format string, args ...any)
CliErrorEnvelopeWithExitCode is CliErrorEnvelopeWithExit with a caller-chosen exit code, for refusals a script branches on (e.g. ExitCodeNotApproved).
func CliErrorWithExit ¶ added in v1.0.0
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 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 Confirm ¶ added in v1.20.0
Confirm asks msg as a yes/no question before a destructive action. A decline prints the cancel notice and returns false, which the caller ends on with exit 0; a non-interactive run returns the exit-2 failure.
func DebugEnabled ¶ added in v1.11.0
func DebugEnabled() bool
DebugEnabled reports whether diagnostic output is turned on.
func DecodeErrorObject ¶ added in v1.21.0
DecodeErrorObject reads a complete JSON object while preserving numbers as sent.
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 EmitLocalSignal ¶ added in v1.20.0
func EmitLocalSignal(kind localsignal.Kind, fields localsignal.Fields, sources ...SignalOriginSource)
func Exit ¶ added in v1.20.0
func Exit(code int)
Exit lets a refresh save its rotated token before terminating the process.
func ExitIfUsageError ¶ added in v1.18.0
ExitIfUsageError exits 2 for a report that would exit 1 when err, or an error among args, answers IsUsageError, as newExitError and newEnvelopeExitError do for an ExitError. Otherwise it returns.
func ExitWithFailureJSON ¶ added in v1.18.0
func ExitWithFailureJSON(f Failure)
ExitWithFailureJSON writes the envelope to stderr and exits with f.ExitCode under --output json; in table mode it returns so the caller's own message and exit stay as they were.
func ExtractBaseDomain ¶ added in v1.1.0
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 FprintExitError ¶ added in v1.20.0
FprintExitError writes what PrintExitError writes to w.
func FprintFailureJSON ¶ added in v1.20.0
FprintFailureJSON writes f's envelope to w whatever the output format, for a caller that has checked for --output json and returns the exit rather than taking it.
func GetCLIVersion ¶
func GetCLIVersion() string
func GetUserAgent ¶
func GetUserAgent() string
func 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 settles a tagged submission refusal (MarkSubmission) through callbacks and retries, returning nil on success. Any other error came after the operation took effect and is returned as is; the returned error carries no tag.
func HasExecutableRefusalStep ¶ added in v1.21.0
HasExecutableRefusalStep reports whether the refusal supplies a supported, complete action.
func HasFieldErrorCode ¶ added in v1.20.0
HasFieldErrorCode reports whether the server's field_errors list an entry for field with code.
func HasIssuedRefusalStep ¶ added in v1.21.0
HasIssuedRefusalStep reports whether a workspace refusal supplies a step that stops decision recovery.
func HasRefusalOutcome ¶ added in v1.21.0
HasRefusalOutcome reports whether the refusal has a displayable reason or step.
func HasUnixModes ¶ added in v1.20.0
func HasUnixModes() bool
HasUnixModes reports whether the OS has Unix permission bits. Windows has none, and Chmod there toggles the read-only attribute instead.
func HiddenCount ¶ added in v1.20.0
HiddenCount reads a count of targets the server left unnamed; nil (a server older than Alpacon Server 2.48.0) and a negative value count as none.
func HintOnly ¶ added in v1.18.0
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 IsApprovalLapse ¶ added in v1.20.0
IsApprovalLapse reports an approval that ended without a denial.
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 IsHookError ¶ added in v1.20.0
IsHookError reports whether err came from a hook MarkHookErrors wrapped.
func IsInteractiveShell ¶ added in v0.4.4
func IsInteractiveShell() bool
IsInteractiveShell checks if the current program is running in an interactive terminal.
func IsLocalTarget ¶ added in v0.4.0
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 reports whether target holds a colon and is not spelled as a local path: a ./, ../, .\, ..\, \\ or / prefix, C:\x, or C:/x on Windows.
func IsReplacementTempName ¶ added in v1.12.0
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 IsServerErrorCode ¶ added in v1.20.2
IsServerErrorCode reports whether code has the shape accepted for a server error code.
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 a MarkSubmission-tagged request can be safely resent. A 429 qualifies even when it carries an issued step. A failed dial or a 503 qualifies only when there is no issued step. A lost response, 502 or 504 can follow a request that ran.
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 JoinReached ¶ added in v1.20.0
JoinReached joins names and says how many more are hidden ("web-1 and 2 more", or "2 servers you cannot access" with no name left); noun is singular, and names are returned unsanitized.
func LastOutputPaged ¶ added in v1.20.0
func LastOutputPaged() bool
LastOutputPaged reports whether the last flush ran a pager rather than falling back to stdout, so a caller can repeat on stderr what the pager scrolled away.
func MarkApprovalSignaled ¶ added in v1.20.0
func MarkHookErrors ¶ added in v1.20.0
MarkHookErrors wraps what every error-returning hook of c and its subcommands returns, so IsHookError can tell a command's own failure from Cobra's parse error. restore puts the original hooks back.
func MarkNotLoggedIn ¶ added in v1.18.0
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 NewEnvelopeExitError ¶ added in v1.20.0
NewEnvelopeExitError is the failure CliErrorEnvelopeWithExit reports: exit 1 with the footer, or 2 when err or an argument is a usage error; json mode classifies err under operation.
func NewEnvelopeExitErrorWithCode ¶ added in v1.20.0
func NewEnvelopeExitErrorWithCode(code int, operation string, err error, msg string, args ...any) error
NewEnvelopeExitErrorWithCode is the failure CliErrorEnvelopeWithExitCode reports: the given exit and no footer, or exit 2 when code is 1 and err or an argument is a usage error.
func NewExitError ¶ added in v1.20.0
NewExitError is the failure CliErrorWithExit reports: exit 1 with the issue footer, or 2 when an argument is a usage error.
func NewExitErrorWithCode ¶ added in v1.20.0
NewExitErrorWithCode returns a failure with the given exit code and no footer, for an expected refusal scripts branch on.
func NewExitErrorWithErrorCode ¶ added in v1.20.0
NewExitErrorWithErrorCode names the json error_code (an ErrorCode* constant); table mode follows the exit code, so only exit 1 keeps the report footer.
func NewFailureExitError ¶ added in v1.20.2
NewFailureExitError prints f's envelope under --output json or calls table when non-nil.
func NewFailureExitErrorFunc ¶ added in v1.20.2
func NewFailureExitErrorFunc(code int, failure func() Failure, table func(w io.Writer, s *IOStreams)) error
NewFailureExitErrorFunc is NewFailureExitError for an envelope worth building only under --output json.
func NewMFARequiredExitError ¶ added in v1.20.1
func NewMFARequiredExitError(operation, message string, next []NextAction) error
NewMFARequiredExitError returns the exit-9 failure for an action that waits on a person to finish MFA in a browser: message on a warning line and next under a "Next:" list in table mode, or one error envelope with error_code mfa_required and next as its next_actions under --output json. Nothing was refused, so no server error rides along and no footer is printed.
func NewParseExitError ¶ added in v1.20.0
NewParseExitError is the failure CliParseErrorWithExit reports. It applies format, as that does.
func NewSilentExitError ¶ added in v1.20.0
NewSilentExitError returns a failure with the given exit code that prints nothing, for a command that wrote its own failure line.
func NewUsageEnvelopeExitError ¶ added in v1.20.0
NewUsageEnvelopeExitError is the failure CliUsageErrorEnvelopeWithExit reports.
func NewUsageExitError ¶ added in v1.20.0
NewUsageExitError is the failure CliUsageErrorWithExit reports: exit 2 with error_code usage_error.
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, skipping the values of cmd's other flags, for a command line whose parse stopped before reaching it; given reports whether one was read, and missing whether a final --output had no value, which leaves an earlier value in force.
func ParseErrorGateAndMissing ¶ added in v1.13.2
func ParseErrorResponse ¶ added in v0.4.0
ParseErrorResponse returns a typed error's code and source, never text a server message could forge.
func ParseIntList ¶ added in v1.20.0
ParseIntList parses a comma-separated list of integers, or returns the exit-1 failure on any other value.
func ParsePositiveDuration ¶ added in v1.9.1
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 ParseServerTarget ¶ added in v1.20.1
ParseServerTarget splits user@host into host and user; a non-empty username wins over the inline one. A target holding a colon is returned untouched.
func PartialTableExitError ¶ added in v1.20.0
PartialTableExitError prints rows to stdout and the reason to stderr (an envelope under --output json), then returns exit 1, or PrintTable's failure when rows do not print. It does not check for empty rows.
func PausedRefusalFrame ¶ added in v1.20.2
func PausedRefusalFrame(message []byte) (localsignal.Fields, bool)
PausedRefusalFrame reads a session_paused refusal sent as one text frame on an established socket, and returns the session it names.
func PausedRefusalNotice ¶ added in v1.20.2
PausedRefusalNotice is the paused signal's text for a session_paused refusal frame, for a terminal that shows it in line rather than as a banner.
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 PrintExitError ¶ added in v1.20.0
func PrintExitError(e *ExitError)
PrintExitError writes e to stderr: the error line, the server's hint and the footer, or one envelope under --output json.
func PrintHeader ¶
func PrintHeader(header string)
func PrintJSONError ¶ added in v1.6.0
func PrintJSONError[T any](w io.Writer, envelope JSONErrorEnvelope[T])
func PrintJson ¶
PrintJson prints body to stdout as indented JSON, or returns the exit-1 failure when body is not JSON.
func PrintList ¶ added in v1.20.0
PrintList prints a list a paginated read returned with err. On a nil err it is PrintTable; otherwise it prints the rows as partial through PartialTableExitError, or fails with failMsg when there are none.
func PrintListTo ¶ added in v1.20.0
PrintListTo is PrintList on s; a generic function, since Go methods take no type parameters.
func PrintPendingApproval ¶ added in v1.7.2
func PrintPendingApproval(message, requestID string, retry NextAction, extra ...NextAction)
PrintPendingApproval reports an action that awaits out-of-band human approval and was not waited on: a {"status":"pending_approval", ...} envelope on stdout under --output json, else an actionable message on stderr. requestID may be empty. retry leads the next actions and keeps its Command a pure executable string, any hint in Description; extra follows the console pointer. It never exits, so the exit-code contract stays with the caller.
func PrintPurposeAccepted ¶ added in v1.12.0
func PrintPurposeAccepted(commandID string)
PrintPurposeAccepted reports a recorded purpose. There is no verdict yet—the command re-enters judgment on the worker—so the result names where to read the outcome rather than pretending to carry it.
func PrintPurposeDemand ¶ added in v1.12.0
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 ¶
PrintTable prints a slice of row structs as a table, or as JSON under --output json. It returns the exit-1 failure when slice is not a slice or does not marshal.
func ProcessEditedData ¶
ProcessEditedData opens originalData as pretty JSON in the editor and returns the edited JSON, or ErrNoChanges when the bytes are unchanged.
func ProcessExitCode ¶ added in v1.20.2
ProcessExitCode returns the status this process can exit with for a remote failure's code: never 0, and only the bits a parent process can read—the low 8 on Unix, the low 32 on Windows.
func PromptForBool ¶
func PromptForPassword ¶
PromptForPassword reads a password after promptText. Ctrl+C returns an exit-1 failure.
func ProtectRefreshOnSignal ¶ added in v1.20.0
func ProtectRefreshOnSignal() func()
ProtectRefreshOnSignal lets an active grant save before a terminating signal is re-raised.
func RawTerminalHintLines ¶ added in v1.18.0
RawTerminalHintLines renders err's refusal guidance for a terminal that may be in raw mode, where a bare newline leaves the cursor where it stood: one "Hint:" line per RefusalNextActions entry, each ending in \r\n.
func ReadInput ¶ added in v1.20.0
ReadInput reads one line from stdin after promptText, or returns the exit-1 failure on no input.
func ReadInputWithDefault ¶ added in v1.20.0
func ReadIntInput ¶ added in v1.20.0
func ReadRequiredInput ¶ added in v1.20.0
ReadRequiredInput is ReadInput that asks again on an empty line.
func ReadRequiredIntInput ¶ added in v1.20.0
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 RejectUnknownSubcommand ¶ added in v1.20.0
func RejectUnknownSubcommand(notes ...string) cobra.PositionalArgs
func RemoteFileName ¶ added in v1.6.0
RemoteFileName returns the final path component for a remote file path.
func RemotePathBase ¶ added in v1.20.0
RemotePathBase returns a remote path's last element by the server's rules: a Windows server also splits on a backslash, which a Linux or macOS file name may hold.
func RemotePathDir ¶ added in v1.20.0
RemotePathDir returns the directory holding a remote path's last element by the server's rules.
func ReportNoChanges ¶ added in v1.20.0
ReportNoChanges prints the no-change notice and returns true when err is ErrNoChanges; the caller then ends on exit 0.
func RequireSubcommand ¶ added in v1.15.0
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 SanitizeTerminalBlockKeepingTabs ¶ added in v1.20.0
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 SanitizeTerminalOneLine ¶ added in v1.20.0
SanitizeTerminalOneLine fits free text, such as an approver's reason or an agent's tunnel failure, onto one terminal line: line breaks, tabs and runs of space become one space. Whitespace is folded before sanitizing, since SanitizeTerminalText drops \t, \r and \n and would run the words on either side together.
func SanitizeTerminalText ¶ added in v1.9.2
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 ServiceTokenAccountMessage ¶ added in v1.20.0
ServiceTokenAccountMessage describes the fixed account on a service token's ACL.
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 SignalApprovalPending ¶ added in v1.20.0
func SignalApprovalPending(err error, fields localsignal.Fields)
func SignalFields ¶ added in v1.20.0
func SignalFields(err error) localsignal.Fields
func SignalPaused ¶ added in v1.20.0
func SignalPaused(err error)
SignalPaused applies to any operation, using only the structured pause code.
func SignalRefusal ¶ added in v1.20.0
func SignalRefusal(err error)
SignalRefusal is called only by command execution and file transfer paths. Error sinks own pause signals so one pause never increments the folded count twice.
func SignalResponse ¶ added in v1.20.0
func SignalResponse(status int, body []byte, sources ...SignalOriginSource)
SignalResponse handles a pause on raw responses without classifying raw API calls as commands.
func SplitAndTrim ¶ added in v1.4.4
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
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 WaitForTokenRefreshes ¶ added in v1.20.0
func WaitForTokenRefreshes()
WaitForTokenRefreshes covers a 10s config lock wait, an 8s grant and 1s for saving.
func WarnTerminalTextAltered ¶ added in v1.11.2
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 WithExitError ¶ added in v1.20.0
WithExitError wraps a RunE that returns ExitError. Cobra prints nothing for an ExitError, which cmd.Execute prints, but keeps its error line and usage for a flag or pre-run error.
func WithHTTPStatus ¶ added in v1.18.0
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 WithSignalFields ¶ added in v1.20.0
func WithSignalFields(err error, fields localsignal.Fields, sources ...SignalOriginSource) error
func WorkSessionExitError ¶ added in v1.20.0
WorkSessionExitError returns the exit-3 gate diagnostic, or nil when err is not a WorkSession gate refusal. target is what the operation names: a cluster for OperationKube, a server otherwise.
func WorkSessionReason ¶ added in v1.20.2
WorkSessionReason is the diagnostic's reason line for a gate code, or "" for any other code.
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 cannot start.
- Once the pager starts, it is the sole output path. WriteToPager reports flush errors on stderr. IOStreams.PagerWithError returns them to the caller.
Types ¶
type AnnotatedText ¶ added in v1.20.0
type AnnotatedText struct {
// contains filtered or unexported fields
}
AnnotatedText is a list cell whose table text adds a note to the value JSON carries, so a table can say what the value leaves out without changing what a script reads.
func Annotate ¶ added in v1.20.0
func Annotate(value, tableText string) AnnotatedText
func (AnnotatedText) MarshalJSON ¶ added in v1.20.0
func (t AnnotatedText) MarshalJSON() ([]byte, error)
func (AnnotatedText) String ¶ added in v1.20.0
func (t AnnotatedText) String() string
type BatchError ¶ added in v1.18.0
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
// OnWorkSessionRefused settles a WorkSession gate refusal, at most once. resend runs RetryOperation again;
// failure replaces the refusal, and neither leaves the refusal as the result.
OnWorkSessionRefused func(serverName string, err error) (resend bool, failure 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 ExitError ¶ added in v1.20.0
type ExitError struct {
Code int
// contains filtered or unexported fields
}
ExitError is a failure a RunE command returns: cmd.Execute prints it with PrintExitError and exits with Code. Build it with a constructor; NewSilentExitError is the one that prints nothing.
type Failure ¶ added in v1.18.0
type Failure struct {
ExitCode int
ErrorCode string
Err error
Message string
Operation string
RemoteExitCode *int
Partial *PartialInfo
NextActions []NextAction
HTTPStatus int
RetryAfter time.Duration
Server map[string]any
}
Failure describes a non-zero exit whose table-mode output the caller keeps; only the --output json envelope is built here. An empty ErrorCode is classified from Err.
type HeldRequest ¶ added in v1.20.0
type HeldRequest struct {
ApprovalRequest string `json:"approval_request"`
ExpiresAt *time.Time `json:"expires_at"` // Nil when the server knows no deadline.
StatusPath string `json:"status_path"`
}
HeldRequest is the command detail's open sudo approval. Null or an absent key on an older server decodes to nil.
func (*HeldRequest) Expired ¶ added in v1.20.0
func (h *HeldRequest) Expired() bool
Expired reports whether the deadline has passed, not when approval occurred.
type IOStreams ¶ added in v1.20.0
type IOStreams struct {
Out io.Writer
ErrOut io.Writer
// ColorEnabled gates ANSI codes; it follows ErrOut, where colored messages go, so a pipe
// or a redirected log carries none, and NO_COLOR turns it off.
ColorEnabled bool
// contains filtered or unexported fields
}
IOStreams is where a command writes: data to Out, messages to ErrOut, in the --output format it holds. Commands take one through their constructor so a test can hand in buffers.
func SystemIOStreams ¶ added in v1.20.0
func SystemIOStreams() *IOStreams
SystemIOStreams writes to whatever os.Stdout and os.Stderr are at the time of each write, under the format the --output flag set.
func TestIOStreams ¶ added in v1.20.0
TestIOStreams returns streams writing to the two buffers, in table format with no color.
func (*IOStreams) AgentInputError ¶ added in v1.21.0
AgentInputError refuses a local prompt in agent mode. Pass the flag or argument that supplies the input.
func (*IOStreams) AgentMode ¶ added in v1.21.0
AgentMode reports whether the CLI identified an agent and JSON is effective.
func (*IOStreams) CommandExitError ¶ added in v1.21.0
CommandExitError converts a Cobra failure after the invocation's format has been resolved.
func (*IOStreams) FprintExitError ¶ added in v1.20.0
FprintExitError writes e to w in s's format.
func (*IOStreams) FprintFailureJSON ¶ added in v1.21.0
FprintFailureJSON writes the failure and preserves an explicit JSON output flag in its action.
func (*IOStreams) IsJSON ¶ added in v1.20.0
IsJSON reports whether these streams print --output json.
func (*IOStreams) ListenerReady ¶ added in v1.21.0
ListenerReady reports the bound address on stderr once the listener is available.
func (*IOStreams) NewParseExitError ¶ added in v1.20.0
NewParseExitError is the package-level NewParseExitError, applying format to s.
func (*IOStreams) OutIsTerminal ¶ added in v1.21.0
OutIsTerminal reports whether Out writes to a terminal.
func (*IOStreams) OutputFormat ¶ added in v1.20.0
OutputFormat is the --output value these streams print in.
func (*IOStreams) Pager ¶ added in v1.20.0
Pager returns where a table goes: through the process pager when Out is the process's stdout writer, and straight to Out for any other writer. The flush warns on stderr if it fails.
func (*IOStreams) PagerWithError ¶ added in v1.21.0
PagerWithError is Pager with a flush function that reports stdout write errors and unsuccessful pager exits.
func (*IOStreams) PartialTableExitError ¶ added in v1.20.0
PartialTableExitError is the package-level PartialTableExitError on s.
func (*IOStreams) PrintCommandRunning ¶ added in v1.21.0
PrintCommandRunning reports a command that has not finished: a {"status":"running", ...} envelope on stdout under --output json, else the status and a check-later line on stderr. It returns an error only when stdout took neither the envelope nor its fallback, since exit 0 with an empty stdout would read as a finished command with no output.
func (*IOStreams) PrintExitError ¶ added in v1.20.0
PrintExitError writes e to s.ErrOut in s's format, as cmd.Execute prints a failure.
func (*IOStreams) PrintHeader ¶ added in v1.20.0
PrintHeader writes header to s.ErrOut, above the data s.Out carries.
func (*IOStreams) PrintJson ¶ added in v1.20.0
PrintJson prints body to s.Out as indented JSON, or returns the exit-1 failure when body is not JSON.
func (*IOStreams) PrintPendingApproval ¶ added in v1.20.0
func (s *IOStreams) PrintPendingApproval(message, requestID string, retry NextAction, extra ...NextAction)
PrintPendingApproval is the package-level PrintPendingApproval on s.
func (*IOStreams) PrintPendingApprovalWithError ¶ added in v1.20.2
func (s *IOStreams) PrintPendingApprovalWithError(message, requestID string, cause error, retry NextAction, extra ...NextAction)
PrintPendingApprovalWithError preserves the cause's server fields in the pending envelope.
func (*IOStreams) PrintPurposeAccepted ¶ added in v1.20.0
PrintPurposeAccepted is the package-level PrintPurposeAccepted on s.
func (*IOStreams) PrintPurposeDemand ¶ added in v1.20.0
PrintPurposeDemand is the package-level PrintPurposeDemand on s.
func (*IOStreams) PrintPurposeRefused ¶ added in v1.20.0
PrintPurposeRefused is the package-level PrintPurposeRefused on s.
func (*IOStreams) PrintRefusalHints ¶ added in v1.20.0
PrintRefusalHints is the package-level PrintRefusalHints in s's color.
func (*IOStreams) PrintTable ¶ added in v1.20.0
PrintTable prints a slice of row structs to s.Out as a table, or as JSON under --output json. It returns the exit-1 failure when slice is not a slice or does not marshal.
func (*IOStreams) Progress ¶ added in v1.21.0
Progress reports intermediate activity to a human caller.
func (*IOStreams) RawTerminalHintLines ¶ added in v1.20.0
RawTerminalHintLines is the package-level RawTerminalHintLines in s's color.
func (*IOStreams) ReportNoChanges ¶ added in v1.20.0
ReportNoChanges is the package-level ReportNoChanges on s.
func (*IOStreams) ResolveOutput ¶ added in v1.21.0
ResolveOutput applies the highest valid input and returns a usage error if the winning input is invalid.
func (*IOStreams) SetExplicitOutputFormat ¶ added in v1.21.0
SetExplicitOutputFormat applies the value the user supplied with --output.
func (*IOStreams) SetOutputDefaults ¶ added in v1.21.0
SetOutputDefaults records the invocation's environment and caller before parsing.
func (*IOStreams) SetOutputFormat ¶ added in v1.20.0
SetOutputFormat applies an --output value, refusing anything but table or json as a usage error.
func (*IOStreams) WarnTerminalTextAltered ¶ added in v1.20.0
WarnTerminalTextAltered is the package-level WarnTerminalTextAltered in s's color.
type JSONErrorEnvelope ¶ added in v1.6.0
type JSONErrorEnvelope[T any] struct { OK bool `json:"ok"` ExitCode int `json:"exit_code"` ErrorCode string `json:"error_code"` Message string `json:"message"` Command string `json:"command,omitempty"` Reason string `json:"reason,omitempty"` Context T `json:"context"` HTTPStatus int `json:"http_status,omitempty"` RetryAfter int `json:"retry_after,omitempty"` Server map[string]any `json:"server,omitempty"` RemoteExitCode *int `json:"remote_exit_code,omitempty"` Partial *PartialInfo `json:"partial,omitempty"` NextActions []NextAction `json:"next_actions,omitempty"` }
JSONErrorEnvelope is the --output json failure line. Fields are additive only; exit_code and error_code are always present.
type NextAction ¶ added in v1.9.0
type NextAction struct {
Command string `json:"command,omitempty"`
Description string `json:"description,omitempty"`
Argv []string `json:"argv,omitempty"`
}
NextAction is one actionable follow-up: Command is a runnable command with no inline comment, for machine consumers, and Description the human hint. Either may be empty, as a guidance-only pointer carries no command.
func RefusalNextActions ¶ added in v1.18.0
func RefusalNextActions(err error) []NextAction
RefusalNextActions returns server hints, status paths, retry delays, held approvals and local follow-up actions. A refusal's "next" is text only under an API token because that path may reject it.
func (NextAction) PlainText ¶ added in v1.9.0
func (a NextAction) PlainText() string
PlainText renders the action as a human-facing line: "command # description", or just the command or description when the other is empty. Sanitized here because its callers write to the terminal outside the Cli* helpers and call sites interpolate server-returned ids into Command; the JSON envelope marshals the fields themselves and escapes via escapeJSONControls instead.
type PartialInfo ¶ added in v1.18.0
type PartialInfo struct {
Count int `json:"count"`
}
type RefusalOutcome ¶ added in v1.21.0
type RefusalOutcome struct {
// contains filtered or unexported fields
}
RefusalOutcome holds the validated parts of an issued reason and next step.
func ParseRefusalOutcome ¶ added in v1.21.0
func ParseRefusalOutcome(fields map[string]any, status int) RefusalOutcome
ParseRefusalOutcome reads a workspace refusal. A validated wait handle is an issued step even when the response lacks a usable code or reason.
func (RefusalOutcome) HasStep ¶ added in v1.21.0
func (o RefusalOutcome) HasStep() bool
HasStep reports whether the workspace supplied a paired step or a valid command wait.
func (RefusalOutcome) ProjectFields ¶ added in v1.21.0
func (o RefusalOutcome) ProjectFields(fields map[string]any, status int)
ProjectFields replaces the outcome fields in a refusal with their allowlisted values.
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 SignalOriginSource ¶ added in v1.20.0
type SignalOriginSource interface {
LocalSignalOrigin() localsignal.ConsoleOrigin
}
type Spinner ¶ added in v1.0.0
type Spinner struct {
// contains filtered or unexported fields
}
Spinner displays an animated spinner with a message. When stderr is not a terminal (e.g., piped or redirected), the spinner animation is replaced with a single static progress line so logs stay clean without ANSI artifacts.
func NewSpinner ¶ added in v1.0.0
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.
type Timestamp ¶ added in v1.20.0
type Timestamp struct {
// contains filtered or unexported fields
}
Timestamp is a list cell: its table text in a table, RFC 3339 UTC or null in JSON, or the server's string as sent when it could not be parsed.
func OptionalTimestamp ¶ added in v1.20.0
OptionalTimestamp is an absolute time with no table text, null in JSON when t is nil.
func ParseLocalTimestamp ¶ added in v1.20.0
ParseLocalTimestamp is ParseTimestamp with the table text in the local zone (FormatTimestamp).
func ParseTimestamp ¶ added in v1.20.0
ParseTimestamp shows a server's time string as sent in a table. JSON gets it in UTC, null when empty, or as sent when it is not RFC 3339.
func RelativeTime ¶ added in v1.20.0
func (Timestamp) MarshalJSON ¶ added in v1.20.0
type TruncatedText ¶ added in v1.20.0
type TruncatedText struct {
// contains filtered or unexported fields
}
TruncatedText is a list cell cut to width in a table and whole in JSON.
func Truncate ¶ added in v1.20.0
func Truncate(s string, width int) TruncatedText
func (TruncatedText) MarshalJSON ¶ added in v1.20.0
func (t TruncatedText) MarshalJSON() ([]byte, error)
func (TruncatedText) String ¶ added in v1.20.0
func (t TruncatedText) String() string
Source Files
¶
- browser.go
- cell.go
- color.go
- command_running.go
- error.go
- error_codes.go
- error_envelope.go
- error_handler.go
- exit_error.go
- failure_report.go
- file_mode.go
- file_replace_unix.go
- file_save.go
- held.go
- hidden.go
- hook_error.go
- iostreams.go
- jwt.go
- local_signal.go
- log.go
- mfa_required.go
- output.go
- pager.go
- pending_approval.go
- poll.go
- process_exit.go
- prompt.go
- purpose_demand.go
- redact.go
- refresh_exit.go
- refusal_hint.go
- refusal_outcome.go
- remote_path.go
- spinner.go
- ssh_parser.go
- stderr_line.go
- unzip_path.go
- utils.go
- version.go
- worksession_error.go